changeset 11984:35fc0c239eb9

Merge
author asaha
date Mon, 08 Aug 2016 15:29:16 -0700
parents c9699355abb3 edc6bcef9ec2
children 684fa25fc7eb
files .hgtags
diffstat 286 files changed, 20543 insertions(+), 2225 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Thu Aug 04 18:37:15 2016 +0300
+++ b/.hgtags	Mon Aug 08 15:29:16 2016 -0700
@@ -633,4 +633,16 @@
 de1d09f09e571e38afdf1fb72984ec210e7c19e6 jdk8u111-b02
 1818c0df435a5e4b8b18dd82de38a03f30714d55 jdk8u111-b03
 710f0c95444deb36b422f449f422d925a72f6b2c jdk8u111-b04
+d689f7b806c89e535f784ba94bea1ae129ee0f19 jdk8u111-b05
+6c822cce832523a5aee9632e28065f0c302187ed jdk8u111-b06
+1afe84012d643b4092dbf25f1cbb761508c19ed2 jdk8u111-b07
+9760ea9a63c0d48956392256bb7769ab40f2a2f7 jdk8u111-b08
+47e20a90bdbb2327289e330606b73a9fe4dc857e jdk8u112-b00
+96393e490afd4acba5b92c5ede68dc9bbb60a38e jdk8u112-b01
+b44d695f738baba091370828b84ae2c4cd715c1b jdk8u112-b02
+1af2eacbc17462f080d70e71c53e073ab0640f32 jdk8u112-b03
+a11ab21bb7991509846e0e45ad3792896c4fe98c jdk8u112-b04
+ecb2bae7905e2fd6f9b837521ee82a2cbb34602c jdk8u112-b06
+c66f5a825a0f0b5fb833bc7f50f327aec43e213b jdk8u112-b07
+89375f5c2c4c2bdc2340d7af1977dc1607908840 jdk8u112-b08
 ab5ff8f1e52c5e3ca02e988f4d978af63ceca5b8 jdk8u121-b00
--- a/LICENSE	Thu Aug 04 18:37:15 2016 +0300
+++ b/LICENSE	Mon Aug 08 15:29:16 2016 -0700
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc., 59
-    Temple Place, Suite 330, Boston, MA 02111-1307 USA
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
 Also add information on how to contact you by electronic and paper mail.
 
--- a/make/data/tzdata/VERSION	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/VERSION	Mon Aug 08 15:29:16 2016 -0700
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2016d
+tzdata2016f
--- a/make/data/tzdata/africa	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/africa	Mon Aug 08 15:29:16 2016 -0700
@@ -366,6 +366,12 @@
 # decision to abandon DST permanently.  See Ahram Online 2015-04-24.
 # http://english.ahram.org.eg/NewsContent/1/64/128509/Egypt/Politics-/Sisi-cancels-daylight-saving-time-in-Egypt.aspx
 
+# From Steffen Thorsen (2016-04-29):
+# Egypt will have DST from July 7 until the end of October....
+# http://english.ahram.org.eg/NewsContentP/1/204655/Egypt/Daylight-savings-time-returning-to-Egypt-on--July.aspx
+# From Mina Samuel (2016-07-04):
+# Egyptian government took the decision to cancel the DST,
+
 Rule	Egypt	2008	only	-	Aug	lastThu	24:00	0	-
 Rule	Egypt	2009	only	-	Aug	20	24:00	0	-
 Rule	Egypt	2010	only	-	Aug	10	24:00	0	-
@@ -881,11 +887,11 @@
 Rule	Morocco	2010	only	-	May	 2	 0:00	1:00	S
 Rule	Morocco	2010	only	-	Aug	 8	 0:00	0	-
 Rule	Morocco	2011	only	-	Apr	 3	 0:00	1:00	S
-Rule	Morocco	2011	only	-	Jul	31	 0	0	-
+Rule	Morocco	2011	only	-	Jul	31	 0:00	0	-
 Rule	Morocco	2012	2013	-	Apr	lastSun	 2:00	1:00	S
-Rule	Morocco	2012	only	-	Sep	30	 3:00	0	-
 Rule	Morocco	2012	only	-	Jul	20	 3:00	0	-
 Rule	Morocco	2012	only	-	Aug	20	 2:00	1:00	S
+Rule	Morocco	2012	only	-	Sep	30	 3:00	0	-
 Rule	Morocco	2013	only	-	Jul	 7	 3:00	0	-
 Rule	Morocco	2013	only	-	Aug	10	 2:00	1:00	S
 Rule	Morocco	2013	max	-	Oct	lastSun	 3:00	0	-
--- a/make/data/tzdata/antarctica	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/antarctica	Mon Aug 08 15:29:16 2016 -0700
@@ -36,7 +36,7 @@
 #
 # Except for the French entries,
 # I made up all time zone abbreviations mentioned here; corrections welcome!
-# FORMAT is 'zzz' and GMTOFF is 0 for locations while uninhabited.
+# FORMAT is '-00' and GMTOFF is 0 for locations while uninhabited.
 
 # Argentina - year-round bases
 # Belgrano II, Confin Coast, -770227-0343737, since 1972-02-05
@@ -90,22 +90,22 @@
 # http://www.timeanddate.com/news/time/antartica-time-changes-2010.html
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/Casey	0	-	zzz	1969
+Zone Antarctica/Casey	0	-	-00	1969
 			8:00	-	AWST	2009 Oct 18  2:00
 						# Australian Western Std Time
 			11:00	-	CAST	2010 Mar  5  2:00  # Casey Time
 			8:00	-	AWST	2011 Oct 28  2:00
 			11:00	-	CAST	2012 Feb 21 17:00u
 			8:00	-	AWST
-Zone Antarctica/Davis	0	-	zzz	1957 Jan 13
+Zone Antarctica/Davis	0	-	-00	1957 Jan 13
 			7:00	-	DAVT	1964 Nov    # Davis Time
-			0	-	zzz	1969 Feb
+			0	-	-00	1969 Feb
 			7:00	-	DAVT	2009 Oct 18  2:00
 			5:00	-	DAVT	2010 Mar 10 20:00u
 			7:00	-	DAVT	2011 Oct 28  2:00
 			5:00	-	DAVT	2012 Feb 21 20:00u
 			7:00	-	DAVT
-Zone Antarctica/Mawson	0	-	zzz	1954 Feb 13
+Zone Antarctica/Mawson	0	-	-00	1954 Feb 13
 			6:00	-	MAWT	2009 Oct 18  2:00 # Mawson Time
 			5:00	-	MAWT
 # References:
@@ -160,7 +160,7 @@
 #	fishing stations operated variously 1819/1931
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Indian/Kerguelen	0	-	zzz	1950 # Port-aux-Français
+Zone Indian/Kerguelen	0	-	-00	1950 # Port-aux-Français
 			5:00	-	TFT	# ISO code TF Time
 #
 # year-round base in the main continent
@@ -171,9 +171,9 @@
 # It was destroyed by fire on 1952-01-14.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/DumontDUrville 0 -	zzz	1947
+Zone Antarctica/DumontDUrville 0 -	-00	1947
 			10:00	-	PMT	1952 Jan 14 # Port-Martin Time
-			0	-	zzz	1956 Nov
+			0	-	-00	1956 Nov
 			10:00	-	DDUT	# Dumont-d'Urville Time
 
 # France & Italy - year-round base
@@ -199,7 +199,7 @@
 # was established on 1957-01-29.  Since Syowa station is still the main
 # station of Japan, it's appropriate for the principal location.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/Syowa	0	-	zzz	1957 Jan 29
+Zone Antarctica/Syowa	0	-	-00	1957 Jan 29
 			3:00	-	SYOT	# Syowa Time
 # See:
 # NIPR Antarctic Research Activities (1999-08-17)
@@ -249,7 +249,7 @@
 # Remove the following line when uncommenting the above '#Rule' lines.
 Rule	Troll	2004	max	-	Oct	lastSun	1:00u	0:00	UTC
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/Troll	0	-	zzz	2005 Feb 12
+Zone Antarctica/Troll	0	-	-00	2005 Feb 12
 			0:00	Troll	%s
 
 # Poland - year-round base
@@ -290,7 +290,7 @@
 # happened to be during their visit.  So we still don't really know what time
 # it is at Vostok.  But we'll guess UTC+6.
 #
-Zone Antarctica/Vostok	0	-	zzz	1957 Dec 16
+Zone Antarctica/Vostok	0	-	-00	1957 Dec 16
 			6:00	-	VOST	# Vostok time
 
 # S Africa - year-round bases
@@ -323,7 +323,7 @@
 # <http://webexhibits.org/daylightsaving/g.html> says Rothera is -03 all year.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/Rothera	0	-	zzz	1976 Dec  1
+Zone Antarctica/Rothera	0	-	-00	1976 Dec  1
 			-3:00	-	ROTT	# Rothera time
 
 # Uruguay - year round base
--- a/make/data/tzdata/asia	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/asia	Mon Aug 08 15:29:16 2016 -0700
@@ -169,7 +169,7 @@
 			3:00	-	BAKT	1957 Mar    # Baku Time
 			4:00 RussiaAsia BAK%sT	1991 Mar 31  2:00s
 			3:00	1:00	BAKST	1991 Aug 30 # independence
-			3:00 RussiaAsia	AZ%sT	1992 Sep lastSat 23:00
+			3:00 RussiaAsia	AZ%sT	1992 Sep lastSun  2:00s
 			4:00	-	AZT	1996     # Azerbaijan Time
 			4:00	EUAsia	AZ%sT	1997
 			4:00	Azer	AZ%sT
--- a/make/data/tzdata/australasia	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/australasia	Mon Aug 08 15:29:16 2016 -0700
@@ -266,11 +266,11 @@
 # will produce a binary file with an [A]EST-type as the first 32-bit type;
 # this is required for correct handling of times before 1916 by
 # pre-2013 versions of localtime.
-Zone Antarctica/Macquarie 0	-	zzz	1899 Nov
+Zone Antarctica/Macquarie 0	-	-00	1899 Nov
 			10:00	-	AEST	1916 Oct  1  2:00
 			10:00	1:00	AEDT	1917 Feb
 			10:00	Aus	AE%sT	1919 Apr  1  0:00s
-			0	-	zzz	1948 Mar 25
+			0	-	-00	1948 Mar 25
 			10:00	Aus	AE%sT	1967
 			10:00	AT	AE%sT	2010 Apr  4  3:00
 			11:00	-	MIST	# Macquarie I Standard Time
--- a/make/data/tzdata/europe	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/europe	Mon Aug 08 15:29:16 2016 -0700
@@ -778,6 +778,14 @@
 			1:00	EU	CE%sT
 
 # Belarus
+#
+# From Stepan Golosunov (2016-07-02):
+# http://www.lawbelarus.com/repub/sub30/texf9611.htm
+# (Act of the Cabinet of Ministers of the Republic of Belarus from
+# 1992-03-25 No. 157) ... says clocks were to be moved forward at 2:00
+# on last Sunday of March and backward at 3:00 on last Sunday of September
+# (the same as previous USSR and contemporary Russian regulations).
+#
 # From Yauhen Kharuzhy (2011-09-16):
 # By latest Belarus government act Europe/Minsk timezone was changed to
 # GMT+3 without DST (was GMT+2 with DST).
@@ -801,9 +809,6 @@
 			1:00	C-Eur	CE%sT	1944 Jul  3
 			3:00	Russia	MSK/MSD	1990
 			3:00	-	MSK	1991 Mar 31  2:00s
-			2:00	1:00	EEST	1991 Sep 29  2:00s
-			2:00	-	EET	1992 Mar 29  0:00s
-			2:00	1:00	EEST	1992 Sep 27  0:00s
 			2:00	Russia	EE%sT	2011 Mar 27  2:00s
 			3:00	-	FET	2014 Oct 26  1:00s
 			3:00	-	MSK
@@ -2746,14 +2751,22 @@
 # Asia/Novosibirsk covers:
 # 54	RU-NVS	Novosibirsk Oblast
 
+# From Stepan Golosunov (2016-05-30):
+# http://asozd2.duma.gov.ru/main.nsf/(Spravka)?OpenAgent&RN=1085784-6
+# moves Novosibirsk oblast from UTC+6 to UTC+7.
+# From Stepan Golosunov (2016-07-04):
+# The law was signed yesterday and published today on
+# http://publication.pravo.gov.ru/Document/View/0001201607040064
+
 Zone Asia/Novosibirsk	 5:31:40 -	LMT	1919 Dec 14  6:00
-			 6:00	-	NOVT	1930 Jun 21 # Novosibirsk Time
-			 7:00	Russia	NOV%sT	1991 Mar 31  2:00s
-			 6:00	Russia	NOV%sT	1992 Jan 19  2:00s
-			 7:00	Russia	NOV%sT	1993 May 23 # say Shanks & P.
-			 6:00	Russia	NOV%sT	2011 Mar 27  2:00s
-			 7:00	-	NOVT	2014 Oct 26  2:00s
-			 6:00	-	NOVT
+			 6:00	-	+06	1930 Jun 21
+			 7:00	Russia	+07/+08	1991 Mar 31  2:00s
+			 6:00	Russia	+06/+07	1992 Jan 19  2:00s
+			 7:00	Russia	+07/+08	1993 May 23 # say Shanks & P.
+			 6:00	Russia	+06/+07	2011 Mar 27  2:00s
+			 7:00	-	+07	2014 Oct 26  2:00s
+			 6:00	-	+06	2016 Jul 24  2:00s
+			 7:00	-	+07
 
 # From Paul Eggert (2016-03-18):
 # Asia/Tomsk covers:
@@ -2794,6 +2807,9 @@
 # approved by the Federation Council on 2016-04-20, signed by the President and
 # published as a law around 2016-04-26.
 
+# From Matt Johnson (2016-04-26):
+# http://publication.pravo.gov.ru/Document/View/0001201604260048
+
 Zone	Asia/Tomsk	 5:39:51 -	LMT	1919 Dec 22
 			 6:00	-	+06	1930 Jun 21
 			 7:00	Russia	+07/+08	1991 Mar 31  2:00s
@@ -2833,14 +2849,12 @@
 # realigning itself with KRAT.
 
 Zone Asia/Novokuznetsk	 5:48:48 -	LMT	1924 May  1
-			 6:00	-	KRAT	1930 Jun 21 # Krasnoyarsk Time
-			 7:00	Russia	KRA%sT	1991 Mar 31  2:00s
-			 6:00	Russia	KRA%sT	1992 Jan 19  2:00s
-			 7:00	Russia	KRA%sT	2010 Mar 28  2:00s
-			 6:00	Russia	NOV%sT	2011 Mar 27  2:00s # Novosibirsk
-			 7:00	-	NOVT	2014 Oct 26  2:00s
-			 7:00	-	KRAT	# Krasnoyarsk Time
-
+			 6:00	-	+06	1930 Jun 21
+			 7:00	Russia	+07/+08	1991 Mar 31  2:00s
+			 6:00	Russia	+06/+07	1992 Jan 19  2:00s
+			 7:00	Russia	+07/+08	2010 Mar 28  2:00s
+			 6:00	Russia	+06/+07	2011 Mar 27  2:00s
+			 7:00	-	+07
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
 # Asia/Krasnoyarsk covers...
--- a/make/data/tzdata/northamerica	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/northamerica	Mon Aug 08 15:29:16 2016 -0700
@@ -2214,39 +2214,39 @@
 Rule	NT_YK	1987	2006	-	Apr	Sun>=1	2:00	1:00	D
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # aka Panniqtuuq
-Zone America/Pangnirtung 0	-	zzz	1921 # trading post est.
+Zone America/Pangnirtung 0	-	-00	1921 # trading post est.
 			-4:00	NT_YK	A%sT	1995 Apr Sun>=1  2:00
 			-5:00	Canada	E%sT	1999 Oct 31  2:00
 			-6:00	Canada	C%sT	2000 Oct 29  2:00
 			-5:00	Canada	E%sT
 # formerly Frobisher Bay
-Zone America/Iqaluit	0	-	zzz	1942 Aug # Frobisher Bay est.
+Zone America/Iqaluit	0	-	-00	1942 Aug # Frobisher Bay est.
 			-5:00	NT_YK	E%sT	1999 Oct 31  2:00
 			-6:00	Canada	C%sT	2000 Oct 29  2:00
 			-5:00	Canada	E%sT
 # aka Qausuittuq
-Zone America/Resolute	0	-	zzz	1947 Aug 31 # Resolute founded
+Zone America/Resolute	0	-	-00	1947 Aug 31 # Resolute founded
 			-6:00	NT_YK	C%sT	2000 Oct 29  2:00
 			-5:00	-	EST	2001 Apr  1  3:00
 			-6:00	Canada	C%sT	2006 Oct 29  2:00
 			-5:00	-	EST	2007 Mar 11  3:00
 			-6:00	Canada	C%sT
 # aka Kangiqiniq
-Zone America/Rankin_Inlet 0	-	zzz	1957 # Rankin Inlet founded
+Zone America/Rankin_Inlet 0	-	-00	1957 # Rankin Inlet founded
 			-6:00	NT_YK	C%sT	2000 Oct 29  2:00
 			-5:00	-	EST	2001 Apr  1  3:00
 			-6:00	Canada	C%sT
 # aka Iqaluktuuttiaq
-Zone America/Cambridge_Bay 0	-	zzz	1920 # trading post est.?
+Zone America/Cambridge_Bay 0	-	-00	1920 # trading post est.?
 			-7:00	NT_YK	M%sT	1999 Oct 31  2:00
 			-6:00	Canada	C%sT	2000 Oct 29  2:00
 			-5:00	-	EST	2000 Nov  5  0:00
 			-6:00	-	CST	2001 Apr  1  3:00
 			-7:00	Canada	M%sT
-Zone America/Yellowknife 0	-	zzz	1935 # Yellowknife founded?
+Zone America/Yellowknife 0	-	-00	1935 # Yellowknife founded?
 			-7:00	NT_YK	M%sT	1980
 			-7:00	Canada	M%sT
-Zone America/Inuvik	0	-	zzz	1953 # Inuvik founded
+Zone America/Inuvik	0	-	-00	1953 # Inuvik founded
 			-8:00	NT_YK	P%sT	1979 Apr lastSun  2:00
 			-7:00	NT_YK	M%sT	1980
 			-7:00	Canada	M%sT
--- a/make/data/tzdata/southamerica	Thu Aug 04 18:37:15 2016 +0300
+++ b/make/data/tzdata/southamerica	Mon Aug 08 15:29:16 2016 -0700
@@ -1332,7 +1332,7 @@
 # Palmer used to be supplied from Argentina.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone Antarctica/Palmer	0	-	zzz	1965
+Zone Antarctica/Palmer	0	-	-00	1965
 			-4:00	Arg	AR%sT	1969 Oct  5
 			-3:00	Arg	AR%sT	1982 May
 			-4:00	Chile	CL%sT
@@ -1782,16 +1782,16 @@
 # https://actualidad.rt.com/actualidad/204758-venezuela-modificar-huso-horario-sequia-elnino
 #
 # From Paul Eggert (2016-04-15):
-# Clocks advance 30 minutes on 2016-05-01 at 02:30. See:
-# Barboza AD. Huso horario en Venezuela volverá a 4 horas menos con
-# respecto al "Greenwich". Panorama 2016-04-15 12:20 -0430.
-# http://www.panorama.com.ve/ciudad/Huso-horario-en-Venezuela-volvera-a-4-horas-menos-con-respecto-al-Greenwich-20160415-0032.html
-#
+# Clocks advance 30 minutes on 2016-05-01 at 02:30....
 # "'Venezuela's new time-zone: hours without light, hours without water,
-# hours of presidential broadcasts, hours of lines," quipped comedian
-# Jean Mary Curro ...". See: Cawthorne A, Kai D. Venezuela scraps
+# hours of presidential broadcasts, hours of lines,' quipped comedian
+# Jean Mary Curró ...". See: Cawthorne A, Kai D. Venezuela scraps
 # half-hour time difference set by Chavez. Reuters 2016-04-15 14:50 -0400
 # http://www.reuters.com/article/us-venezuela-timezone-idUSKCN0XC2BE
+#
+# From Matt Johnson (2016-04-20):
+# ... published in the official Gazette [2016-04-18], here:
+# http://historico.tsj.gob.ve/gaceta_ext/abril/1842016/E-1842016-4551.pdf
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	America/Caracas	-4:27:44 -	LMT	1890
--- a/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,8 @@
 
 package sun.lwawt.macosx;
 
+import sun.lwawt.LWWindowPeer;
+
 import java.awt.*;
 import java.beans.*;
 import java.lang.reflect.Field;
@@ -421,6 +423,8 @@
     }
 
     public static AccessibleAction getAccessibleAction(final Accessible a, final Component c) {
+        if (a == null) return null;
+
         return invokeAndWait(new Callable<AccessibleAction>() {
             public AccessibleAction call() throws Exception {
                 final AccessibleContext ac = a.getAccessibleContext();
@@ -667,4 +671,28 @@
             }
         }, c);
     }
+
+    /**
+     * @return AWTView ptr, a peer of the CPlatformView associated with the toplevel container of the Accessible, if any
+     */
+    private static long getAWTView(Accessible a) {
+        Accessible ax = CAccessible.getSwingAccessible(a);
+        if (!(ax instanceof Component)) return 0;
+
+        return invokeAndWait(new Callable<Long>() {
+            public Long call() throws Exception {
+                Component cont = (Component) ax;
+                while (cont != null && !(cont instanceof Window)) {
+                    cont = cont.getParent();
+                }
+                if (cont != null) {
+                    LWWindowPeer peer = (LWWindowPeer) cont.getPeer();
+                    if (peer != null) {
+                        return ((CPlatformWindow) peer.getPlatformWindow()).getContentView().getAWTView();
+                    }
+                }
+                return 0L;
+            }
+        }, (Component)ax);
+    }
 }
--- a/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -264,6 +264,8 @@
                 final double localY = boundsUnion.getY();
 
                 final Point componentLocation = ac.getAccessibleComponent().getLocationOnScreen();
+                if (componentLocation == null) return ret;
+
                 final double screenX = componentLocation.getX() + localX;
                 final double screenY = componentLocation.getY() + localY;
 
--- a/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Mon Aug 08 15:29:16 2016 -0700
@@ -34,6 +34,7 @@
 import java.awt.event.InputEvent;
 import java.awt.event.MouseWheelEvent;
 import java.awt.event.KeyEvent;
+import java.util.Locale;
 
 /**
  * Translates NSEvents/NPCocoaEvents into AWT events.
@@ -171,6 +172,16 @@
                 }
             }
 
+            // If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
+            // input to latin letters.
+            // It is necessary to use testCharIgnoringModifiers instead of testChar for event
+            // generation in such case to avoid uppercase letters in text components.
+            LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
+            if (lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
+                    Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) {
+                testChar = testCharIgnoringModifiers;
+            }
+
             jkeyCode = out[0];
             jkeyLocation = out[1];
             jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
--- a/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java	Mon Aug 08 15:29:16 2016 -0700
@@ -427,9 +427,6 @@
 
     @Override // PlatformWindow
     public void dispose() {
-        if (owner != null) {
-            CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
-        }
         contentView.dispose();
         nativeDispose(getNSWindowPtr());
         CPlatformWindow.super.dispose();
@@ -526,25 +523,6 @@
     public void setVisible(boolean visible) {
         final long nsWindowPtr = getNSWindowPtr();
 
-        // Process parent-child relationship when hiding
-        if (!visible) {
-            // Unparent my children
-            for (Window w : target.getOwnedWindows()) {
-                WindowPeer p = (WindowPeer)w.getPeer();
-                if (p instanceof LWWindowPeer) {
-                    CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
-                    if (pw != null && pw.isVisible()) {
-                        CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
-                    }
-                }
-            }
-
-            // Unparent myself
-            if (owner != null && owner.isVisible()) {
-                CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
-            }
-        }
-
         // Configure stuff
         updateIconImages();
         updateFocusabilityForAutoRequestFocus(false);
@@ -618,19 +596,19 @@
 
         // Manage parent-child relationship when showing
         if (visible) {
-            // Add myself as a child
+            // Order myself above my parent
             if (owner != null && owner.isVisible()) {
-                CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
+                CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
                 applyWindowLevel(target);
             }
 
-            // Add my own children to myself
+            // Order my own children above myself
             for (Window w : target.getOwnedWindows()) {
                 WindowPeer p = (WindowPeer)w.getPeer();
                 if (p instanceof LWWindowPeer) {
                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
                     if (pw != null && pw.isVisible()) {
-                        CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
+                        CWrapper.NSWindow.orderWindow(pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove, nsWindowPtr);
                         pw.applyWindowLevel(w);
                     }
                 }
@@ -1059,8 +1037,8 @@
             // Order the window to front of the stack of child windows
             final long nsWindowSelfPtr = getNSWindowPtr();
             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
-            CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
-            CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
+            CWrapper.NSWindow.orderFront(nsWindowOwnerPtr);
+            CWrapper.NSWindow.orderWindow(nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove, nsWindowOwnerPtr);
         }
 
         applyWindowLevel(target);
--- a/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java	Mon Aug 08 15:29:16 2016 -0700
@@ -221,15 +221,6 @@
         synchronized (lock) {
             final long nsWindowPtr = getNSWindowPtr();
 
-            // Process parent-child relationship when hiding
-            if (!visible) {
-                // Unparent myself
-                if (owner != null && owner.isVisible()) {
-                    CWrapper.NSWindow.removeChildWindow(
-                            owner.getNSWindowPtr(), nsWindowPtr);
-                }
-            }
-
             // Actually show or hide the window
             if (visible) {
                 CWrapper.NSWindow.orderFront(nsWindowPtr);
@@ -241,10 +232,10 @@
 
             // Manage parent-child relationship when showing
             if (visible) {
-                // Add myself as a child
+                // Order myself above my parent
                 if (owner != null && owner.isVisible()) {
-                    CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(),
-                            nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
+                    CWrapper.NSWindow.orderWindow(nsWindowPtr,
+                            CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
 
                     // do not allow security warning to be obscured by other windows
                     applyWindowLevel(ownerWindow);
--- a/src/macosx/native/sun/awt/AWTView.h	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/AWTView.h	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -63,6 +63,8 @@
 - (void) deliverJavaMouseEvent: (NSEvent *) event;
 - (jobject) awtComponent:(JNIEnv *)env;
 
++ (AWTView *) awtView:(JNIEnv *)env ofAccessible:(jobject)jaccessible;
+
 // Input method-related events
 - (void)setInputMethod:(jobject)inputMethod;
 - (void)abandonInput;
--- a/src/macosx/native/sun/awt/AWTView.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/AWTView.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 #import "LWCToolkit.h"
 #import "JavaComponentAccessibility.h"
 #import "JavaTextAccessibility.h"
+#import "JavaAccessibilityUtilities.h"
 #import "GeomUtilities.h"
 #import "OSVersion.h"
 #import "CGLLayer.h"
@@ -132,7 +133,7 @@
     self.cglLayer = nil;
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
-    (*env)->DeleteGlobalRef(env, m_cPlatformView);
+    (*env)->DeleteWeakGlobalRef(env, m_cPlatformView);
     m_cPlatformView = NULL;
 
     if (fInputMethodLOCKABLE != NULL)
@@ -402,7 +403,12 @@
 
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
-    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent);
+
+    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
+    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
+        JNFCallVoidMethod(env, jlocal, jm_deliverMouseEvent, jEvent);
+        (*env)->DeleteLocalRef(env, jlocal);
+    }
 }
 
 - (void) resetTrackingArea {
@@ -463,7 +469,12 @@
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView,
                             "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
-    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent);
+
+    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
+    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
+        JNFCallVoidMethod(env, jlocal, jm_deliverKeyEvent, jevent);
+        (*env)->DeleteLocalRef(env, jlocal);
+    }
 
     if (characters != NULL) {
         (*env)->DeleteLocalRef(env, characters);
@@ -478,7 +489,12 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverResize, jc_PlatformView, "deliverResize", "(IIII)V");
-    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverResize, x,y,w,h);
+
+    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
+    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
+        JNFCallVoidMethod(env, jlocal, jm_deliverResize, x,y,w,h);
+        (*env)->DeleteLocalRef(env, jlocal);
+    }
 }
 
 
@@ -507,7 +523,12 @@
 */
         static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
         static JNF_MEMBER_CACHE(jm_deliverWindowDidExposeEvent, jc_CPlatformView, "deliverWindowDidExposeEvent", "()V");
-        JNFCallVoidMethod(env, m_cPlatformView, jm_deliverWindowDidExposeEvent);
+
+        jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
+        if (!(*env)->IsSameObject(env, jlocal, NULL)) {
+            JNFCallVoidMethod(env, jlocal, jm_deliverWindowDidExposeEvent);
+            (*env)->DeleteLocalRef(env, jlocal);
+        }
 /*
         }
 */
@@ -515,8 +536,10 @@
 }
 
 -(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint {
-    if ((codePoint >= 0x3000) && (codePoint <= 0x303F)) {
-        // Code point is in 'CJK Symbols and Punctuation' Unicode block.
+    if (((codePoint >= 0x3000) && (codePoint <= 0x303F)) ||
+        ((codePoint >= 0xFF00) && (codePoint <= 0xFFEF))) {
+        // Code point is in 'CJK Symbols and Punctuation' or
+        // 'Halfwidth and Fullwidth Forms' Unicode block.
         return YES;
     }
     return NO;
@@ -535,7 +558,13 @@
         }
         return NULL;
     }
-    jobject peer = JNFGetObjectField(env, m_cPlatformView, jf_Peer);
+
+    jobject peer = NULL;
+    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
+    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
+        peer = JNFGetObjectField(env, jlocal, jf_Peer);
+        (*env)->DeleteLocalRef(env, jlocal);
+    }
     static JNF_CLASS_CACHE(jc_LWWindowPeer, "sun/lwawt/LWWindowPeer");
     static JNF_MEMBER_CACHE(jf_Target, jc_LWWindowPeer, "target", "Ljava/awt/Component;");
     if (peer == NULL) {
@@ -543,12 +572,27 @@
         JNFDumpJavaStack(env);
         return NULL;
     }
-    return JNFGetObjectField(env, peer, jf_Target);
+    jobject comp = JNFGetObjectField(env, peer, jf_Target);
+    (*env)->DeleteLocalRef(env, peer);
+    return comp;
+}
+
++ (AWTView *) awtView:(JNIEnv*)env ofAccessible:(jobject)jaccessible
+{
+    static JNF_STATIC_MEMBER_CACHE(jm_getAWTView, sjc_CAccessibility, "getAWTView", "(Ljavax/accessibility/Accessible;)J");
+
+    jlong jptr = JNFCallStaticLongMethod(env, jm_getAWTView, jaccessible);
+    if (jptr == 0) return nil;
+
+    return (AWTView *)jlong_to_ptr(jptr);
 }
 
 - (id)getAxData:(JNIEnv*)env
 {
-    return [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:[self awtComponent:env] withIndex:-1 withView:self withJavaRole:nil] autorelease];
+    jobject jcomponent = [self awtComponent:env];
+    id ax = [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:jcomponent withIndex:-1 withView:self withJavaRole:nil] autorelease];
+    (*env)->DeleteLocalRef(env, jcomponent);
+    return ax;
 }
 
 - (NSArray *)accessibilityAttributeNames
@@ -1291,7 +1335,7 @@
 JNF_COCOA_ENTER(env);
 
     NSRect rect = NSMakeRect(originX, originY, width, height);
-    jobject cPlatformView = (*env)->NewGlobalRef(env, obj);
+    jobject cPlatformView = (*env)->NewWeakGlobalRef(env, obj);
 
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 
--- a/src/macosx/native/sun/awt/AWTWindow.h	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/AWTWindow.h	Mon Aug 08 15:29:16 2016 -0700
@@ -46,6 +46,7 @@
     NSWindow *nsWindow;
     AWTWindow *ownerWindow;
     jint preFullScreenLevel;
+    BOOL isMinimizing;
 }
 
 // An instance of either AWTWindow_Normal or AWTWindow_Panel
@@ -59,6 +60,7 @@
 @property (nonatomic) jint styleBits;
 @property (nonatomic) BOOL isEnabled;
 @property (nonatomic) jint preFullScreenLevel;
+@property (nonatomic) BOOL isMinimizing;
 
 
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)javaPlatformWindow
--- a/src/macosx/native/sun/awt/AWTWindow.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/AWTWindow.m	Mon Aug 08 15:29:16 2016 -0700
@@ -184,6 +184,7 @@
 @synthesize isEnabled;
 @synthesize ownerWindow;
 @synthesize preFullScreenLevel;
+@synthesize isMinimizing;
 
 - (void) updateMinMaxSize:(BOOL)resizable {
     if (resizable) {
@@ -308,6 +309,7 @@
     [self.nsWindow release]; // the property retains the object already
 
     self.isEnabled = YES;
+    self.isMinimizing = NO;
     self.javaPlatformWindow = platformWindow;
     self.styleBits = bits;
     self.ownerWindow = owner;
@@ -427,6 +429,68 @@
     [super dealloc];
 }
 
+// Tests wheather the corresponding Java paltform window is visible or not
++ (BOOL) isJavaPlatformWindowVisible:(NSWindow *)window {
+    BOOL isVisible = NO;
+    
+    if ([AWTWindow isAWTWindow:window] && [window delegate] != nil) {
+        AWTWindow *awtWindow = (AWTWindow *)[window delegate];
+        [AWTToolkit eventCountPlusPlus];
+        
+        JNIEnv *env = [ThreadUtilities getJNIEnv];
+        jobject platformWindow = [awtWindow.javaPlatformWindow jObjectWithEnv:env];
+        if (platformWindow != NULL) {
+            static JNF_MEMBER_CACHE(jm_isVisible, jc_CPlatformWindow, "isVisible", "()Z");
+            isVisible = JNFCallBooleanMethod(env, platformWindow, jm_isVisible) == JNI_TRUE ? YES : NO;
+            (*env)->DeleteLocalRef(env, platformWindow);
+            
+        }
+    }
+    return isVisible;
+}
+
+// Orders window's childs based on the current focus state
+- (void) orderChildWindows:(BOOL)focus {
+AWT_ASSERT_APPKIT_THREAD;
+
+    if (self.isMinimizing) {
+        // Do not perform any ordering, if iconify is in progress
+        return;
+    }
+
+    NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
+    NSWindow *window;
+    while ((window = [windowEnumerator nextObject]) != nil) {
+        if ([AWTWindow isJavaPlatformWindowVisible:window]) {
+            AWTWindow *awtWindow = (AWTWindow *)[window delegate];
+            AWTWindow *owner = awtWindow.ownerWindow;
+            if (IS(awtWindow.styleBits, ALWAYS_ON_TOP)) {
+                // Do not order 'always on top' windows
+                continue;
+            }
+            while (awtWindow.ownerWindow != nil) {
+                if (awtWindow.ownerWindow == self) {
+                    if (focus) {
+                        // Move the childWindow to floating level
+                        // so it will appear in front of its
+                        // parent which owns the focus
+                        [window setLevel:NSFloatingWindowLevel];
+                    } else {
+                        // Focus owner has changed, move the childWindow
+                        // back to normal window level
+                        [window setLevel:NSNormalWindowLevel];
+                    }
+                    // The childWindow should be displayed in front of
+                    // its nearest parentWindow
+                    [window orderWindow:NSWindowAbove relativeTo:[owner.nsWindow windowNumber]];
+                    break;
+                }
+                awtWindow = awtWindow.ownerWindow;
+            }
+        }
+    }
+}
+
 // NSWindow overrides
 - (BOOL) canBecomeKeyWindow {
 AWT_ASSERT_APPKIT_THREAD;
@@ -509,6 +573,30 @@
     // window exposing in _setVisible:(BOOL)
 }
 
+// Hides/shows window's childs during iconify/de-iconify operation
+- (void) iconifyChildWindows:(BOOL)iconify {
+AWT_ASSERT_APPKIT_THREAD;
+
+    NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
+    NSWindow *window;
+    while ((window = [windowEnumerator nextObject]) != nil) {
+        if ([AWTWindow isJavaPlatformWindowVisible:window]) {
+            AWTWindow *awtWindow = (AWTWindow *)[window delegate];
+            while (awtWindow.ownerWindow != nil) {
+                if (awtWindow.ownerWindow == self) {
+                    if (iconify) {
+                        [window orderOut:window];
+                    } else {
+                        [window orderFront:window];
+                    }
+                    break;
+                }
+                awtWindow = awtWindow.ownerWindow;
+            }
+        }
+    }
+}
+
 - (void) _deliverIconify:(BOOL)iconify {
 AWT_ASSERT_APPKIT_THREAD;
 
@@ -522,16 +610,28 @@
     }
 }
 
+- (void)windowWillMiniaturize:(NSNotification *)notification {
+AWT_ASSERT_APPKIT_THREAD;
+
+    self.isMinimizing = YES;
+    // Excplicitly make myself a key window to avoid possible
+    // negative visual effects during iconify operation
+    [self.nsWindow makeKeyAndOrderFront:self.nsWindow];
+    [self iconifyChildWindows:YES];
+}
+
 - (void)windowDidMiniaturize:(NSNotification *)notification {
 AWT_ASSERT_APPKIT_THREAD;
 
     [self _deliverIconify:JNI_TRUE];
+    self.isMinimizing = NO;
 }
 
 - (void)windowDidDeminiaturize:(NSNotification *)notification {
 AWT_ASSERT_APPKIT_THREAD;
 
     [self _deliverIconify:JNI_FALSE];
+    [self iconifyChildWindows:NO];
 }
 
 - (void) _deliverWindowFocusEvent:(BOOL)focused oppositeWindow:(AWTWindow *)opposite {
@@ -577,6 +677,7 @@
     [AWTWindow setLastKeyWindow:nil];
 
     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
+    [self orderChildWindows:YES];
 }
 
 - (void) windowDidResignKey: (NSNotification *) notification {
@@ -604,6 +705,7 @@
     }
 
     [self _deliverWindowFocusEvent:NO oppositeWindow: opposite];
+    [self orderChildWindows:NO];
 }
 
 - (void) windowDidBecomeMain: (NSNotification *) notification {
--- a/src/macosx/native/sun/awt/JavaAccessibilityAction.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/JavaAccessibilityAction.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,9 +35,9 @@
 {
     self = [super init];
     if (self) {
-        fAccessibleAction = JNFNewGlobalRef(env, accessibleAction);
+        fAccessibleAction = JNFNewWeakGlobalRef(env, accessibleAction);
         fIndex = index;
-        fComponent = JNFNewGlobalRef(env, component);
+        fComponent = JNFNewWeakGlobalRef(env, component);
     }
     return self;
 }
@@ -46,10 +46,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fAccessibleAction);
+    JNFDeleteWeakGlobalRef(env, fAccessibleAction);
     fAccessibleAction = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    JNFDeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super dealloc];
@@ -59,10 +59,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fAccessibleAction);
+    JNFDeleteWeakGlobalRef(env, fAccessibleAction);
     fAccessibleAction = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    JNFDeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
@@ -75,7 +75,18 @@
 
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
-    return JNFJavaToNSString(env, JNFCallStaticObjectMethod(env, jm_getAccessibleActionDescription, fAccessibleAction, fIndex, fComponent)); // AWT_THREADING Safe (AWTRunLoopMode)
+    jobject fCompLocal = (*env)->NewLocalRef(env, fComponent);
+    if ((*env)->IsSameObject(env, fCompLocal, NULL)) {
+        return @"unknown";
+    }
+    NSString *str = nil;
+    jobject jstr = JNFCallStaticObjectMethod(env, jm_getAccessibleActionDescription, fAccessibleAction, fIndex, fCompLocal);
+    if (jstr != NULL) {
+        NSString *str = JNFJavaToNSString(env, jstr); // AWT_THREADING Safe (AWTRunLoopMode)
+        (*env)->DeleteLocalRef(env, jstr);
+    }
+    (*env)->DeleteLocalRef(env, fCompLocal);
+    return str == nil ? @"unknown" : str;
 }
 
 - (void)perform
@@ -96,9 +107,9 @@
 {
     self = [super init];
     if (self) {
-        fTabGroup = JNFNewGlobalRef(env, tabGroup);
+        fTabGroup = JNFNewWeakGlobalRef(env, tabGroup);
         fIndex = index;
-        fComponent = JNFNewGlobalRef(env, component);
+        fComponent = JNFNewWeakGlobalRef(env, component);
     }
     return self;
 }
@@ -107,10 +118,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fTabGroup);
+    JNFDeleteWeakGlobalRef(env, fTabGroup);
     fTabGroup = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    JNFDeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super dealloc];
@@ -120,10 +131,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fTabGroup);
+    JNFDeleteWeakGlobalRef(env, fTabGroup);
     fTabGroup = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    JNFDeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
--- a/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -77,7 +77,9 @@
     jobject axRole = JNFCallStaticObjectMethod(env, sjm_getAccessibleRole, axComponent, component); // AWT_THREADING Safe (AWTRunLoopMode)
     if (axRole == NULL) return @"unknown";
 
-    return JNFJavaToNSString(env, axRole);
+    NSString* str = JNFJavaToNSString(env, axRole);
+    (*env)->DeleteLocalRef(env, axRole);
+    return str;
 }
 
 jobject getAxSelection(JNIEnv *env, jobject axContext, jobject component)
@@ -126,21 +128,27 @@
 {
     static JNF_STATIC_MEMBER_CACHE(jm_VERTICAL, sjc_AccessibleState, "VERTICAL", "Ljavax/accessibility/AccessibleState;");
     jobject axVertState = JNFGetStaticObjectField(env, jm_VERTICAL);
-    return containsAxState(env, axContext, axVertState, component);
+    BOOL vertical = containsAxState(env, axContext, axVertState, component);
+    (*env)->DeleteLocalRef(env, axVertState);
+    return vertical;
 }
 
 BOOL isHorizontal(JNIEnv *env, jobject axContext, jobject component)
 {
     static JNF_STATIC_MEMBER_CACHE(jm_HORIZONTAL, sjc_AccessibleState, "HORIZONTAL", "Ljavax/accessibility/AccessibleState;");
     jobject axHorizState = JNFGetStaticObjectField(env, jm_HORIZONTAL);
-    return containsAxState(env, axContext, axHorizState, component);
+    BOOL horizontal = containsAxState(env, axContext, axHorizState, component);
+    (*env)->DeleteLocalRef(env, axHorizState);
+    return horizontal;
 }
 
 BOOL isShowing(JNIEnv *env, jobject axContext, jobject component)
 {
     static JNF_STATIC_MEMBER_CACHE(jm_SHOWING, sjc_AccessibleState, "SHOWING", "Ljavax/accessibility/AccessibleState;");
     jobject axVisibleState = JNFGetStaticObjectField(env, jm_SHOWING);
-    return containsAxState(env, axContext, axVisibleState, component);
+    BOOL showing = containsAxState(env, axContext, axVisibleState, component);
+    (*env)->DeleteLocalRef(env, axVisibleState);
+    return showing;
 }
 
 NSPoint getAxComponentLocationOnScreen(JNIEnv *env, jobject axComponent, jobject component)
--- a/src/macosx/native/sun/awt/JavaComponentAccessibility.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/JavaComponentAccessibility.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -75,7 +75,6 @@
 static NSMutableDictionary *sAttributeNamesForRoleCache = nil;
 static NSObject *sAttributeNamesLOCK = nil;
 
-
 @interface TabGroupAccessibility : JavaComponentAccessibility {
     NSInteger _numTabs;
 }
@@ -137,8 +136,11 @@
         fView = [view retain];
         fJavaRole = [javaRole retain];
 
-        fAccessible = JNFNewGlobalRef(env, accessible);
-        fComponent = JNFNewGlobalRef(env, [(AWTView *)fView awtComponent:env]);
+        fAccessible = (*env)->NewWeakGlobalRef(env, accessible);
+        
+        jobject jcomponent = [(AWTView *)fView awtComponent:env];
+        fComponent = (*env)->NewWeakGlobalRef(env, jcomponent);
+        (*env)->DeleteLocalRef(env, jcomponent);
 
         fIndex = index;
 
@@ -166,10 +168,10 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fAccessible);
+    (*env)->DeleteWeakGlobalRef(env, fAccessible);
     fAccessible = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    (*env)->DeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [fParent release];
@@ -198,10 +200,10 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteGlobalRef(env, fAccessible);
+    (*env)->DeleteWeakGlobalRef(env, fAccessible);
     fAccessible = NULL;
 
-    JNFDeleteGlobalRef(env, fComponent);
+    (*env)->DeleteWeakGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
@@ -293,7 +295,7 @@
 
 + (NSArray *)childrenOfParent:(JavaComponentAccessibility *)parent withEnv:(JNIEnv *)env withChildrenCode:(NSInteger)whichChildren allowIgnored:(BOOL)allowIgnored
 {
-    jobjectArray jchildrenAndRoles = JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, parent->fAccessible, parent->fComponent, whichChildren, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
+    jobjectArray jchildrenAndRoles = (jobjectArray)JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, parent->fAccessible, parent->fComponent, whichChildren, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
     if (jchildrenAndRoles == NULL) return nil;
 
     jsize arrayLen = (*env)->GetArrayLength(env, jchildrenAndRoles);
@@ -308,14 +310,21 @@
 
         NSString *childJavaRole = nil;
         if (jchildJavaRole != NULL) {
-            childJavaRole = JNFJavaToNSString(env, JNFGetObjectField(env, jchildJavaRole, sjf_key));
+            jobject jkey = JNFGetObjectField(env, jchildJavaRole, sjf_key);
+            childJavaRole = JNFJavaToNSString(env, jkey);
+            (*env)->DeleteLocalRef(env, jkey);
         }
 
         JavaComponentAccessibility *child = [self createWithParent:parent accessible:jchild role:childJavaRole index:childIndex withEnv:env withView:parent->fView];
+        
+        (*env)->DeleteLocalRef(env, jchild);
+        (*env)->DeleteLocalRef(env, jchildJavaRole);
+        
         [children addObject:child];
         childIndex++;
     }
-
+    (*env)->DeleteLocalRef(env, jchildrenAndRoles);
+    
     return children;
 }
 
@@ -324,7 +333,7 @@
     jobject jcomponent = [(AWTView *)view awtComponent:env];
     jint index = JNFCallStaticIntMethod(env, sjm_getAccessibleIndexInParent, jaccessible, jcomponent);
     NSString *javaRole = getJavaRole(env, jaccessible, jcomponent);
-
+    (*env)->DeleteLocalRef(env, jcomponent);
     return [self createWithAccessible:jaccessible role:javaRole index:index withEnv:env withView:view];
 }
 
@@ -339,7 +348,10 @@
     jobject jCAX = [JavaComponentAccessibility getCAccessible:jaccessible withEnv:env];
     if (jCAX == NULL) return nil;
     JavaComponentAccessibility *value = (JavaComponentAccessibility *) jlong_to_ptr(JNFGetLongField(env, jCAX, jf_ptr));
-    if (value != nil) return [[value retain] autorelease];
+    if (value != nil) {
+        (*env)->DeleteLocalRef(env, jCAX);
+        return [[value retain] autorelease];
+    }
 
     // otherwise, create a new instance
     JavaComponentAccessibility *newChild = nil;
@@ -362,6 +374,7 @@
     // must hard CFRetain() pointer poked into Java object
     CFRetain(newChild);
     JNFSetLongField(env, jCAX, jf_ptr, ptr_to_jlong(newChild));
+    (*env)->DeleteLocalRef(env, jCAX);
 
     // return autoreleased instance
     return [newChild autorelease];
@@ -394,7 +407,7 @@
 
     // Get all the other accessibility attributes states we need in one swell foop.
     // javaRole isn't pulled in because we need protected access to AccessibleRole.key
-    jbooleanArray attributeStates = JNFCallStaticObjectMethod(env, jm_getInitialAttributeStates, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
+    jbooleanArray attributeStates = (jbooleanArray)JNFCallStaticObjectMethod(env, jm_getInitialAttributeStates, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (attributeStates == NULL) return nil;
     jboolean *attributeStatesArray = (*env)->GetBooleanArrayElements(env, attributeStates, 0);
     if (attributeStatesArray == NULL) {
@@ -489,6 +502,7 @@
         JavaAxAction *action = [[JavaAxAction alloc] initWithEnv:env withAccessibleAction:axAction withIndex:0 withComponent:fComponent];
         [fActions setObject:action forKey:[self isMenu] ? NSAccessibilityPickAction : NSAccessibilityPressAction];
         [action release];
+        (*env)->DeleteLocalRef(env, axAction);
     }
 }
 
@@ -499,7 +513,9 @@
 
 - (id)parent
 {
+    static JNF_CLASS_CACHE(sjc_Window, "java/awt/Window");
     static JNF_STATIC_MEMBER_CACHE(sjm_getAccessibleParent, sjc_CAccessibility, "getAccessibleParent", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/Accessible;");
+    static JNF_STATIC_MEMBER_CACHE(sjm_getSwingAccessible, sjc_CAccessible, "getSwingAccessible", "(Ljavax/accessibility/Accessible;)Ljavax/accessibility/Accessible;");
 
     if(fParent == nil) {
         JNIEnv* env = [ThreadUtilities getJNIEnv];
@@ -509,10 +525,21 @@
         if (jparent == NULL) {
             fParent = fView;
         } else {
-            fParent = [JavaComponentAccessibility createWithAccessible:jparent withEnv:env withView:fView];
+            AWTView *view = fView;
+            jobject jax = JNFCallStaticObjectMethod(env, sjm_getSwingAccessible, fAccessible);
+
+            if (JNFIsInstanceOf(env, jax, &sjc_Window)) {
+                // In this case jparent is an owner toplevel and we should retrieve its own view
+                view = [AWTView awtView:env ofAccessible:jparent];
+            }
+            if (view != nil) {
+                fParent = [JavaComponentAccessibility createWithAccessible:jparent withEnv:env withView:view];
+            }
             if (fParent == nil) {
                 fParent = fView;
             }
+            (*env)->DeleteLocalRef(env, jparent);
+            (*env)->DeleteLocalRef(env, jax );
         }
         [fParent retain];
     }
@@ -560,7 +587,10 @@
         return NO;
     }
 
-    return isShowing(env, [self axContextWithEnv:env], fComponent);
+    jobject axContext = [self axContextWithEnv:env];
+    BOOL showing = isShowing(env, axContext, fComponent);
+    (*env)->DeleteLocalRef(env, axContext);
+    return showing;
 }
 
 // the array of names for each role is cached in the sAttributeNamesForRoleCache
@@ -737,7 +767,12 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleDescription, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return JNFJavaToNSString(env, val);
+    if (val == NULL) {
+        return @"unknown";
+    }
+    NSString* str = JNFJavaToNSString(env, val);
+    (*env)->DeleteLocalRef(env, val);
+    return str;
 }
 
 - (BOOL)accessibilityIsHelpAttributeSettable
@@ -753,7 +788,12 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject axValue = JNFCallStaticObjectMethod(env, jm_getMaximumAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return JNFJavaToNSNumber(env, axValue);
+    if (axValue == NULL) {
+        return [NSNumber numberWithInt:0];
+    }
+    NSNumber* num = JNFJavaToNSNumber(env, axValue);
+    (*env)->DeleteLocalRef(env, axValue);
+    return num;
 }
 
 - (BOOL)accessibilityIsMaxValueAttributeSettable
@@ -769,7 +809,12 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject axValue = JNFCallStaticObjectMethod(env, jm_getMinimumAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return JNFJavaToNSNumber(env, axValue);
+    if (axValue == NULL) {
+        return [NSNumber numberWithInt:0];
+    }
+    NSNumber* num = JNFJavaToNSNumber(env, axValue);
+    (*env)->DeleteLocalRef(env, axValue);
+    return num;
 }
 
 - (BOOL)accessibilityIsMinValueAttributeSettable
@@ -784,13 +829,16 @@
 
     // cmcnote - should batch these two calls into one that returns an array of two bools, one for vertical and one for horiz
     if (isVertical(env, axContext, fComponent)) {
+        (*env)->DeleteLocalRef(env, axContext);
         return NSAccessibilityVerticalOrientationValue;
     }
 
     if (isHorizontal(env, axContext, fComponent)) {
+        (*env)->DeleteLocalRef(env, axContext);
         return NSAccessibilityHorizontalOrientationValue;
     }
 
+    (*env)->DeleteLocalRef(env, axContext);
     return nil;
 }
 
@@ -822,6 +870,7 @@
     // Get the java screen coords, and make a NSPoint of the bottom left of the AxComponent.
     NSSize size = getAxComponentSize(env, axComponent, fComponent);
     NSPoint point = getAxComponentLocationOnScreen(env, axComponent, fComponent);
+    (*env)->DeleteLocalRef(env, axComponent);
 
     point.y += size.height;
 
@@ -871,8 +920,9 @@
         JNIEnv* env = [ThreadUtilities getJNIEnv];
 
         jobject axRole = JNFCallStaticObjectMethod(env, jm_getAccessibleRoleDisplayString, fAccessible, fComponent);
-        if(axRole != NULL) {
+        if (axRole != NULL) {
             value = JNFJavaToNSString(env, axRole);
+            (*env)->DeleteLocalRef(env, axRole);
         } else {
             value = @"unknown";
         }
@@ -907,7 +957,9 @@
 - (NSValue *)accessibilitySizeAttribute {
     JNIEnv* env = [ThreadUtilities getJNIEnv];
     jobject axComponent = JNFCallStaticObjectMethod(env, sjm_getAccessibleComponent, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return [NSValue valueWithSize:getAxComponentSize(env, axComponent, fComponent)];
+    NSValue* size = [NSValue valueWithSize:getAxComponentSize(env, axComponent, fComponent)];
+    (*env)->DeleteLocalRef(env, axComponent);
+    return size;
 }
 
 - (BOOL)accessibilityIsSizeAttributeSettable
@@ -966,7 +1018,12 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleName, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return JNFJavaToNSString(env, val);
+    if (val == NULL) {
+        return @"unknown";
+    }
+    NSString* str = JNFJavaToNSString(env, val);
+    (*env)->DeleteLocalRef(env, val);
+    return str;
 }
 
 - (BOOL)accessibilityIsTitleAttributeSettable
@@ -998,8 +1055,20 @@
     // a text value is taken care of in JavaTextAccessibility
 
     // cmcnote should coalesce these calls into one java call
+    NSNumber *num = nil;
     jobject axValue = JNFCallStaticObjectMethod(env, sjm_getAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return JNFJavaToNSNumber(env, JNFCallStaticObjectMethod(env, jm_getCurrentAccessibleValue, axValue, fComponent)); // AWT_THREADING Safe (AWTRunLoop)
+    if (axValue != NULL) {
+        jobject str = JNFCallStaticObjectMethod(env, jm_getCurrentAccessibleValue, axValue, fComponent);
+        if (str != NULL) {
+            num = JNFJavaToNSNumber(env, str); // AWT_THREADING Safe (AWTRunLoop)
+            (*env)->DeleteLocalRef(env, str);
+        }
+        (*env)->DeleteLocalRef(env, axValue);
+    }
+    if (num == nil) {
+        num = [NSNumber numberWithInt:0];
+    }
+    return num;
 }
 
 - (BOOL)accessibilityIsValueAttributeSettable
@@ -1098,7 +1167,10 @@
     id value = nil;
     if (JNFIsInstanceOf(env, jparent, &jc_Container)) {
         jobject jaccessible = JNFCallStaticObjectMethod(env, jm_accessibilityHitTest, jparent, (jfloat)point.x, (jfloat)point.y); // AWT_THREADING Safe (AWTRunLoop)
-        value = [JavaComponentAccessibility createWithAccessible:jaccessible withEnv:env withView:fView];
+        if (jaccessible != NULL) {
+            value = [JavaComponentAccessibility createWithAccessible:jaccessible withEnv:env withView:fView];
+            (*env)->DeleteLocalRef(env, jaccessible);
+        }
     }
 
     if (value == nil) {
@@ -1130,6 +1202,7 @@
         if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) {
             value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView];
         }
+        (*env)->DeleteLocalRef(env, focused);
     }
 
     if (value == nil) {
@@ -1236,38 +1309,46 @@
     for (i = 0; i < _numTabs; i++) {
         aTab = (JavaComponentAccessibility *)[tabs objectAtIndex:i];
         if ([aTab isAccessibleWithEnv:env forAccessible:selAccessible]) {
+            (*env)->DeleteLocalRef(env, selAccessible);
             return aTab;
         }
     }
-
+    (*env)->DeleteLocalRef(env, selAccessible);
     return nil;
 }
 
 - (NSArray *)tabControlsWithEnv:(JNIEnv *)env withTabGroupAxContext:(jobject)axContext withTabCode:(NSInteger)whichTabs allowIgnored:(BOOL)allowIgnored
 {
-    jobjectArray jtabsAndRoles = JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, fAccessible, fComponent, whichTabs, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
+    jobjectArray jtabsAndRoles = (jobjectArray)JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, fAccessible, fComponent, whichTabs, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
     if(jtabsAndRoles == NULL) return nil;
 
     jsize arrayLen = (*env)->GetArrayLength(env, jtabsAndRoles);
-    if (arrayLen == 0) return nil;
-
+    if (arrayLen == 0) {
+        (*env)->DeleteLocalRef(env, jtabsAndRoles);
+        return nil;
+    }
     NSMutableArray *tabs = [NSMutableArray arrayWithCapacity:(arrayLen/2)];
 
     // all of the tabs have the same role, so we can just find out what that is here and use it for all the tabs
     jobject jtabJavaRole = (*env)->GetObjectArrayElement(env, jtabsAndRoles, 1); // the array entries alternate between tab/role, starting with tab. so the first role is entry 1.
-    if (jtabJavaRole == NULL) return nil;
-
-    NSString *tabJavaRole = JNFJavaToNSString(env, JNFGetObjectField(env, jtabJavaRole, sjf_key));
+    if (jtabJavaRole == NULL) {
+        (*env)->DeleteLocalRef(env, jtabsAndRoles);
+        return nil;
+    }
+    jobject jkey = JNFGetObjectField(env, jtabJavaRole, sjf_key);
+    NSString *tabJavaRole = JNFJavaToNSString(env, jkey);
+    (*env)->DeleteLocalRef(env, jkey);
 
     NSInteger i;
     NSUInteger tabIndex = (whichTabs >= 0) ? whichTabs : 0; // if we're getting one particular child, make sure to set its index correctly
     for(i = 0; i < arrayLen; i+=2) {
         jobject jtab = (*env)->GetObjectArrayElement(env, jtabsAndRoles, i);
         JavaComponentAccessibility *tab = [[[TabGroupControlAccessibility alloc] initWithParent:self withEnv:env withAccessible:jtab withIndex:tabIndex withTabGroup:axContext withView:[self view] withJavaRole:tabJavaRole] autorelease];
+        (*env)->DeleteLocalRef(env, jtab);
         [tabs addObject:tab];
         tabIndex++;
     }
-
+    (*env)->DeleteLocalRef(env, jtabsAndRoles);
     return tabs;
 }
 
@@ -1286,7 +1367,9 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    return [self tabControlsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
+    id tabs = [self tabControlsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
+    (*env)->DeleteLocalRef(env, axContext);
+    return tabs;
 }
 
 - (BOOL)accessibilityIsTabsAttributeSettable
@@ -1306,7 +1389,9 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    return [self contentsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
+    NSArray* cont = [self contentsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
+    (*env)->DeleteLocalRef(env, axContext);
+    return cont;
 }
 
 - (BOOL)accessibilityIsContentsAttributeSettable
@@ -1319,7 +1404,9 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    return [self currentTabWithEnv:env withAxContext:axContext];
+    id val = [self currentTabWithEnv:env withAxContext:axContext];
+    (*env)->DeleteLocalRef(env, axContext);
+    return val;
 }
 
 - (BOOL)accessibilityIsValueAttributeSettable
@@ -1336,6 +1423,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
     setAxContextSelection(env, axContext, fIndex, fComponent);
+    (*env)->DeleteLocalRef(env, axContext);
 }
 
 - (NSArray *)accessibilityChildrenAttribute
@@ -1371,6 +1459,7 @@
                 result = children;
             }
         }
+        (*env)->DeleteLocalRef(env, axContext);
     } else {
         result = [super accessibilityArrayAttributeValues:attribute index:index maxCount:maxCount];
     }
@@ -1389,7 +1478,7 @@
     self = [super initWithParent:parent withEnv:env withAccessible:accessible withIndex:index withView:view withJavaRole:javaRole];
     if (self) {
         if (tabGroup != NULL) {
-            fTabGroupAxContext = JNFNewGlobalRef(env, tabGroup);
+            fTabGroupAxContext = JNFNewWeakGlobalRef(env, tabGroup);
         } else {
             fTabGroupAxContext = NULL;
         }
@@ -1402,7 +1491,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
     if (fTabGroupAxContext != NULL) {
-        JNFDeleteGlobalRef(env, fTabGroupAxContext);
+        JNFDeleteWeakGlobalRef(env, fTabGroupAxContext);
         fTabGroupAxContext = NULL;
     }
 
@@ -1414,7 +1503,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
     if (fTabGroupAxContext != NULL) {
-        JNFDeleteGlobalRef(env, fTabGroupAxContext);
+        JNFDeleteWeakGlobalRef(env, fTabGroupAxContext);
         fTabGroupAxContext = NULL;
     }
 
@@ -1425,9 +1514,14 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
+    jobject selAccessible = getAxContextSelection(env, [self tabGroup], fIndex, fComponent);
 
     // Returns the current selection of the page tab list
-    return [NSNumber numberWithBool:ObjectEquals(env, axContext, getAxContextSelection(env, [self tabGroup], fIndex, fComponent), fComponent)];
+    id val = [NSNumber numberWithBool:ObjectEquals(env, axContext, selAccessible, fComponent)];
+
+    (*env)->DeleteLocalRef(env, selAccessible);
+    (*env)->DeleteLocalRef(env, axContext);
+    return val;
 }
 
 - (void)getActionsWithEnv:(JNIEnv *)env
@@ -1442,7 +1536,8 @@
     if (fTabGroupAxContext == NULL) {
         JNIEnv* env = [ThreadUtilities getJNIEnv];
         jobject tabGroupAxContext = [(JavaComponentAccessibility *)[self parent] axContextWithEnv:env];
-        fTabGroupAxContext = JNFNewGlobalRef(env, tabGroupAxContext);
+        fTabGroupAxContext = JNFNewWeakGlobalRef(env, tabGroupAxContext);
+        (*env)->DeleteLocalRef(env, tabGroupAxContext);
     }
     return fTabGroupAxContext;
 }
@@ -1477,8 +1572,10 @@
         if ([[aElement accessibilityRoleAttribute] isEqualToString:NSAccessibilityScrollBarRole]) {
             jobject elementAxContext = [aElement axContextWithEnv:env];
             if (isHorizontal(env, elementAxContext, fComponent)) {
+                (*env)->DeleteLocalRef(env, elementAxContext);
                 return aElement;
             }
+            (*env)->DeleteLocalRef(env, elementAxContext);
         }
     }
 
@@ -1504,8 +1601,10 @@
         if ([[aElement accessibilityRoleAttribute] isEqualToString:NSAccessibilityScrollBarRole]) {
             jobject elementAxContext = [aElement axContextWithEnv:env];
             if (isVertical(env, elementAxContext, fComponent)) {
+                (*env)->DeleteLocalRef(env, elementAxContext);
                 return aElement;
             }
+            (*env)->DeleteLocalRef(env, elementAxContext);
         }
     }
 
--- a/src/macosx/native/sun/awt/JavaTextAccessibility.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/awt/JavaTextAccessibility.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -112,7 +112,9 @@
         // if it's static text, the AppKit AXValue is the java accessibleName
         jobject axName = JNFCallStaticObjectMethod(env, sjm_getAccessibleName, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
         if (axName != NULL) {
-            return JNFJavaToNSString(env, axName);
+            NSString* str = JNFJavaToNSString(env, axName);
+            (*env)->DeleteLocalRef(env, axName);
+            return str;
         }
         // value is still nil if no accessibleName for static text. Below, try to get the accessibleText.
     }
@@ -120,12 +122,18 @@
     // cmcnote: inefficient to make three distinct JNI calls. Coalesce. radr://3951923
     jobject axText = JNFCallStaticObjectMethod(env, sjm_getAccessibleText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axText == NULL) return nil;
-
+    (*env)->DeleteLocalRef(env, axText);
+    
     jobject axEditableText = JNFCallStaticObjectMethod(env, sjm_getAccessibleEditableText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axEditableText == NULL) return nil;
 
     static JNF_STATIC_MEMBER_CACHE(jm_getTextRange, sjc_CAccessibleText, "getTextRange", "(Ljavax/accessibility/AccessibleEditableText;IILjava/awt/Component;)Ljava/lang/String;");
-    NSString *string = JNFJavaToNSString(env, JNFCallStaticObjectMethod(env, jm_getTextRange, axEditableText, 0, getAxTextCharCount(env, axEditableText, fComponent), fComponent)); // AWT_THREADING Safe (AWTRunLoop)
+    jobject jrange = JNFCallStaticObjectMethod(env, jm_getTextRange, axEditableText, 0, getAxTextCharCount(env, axEditableText, fComponent), fComponent);
+    NSString *string = JNFJavaToNSString(env, jrange); // AWT_THREADING Safe (AWTRunLoop)
+
+    (*env)->DeleteLocalRef(env, jrange);
+    (*env)->DeleteLocalRef(env, axEditableText);
+    
     if (string == nil) string = @"";
     return string;
 }
@@ -139,6 +147,7 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
     jobject axEditableText = JNFCallStaticObjectMethod(env, sjm_getAccessibleEditableText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axEditableText == NULL) return NO;
+    (*env)->DeleteLocalRef(env, axEditableText);
     return YES;
 }
 
@@ -157,7 +166,9 @@
     static JNF_STATIC_MEMBER_CACHE(jm_getSelectedText, sjc_CAccessibleText, "getSelectedText", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;");
     jobject axText = JNFCallStaticObjectMethod(env, jm_getSelectedText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axText == NULL) return @"";
-    return JNFJavaToNSString(env, axText);
+    NSString* str = JNFJavaToNSString(env, axText);
+    (*env)->DeleteLocalRef(env, axText);
+    return str;
 }
 
 - (BOOL)accessibilityIsSelectedTextAttributeSettable
@@ -220,7 +231,9 @@
     // also, static text doesn't always have accessibleText. if axText is null, should get the charcount of the accessibleName instead
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axText = JNFCallStaticObjectMethod(env, sjm_getAccessibleText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    return [NSNumber numberWithInt:getAxTextCharCount(env, axText, fComponent)];
+    NSNumber* num = [NSNumber numberWithInt:getAxTextCharCount(env, axText, fComponent)];
+    (*env)->DeleteLocalRef(env, axText);
+    return num;
 }
 
 - (BOOL)accessibilityIsNumberOfCharactersAttributeSettable
@@ -285,7 +298,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getBoundsForRange, sjc_CAccessibleText, "getBoundsForRange", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;II)[D");
-    jdoubleArray axBounds = JNFCallStaticObjectMethod(env, jm_getBoundsForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
+    jdoubleArray axBounds = (jdoubleArray)JNFCallStaticObjectMethod(env, jm_getBoundsForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
     if (axBounds == NULL) return nil;
 
     // We cheat because we know that the array is 4 elements long (x, y, width, height)
@@ -324,7 +337,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getRangeForLine, sjc_CAccessibleText, "getRangeForLine", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;I)[I");
-    jintArray axTextRange = JNFCallStaticObjectMethod(env, jm_getRangeForLine, fAccessible, fComponent, [line intValue]); // AWT_THREADING Safe (AWTRunLoop)
+    jintArray axTextRange = (jintArray)JNFCallStaticObjectMethod(env, jm_getRangeForLine, fAccessible, fComponent, [line intValue]); // AWT_THREADING Safe (AWTRunLoop)
     if (axTextRange == NULL) return nil;
 
     return javaIntArrayToNSRangeValue(env,axTextRange);
@@ -350,10 +363,12 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getStringForRange, sjc_CAccessibleText, "getStringForRange", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;II)Ljava/lang/String;");
-    jstring jstringForRange = JNFCallStaticObjectMethod(env, jm_getStringForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
+    jstring jstringForRange = (jstring)JNFCallStaticObjectMethod(env, jm_getStringForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
 
     if (jstringForRange == NULL) return @"";
-    return JNFJavaToNSString(env, jstringForRange);
+    NSString* str = JNFJavaToNSString(env, jstringForRange);
+    (*env)->DeleteLocalRef(env, jstringForRange);
+    return str;
 }
 
 //
@@ -406,7 +421,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getRangeForIndex, sjc_CAccessibleText, "getRangeForIndex", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;I)[I");
-    jintArray axTextRange = JNFCallStaticObjectMethod(env, jm_getRangeForIndex, fAccessible, fComponent, index); // AWT_THREADING Safe (AWTRunLoop)
+    jintArray axTextRange = (jintArray)JNFCallStaticObjectMethod(env, jm_getRangeForIndex, fAccessible, fComponent, index); // AWT_THREADING Safe (AWTRunLoop)
     if (axTextRange == NULL) return nil;
 
     return javaIntArrayToNSRangeValue(env, axTextRange);
--- a/src/macosx/native/sun/java2d/opengl/CGLLayer.h	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/java2d/opengl/CGLLayer.h	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,7 +31,7 @@
 @interface CGLLayer : CAOpenGLLayer
 {
 @private
-    JNFJObjectWrapper *javaLayer;
+    JNFWeakJObjectWrapper *javaLayer;
 
     // intermediate buffer, used the RQ lock to synchronize
     GLuint textureID;
@@ -45,7 +45,7 @@
 #endif /* REMOTELAYER */
 }
 
-@property (nonatomic, retain) JNFJObjectWrapper *javaLayer;
+@property (nonatomic, retain) JNFWeakJObjectWrapper *javaLayer;
 @property (readwrite, assign) GLuint textureID;
 @property (readwrite, assign) GLenum target;
 @property (readwrite, assign) float textureWidth;
@@ -57,7 +57,7 @@
 @property (nonatomic, retain) NSObject<JRSRemoteLayer> *jrsRemoteLayer;
 #endif
 
-- (id) initWithJavaLayer:(JNFJObjectWrapper *)javaLayer;
+- (id) initWithJavaLayer:(JNFWeakJObjectWrapper *)javaLayer;
 - (void) blitTexture;
 @end
 
--- a/src/macosx/native/sun/java2d/opengl/CGLLayer.m	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/macosx/native/sun/java2d/opengl/CGLLayer.m	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -46,7 +46,7 @@
 @synthesize jrsRemoteLayer;
 #endif
 
-- (id) initWithJavaLayer:(JNFJObjectWrapper *)layer;
+- (id) initWithJavaLayer:(JNFWeakJObjectWrapper *)layer;
 {
 AWT_ASSERT_APPKIT_THREAD;
     // Initialize ourselves
@@ -133,6 +133,15 @@
 {
     AWT_ASSERT_APPKIT_THREAD;
 
+    JNIEnv *env = [ThreadUtilities getJNIEnv];
+    static JNF_CLASS_CACHE(jc_JavaLayer, "sun/java2d/opengl/CGLLayer");
+    static JNF_MEMBER_CACHE(jm_drawInCGLContext, jc_JavaLayer, "drawInCGLContext", "()V");
+
+    jobject javaLayerLocalRef = [self.javaLayer jObjectWithEnv:env];
+    if ((*env)->IsSameObject(env, javaLayerLocalRef, NULL)) {
+        return;
+    }
+
     // Set the current context to the one given to us.
     CGLSetCurrentContext(glContext);
 
@@ -141,12 +150,7 @@
     glClear(GL_COLOR_BUFFER_BIT);
 
     glViewport(0, 0, textureWidth, textureHeight);
-    
-    JNIEnv *env = [ThreadUtilities getJNIEnv];
-    static JNF_CLASS_CACHE(jc_JavaLayer, "sun/java2d/opengl/CGLLayer");
-    static JNF_MEMBER_CACHE(jm_drawInCGLContext, jc_JavaLayer, "drawInCGLContext", "()V");
 
-    jobject javaLayerLocalRef = [self.javaLayer jObjectWithEnv:env];
     JNFCallVoidMethod(env, javaLayerLocalRef, jm_drawInCGLContext);
     (*env)->DeleteLocalRef(env, javaLayerLocalRef);
 
@@ -171,7 +175,7 @@
 
 JNF_COCOA_ENTER(env);
 
-    JNFJObjectWrapper *javaLayer = [JNFJObjectWrapper wrapperWithJObject:obj withEnv:env];
+    JNFWeakJObjectWrapper *javaLayer = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
 
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
             AWT_ASSERT_APPKIT_THREAD;
--- a/src/share/back/debugInit.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/back/debugInit.c	Mon Aug 08 15:29:16 2016 -0700
@@ -1013,7 +1013,7 @@
 atexit_finish_logging(void)
 {
     /* Normal exit(0) (not _exit()) may only reach here */
-    finish_logging(0);  /* Only first call matters */
+    finish_logging();  /* Only first call matters */
 }
 
 static jboolean
@@ -1301,39 +1301,49 @@
 void
 debugInit_exit(jvmtiError error, const char *msg)
 {
-    int exit_code = 0;
+    enum exit_codes { EXIT_NO_ERRORS = 0, EXIT_JVMTI_ERROR = 1, EXIT_TRANSPORT_ERROR = 2 };
 
-    /* Pick an error code */
-    if ( error != JVMTI_ERROR_NONE ) {
-        exit_code = 1;
-        if ( docoredump ) {
-            finish_logging(exit_code);
-            abort();
+    // Prepare to exit. Log error and finish logging
+    LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error,
+                                               ((msg == NULL) ? "" : msg)));
+
+    // coredump requested by command line. Keep JVMTI data dirty
+    if (error != JVMTI_ERROR_NONE && docoredump) {
+        LOG_MISC(("Dumping core as requested by command line"));
+        finish_logging();
+        abort();
+    }
+
+    finish_logging();
+
+    // Cleanup the JVMTI if we have one
+    if (gdata != NULL) {
+        gdata->vmDead = JNI_TRUE;
+        if (gdata->jvmti != NULL) {
+            // Dispose of jvmti (gdata->jvmti becomes NULL)
+            disposeEnvironment(gdata->jvmti);
         }
     }
-    if ( msg==NULL ) {
-        msg = "";
+
+    // We are here with no errors. Kill entire process and exit with zero exit code
+    if (error == JVMTI_ERROR_NONE) {
+        forceExit(EXIT_NO_ERRORS);
+        return;
     }
 
-    LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error, msg));
-
-    gdata->vmDead = JNI_TRUE;
-
-    /* Let's try and cleanup the JVMTI, if we even have one */
-    if ( gdata->jvmti != NULL ) {
-        /* Dispose of jvmti (gdata->jvmti becomes NULL) */
-        disposeEnvironment(gdata->jvmti);
+    // No transport initilized.
+    // As we don't have any details here exiting with separate exit code
+    if (error == AGENT_ERROR_TRANSPORT_INIT) {
+        forceExit(EXIT_TRANSPORT_ERROR);
+        return;
     }
 
-    /* Finish up logging. We reach here if JDWP is doing the exiting. */
-    finish_logging(exit_code);  /* Only first call matters */
+    // We have JVMTI error. Call hotspot jni_FatalError handler
+    jniFatalError(NULL, msg, error, EXIT_JVMTI_ERROR);
 
-    /* Let's give the JNI a FatalError if non-exit 0, which is historic way */
-    if ( exit_code != 0 ) {
-        JNIEnv *env = NULL;
-        jniFatalError(env, msg, error, exit_code);
-    }
+    // hotspot calls os:abort() so we should never reach code below,
+    // but guard against possible hotspot changes
 
-    /* Last chance to die, this kills the entire process. */
-    forceExit(exit_code);
+    // Last chance to die, this kills the entire process.
+    forceExit(EXIT_JVMTI_ERROR);
 }
--- a/src/share/back/log_messages.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/back/log_messages.c	Mon Aug 08 15:29:16 2016 -0700
@@ -230,7 +230,7 @@
 
 /* Finish up logging, flush output to the logfile. */
 void
-finish_logging(int exit_code)
+finish_logging()
 {
 #ifdef JDWP_LOGGING
     MUTEX_LOCK(my_mutex);
--- a/src/share/back/log_messages.h	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/back/log_messages.h	Mon Aug 08 15:29:16 2016 -0700
@@ -29,7 +29,7 @@
 /* LOG: Must be called like:  LOG_category(("anything")) or LOG_category((format,args)) */
 
 void setup_logging(const char *, unsigned);
-void finish_logging(int);
+void finish_logging();
 
 #define LOG_NULL ((void)0)
 
--- a/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,6 +26,8 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
+import java.security.ProviderException;
+
 
 /**
  * This class represents ciphers in cipher block chaining (CBC) mode.
@@ -122,31 +124,31 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + len - 1)</code>, is encrypted.
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
-     * as any excess bytes are ignored.
-     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
      * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset)
     {
-        int i;
+        if ((plainLen % blockSize) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
         int endIndex = plainOffset + plainLen;
 
         for (; plainOffset < endIndex;
              plainOffset+=blockSize, cipherOffset += blockSize) {
-            for (i=0; i<blockSize; i++) {
-                k[i] = (byte)(plain[i+plainOffset] ^ r[i]);
+            for (int i = 0; i < blockSize; i++) {
+                k[i] = (byte)(plain[i + plainOffset] ^ r[i]);
             }
             embeddedCipher.encryptBlock(k, 0, cipher, cipherOffset);
             System.arraycopy(cipher, cipherOffset, r, 0, blockSize);
@@ -159,14 +161,10 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the embedded cipher's block
-     * size, as any excess bytes are ignored.
-     *
      * <p>It is also the application's responsibility to make sure that
      * <code>init</code> has been called before this method is called.
      * (This check is omitted here, to avoid double checking.)
@@ -176,23 +174,23 @@
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
      * @return the length of the decrypted data
-     *
-     * @exception IllegalBlockSizeException if input data whose length does
-     * not correspond to the embedded cipher's block size is passed to the
-     * embedded cipher
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset)
     {
-        int i;
+        if ((cipherLen % blockSize) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
         int endIndex = cipherOffset + cipherLen;
 
         for (; cipherOffset < endIndex;
              cipherOffset += blockSize, plainOffset += blockSize) {
             embeddedCipher.decryptBlock(cipher, cipherOffset, k, 0);
-            for (i = 0; i < blockSize; i++) {
-                plain[i+plainOffset] = (byte)(k[i] ^ r[i]);
+            for (int i = 0; i < blockSize; i++) {
+                plain[i + plainOffset] = (byte)(k[i] ^ r[i]);
             }
             System.arraycopy(cipher, cipherOffset, r, 0, blockSize);
         }
--- a/src/share/classes/com/sun/crypto/provider/CipherCore.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/CipherCore.java	Mon Aug 08 15:29:16 2016 -0700
@@ -717,7 +717,7 @@
             len -= blockSize;
         }
         // do not count the trailing bytes which do not make up a unit
-        len = (len > 0 ? (len - (len%unitBytes)) : 0);
+        len = (len > 0 ? (len - (len % unitBytes)) : 0);
 
         // check output buffer capacity
         if ((output == null) ||
@@ -729,6 +729,15 @@
 
         int outLen = 0;
         if (len != 0) { // there is some work to do
+            if ((input == output)
+                 && (outputOffset < (inputOffset + inputLen))
+                 && (inputOffset < (outputOffset + buffer.length))) {
+                // copy 'input' out to avoid its content being
+                // overwritten prematurely.
+                input = Arrays.copyOfRange(input, inputOffset,
+                    inputOffset + inputLen);
+                inputOffset = 0;
+            }
             if (len <= buffered) {
                 // all to-be-processed data are from 'buffer'
                 if (decrypting) {
@@ -741,37 +750,40 @@
                     System.arraycopy(buffer, len, buffer, 0, buffered);
                 }
             } else { // len > buffered
-                if ((input != output) && (buffered == 0)) {
-                    // all to-be-processed data are from 'input'
-                    // however, note that if 'input' and 'output' are the same,
-                    // then they can't be passed directly to the underlying cipher
-                    // engine operations as data may be overwritten before they
-                    // are read.
+                int inputConsumed = len - buffered;
+                int temp;
+                if (buffered > 0) {
+                    int bufferCapacity = buffer.length - buffered;
+                    if (bufferCapacity != 0) {
+                        temp = Math.min(bufferCapacity, inputConsumed);
+                        if (unitBytes != blockSize) {
+                            temp -= ((buffered + temp) % unitBytes);
+                        }
+                        System.arraycopy(input, inputOffset, buffer, buffered, temp);
+                        inputOffset += temp;
+                        inputConsumed -= temp;
+                        inputLen -= temp;
+                        buffered += temp;
+                    }
+                    // process 'buffer'
                     if (decrypting) {
-                        outLen = cipher.decrypt(input, inputOffset, len, output, outputOffset);
+                         outLen = cipher.decrypt(buffer, 0, buffered, output, outputOffset);
                     } else {
-                        outLen = cipher.encrypt(input, inputOffset, len, output, outputOffset);
+                         outLen = cipher.encrypt(buffer, 0, buffered, output, outputOffset);
                     }
-                    inputOffset += len;
-                    inputLen -= len;
-                } else {
-                    // assemble the data using both 'buffer' and 'input'
-                    byte[] in = new byte[len];
-                    int inConsumed = len - buffered;
-                    if (buffered != 0) {
-                        System.arraycopy(buffer, 0, in, 0, buffered);
-                        buffered = 0;
+                    outputOffset += outLen;
+                    buffered = 0;
+                }
+                if (inputConsumed > 0) { // still has input to process
+                    if (decrypting) {
+                        outLen += cipher.decrypt(input, inputOffset, inputConsumed,
+                            output, outputOffset);
+                    } else {
+                        outLen += cipher.encrypt(input, inputOffset, inputConsumed,
+                            output, outputOffset);
                     }
-                    if (inConsumed != 0) {
-                        System.arraycopy(input, inputOffset, in, len - inConsumed, inConsumed);
-                        inputOffset += inConsumed;
-                        inputLen -= inConsumed;
-                    }
-                    if (decrypting) {
-                        outLen = cipher.decrypt(in, 0, len, output, outputOffset);
-                    } else {
-                        outLen = cipher.encrypt(in, 0, len, output, outputOffset);
-                    }
+                    inputOffset += inputConsumed;
+                    inputLen -= inputConsumed;
                 }
             }
             // Let's keep track of how many bytes are needed to make
@@ -934,8 +946,10 @@
         byte[] finalBuf = input;
         int finalOffset = inputOffset;
         int finalBufLen = inputLen;
-        if ((input == output) || (buffered != 0) ||
-            (!decrypting && padding != null)) {
+        if ((buffered != 0) || (!decrypting && padding != null) ||
+            ((input == output)
+              && (outputOffset < (inputOffset + inputLen))
+              && (inputOffset < (outputOffset + buffer.length)))) {
             if (decrypting || padding == null) {
                 paddingLen = 0;
             }
--- a/src/share/classes/com/sun/crypto/provider/CipherFeedback.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/CipherFeedback.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
+import java.security.ProviderException;
 
 /**
  * This class represents ciphers in cipher-feedback (CFB) mode.
@@ -133,66 +134,72 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + len - 1)</code>, is encrypted.
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the stream unit size
-     * <code>numBytes</code>, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
+     * @exception ProviderException if <code>plainLen</code> is not
+     * a multiple of the <code>numBytes</code>
      * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
-                byte[] cipher, int cipherOffset)
-    {
-        int i, len;
-        len = blockSize - numBytes;
+                byte[] cipher, int cipherOffset) {
+        if ((plainLen % numBytes) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
+
+        int nShift = blockSize - numBytes;
         int loopCount = plainLen / numBytes;
+
+        for (; loopCount > 0 ;
+             plainOffset += numBytes, cipherOffset += numBytes,
+             loopCount--) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            if (nShift != 0) {
+                System.arraycopy(register, numBytes, register, 0, nShift);
+            }
+            for (int i = 0; i < numBytes; i++) {
+                register[nShift + i] = cipher[i + cipherOffset] =
+                        (byte)(k[i] ^ plain[i + plainOffset]);
+            }
+        }
+        return plainLen;
+    }
+
+    /**
+     * Performs the last encryption operation.
+     *
+     * <p>The input plain text <code>plain</code>, starting at
+     * <code>plainOffset</code> and ending at
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * The result is stored in <code>cipher</code>, starting at
+     * <code>cipherOffset</code>.
+     *
+     * @param plain the buffer with the input data to be encrypted
+     * @param plainOffset the offset in <code>plain</code>
+     * @param plainLen the length of the input data
+     * @param cipher the buffer for the result
+     * @param cipherOffset the offset in <code>cipher</code>
+     * @return the number of bytes placed into <code>cipher</code>
+     */
+    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
+                     byte[] cipher, int cipherOffset) {
+
         int oddBytes = plainLen % numBytes;
-
-        if (len == 0) {
-            for (; loopCount > 0 ;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i = 0; i < blockSize; i++)
-                    register[i] = cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-            }
-            if (oddBytes > 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<oddBytes; i++)
-                    register[i] = cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-            }
-        } else {
-            for (; loopCount > 0 ;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                System.arraycopy(register, numBytes, register, 0, len);
-                for (i=0; i<numBytes; i++)
-                    register[i+len] = cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-
-            }
-            if (oddBytes != 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                System.arraycopy(register, numBytes, register, 0, len);
-                for (i=0; i<oddBytes; i++) {
-                    register[i+len] = cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-                }
+        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
+                          cipher, cipherOffset);
+        plainOffset += len;
+        cipherOffset += len;
+        if (oddBytes != 0) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            for (int i = 0; i < oddBytes; i++) {
+                 cipher[i + cipherOffset] =
+                    (byte)(k[i] ^ plain[i + plainOffset]);
             }
         }
         return plainLen;
@@ -203,17 +210,52 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the stream unit size
-     * <code>numBytes</code>, as any excess bytes are ignored.
+     * @param cipher the buffer with the input data to be decrypted
+     * @param cipherOffset the offset in <code>cipherOffset</code>
+     * @param cipherLen the length of the input data
+     * @param plain the buffer for the result
+     * @param plainOffset the offset in <code>plain</code>
+     * @exception ProviderException if <code>cipherLen</code> is not
+     * a multiple of the <code>numBytes</code>
+     * @return the length of the decrypted data
+     */
+    int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
+                byte[] plain, int plainOffset) {
+        if ((cipherLen % numBytes) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
+
+        int nShift = blockSize - numBytes;
+        int loopCount = cipherLen / numBytes;
+
+        for (; loopCount > 0;
+             plainOffset += numBytes, cipherOffset += numBytes,
+             loopCount--) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            if (nShift != 0) {
+                System.arraycopy(register, numBytes, register, 0, nShift);
+            }
+            for (int i = 0; i < numBytes; i++) {
+                register[i + nShift] = cipher[i + cipherOffset];
+                plain[i + plainOffset]
+                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
+            }
+        }
+        return cipherLen;
+    }
+
+    /**
+     * Performs the last decryption operation.
      *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
+     * <p>The input cipher text <code>cipher</code>, starting at
+     * <code>cipherOffset</code> and ending at
+     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
+     * The result is stored in <code>plain</code>, starting at
+     * <code>plainOffset</code>.
      *
      * @param cipher the buffer with the input data to be decrypted
      * @param cipherOffset the offset in <code>cipherOffset</code>
@@ -222,53 +264,19 @@
      * @param plainOffset the offset in <code>plain</code>
      * @return the length of the decrypted data
      */
-    int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
-                byte[] plain, int plainOffset)
-    {
-        int i, len;
-        len = blockSize - numBytes;
-        int loopCount = cipherLen / numBytes;
+    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
+                byte[] plain, int plainOffset) {
+
         int oddBytes = cipherLen % numBytes;
-
-        if (len == 0) {
-            for (; loopCount > 0;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i = 0; i < blockSize; i++) {
-                    register[i] = cipher[i+cipherOffset];
-                    plain[i+plainOffset]
-                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
-                }
-            }
-            if (oddBytes > 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<oddBytes; i++) {
-                    register[i] = cipher[i+cipherOffset];
-                    plain[i+plainOffset]
-                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
-                }
-            }
-        } else {
-            for (; loopCount > 0;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                System.arraycopy(register, numBytes, register, 0, len);
-                for (i=0; i<numBytes; i++) {
-                    register[i+len] = cipher[i+cipherOffset];
-                    plain[i+plainOffset]
-                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
-                }
-            }
-            if (oddBytes != 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                System.arraycopy(register, numBytes, register, 0, len);
-                for (i=0; i<oddBytes; i++) {
-                    register[i+len] = cipher[i+cipherOffset];
-                    plain[i+plainOffset]
-                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
-                }
+        int len = decrypt(cipher, cipherOffset, (cipherLen - oddBytes),
+                          plain, plainOffset);
+        cipherOffset += len;
+        plainOffset += len;
+        if (oddBytes != 0) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            for (int i = 0; i < oddBytes; i++) {
+                plain[i + plainOffset]
+                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
             }
         }
         return cipherLen;
--- a/src/share/classes/com/sun/crypto/provider/CounterMode.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/CounterMode.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 201313, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 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
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 
+
 /**
  * This class represents ciphers in counter (CTR) mode.
  *
@@ -136,14 +137,6 @@
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
-     * as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param in the buffer with the input data to be encrypted
      * @param inOffset the offset in <code>plain</code>
      * @param len the length of the input data
@@ -155,30 +148,7 @@
         return crypt(in, inOff, len, out, outOff);
     }
 
-    /**
-     * Performs decryption operation.
-     *
-     * <p>The input cipher text <code>cipher</code>, starting at
-     * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
-     * The result is stored in <code>plain</code>, starting at
-     * <code>plainOffset</code>.
-     *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the embedded cipher's block
-     * size, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
-     * @param in the buffer with the input data to be decrypted
-     * @param inOff the offset in <code>cipherOffset</code>
-     * @param len the length of the input data
-     * @param out the buffer for the result
-     * @param outOff the offset in <code>plain</code>
-     * @return the length of the decrypted data
-     */
+    // CTR encrypt and decrypt are identical
     int decrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
         return crypt(in, inOff, len, out, outOff);
     }
--- a/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java	Mon Aug 08 15:29:16 2016 -0700
@@ -71,6 +71,17 @@
         initialize(1024, null);
     }
 
+    private static void checkKeySize(int keysize)
+            throws InvalidParameterException {
+
+        if ((keysize < 512) || (keysize > 2048) || ((keysize & 0x3F) != 0)) {
+            throw new InvalidParameterException(
+                    "DH key size must be multiple of 64, and can only range " +
+                    "from 512 to 2048 (inclusive). " +
+                    "The specific key size " + keysize + " is not supported");
+        }
+    }
+
     /**
      * Initializes this key pair generator for a certain keysize and source of
      * randomness.
@@ -80,12 +91,8 @@
      * @param random the source of randomness
      */
     public void initialize(int keysize, SecureRandom random) {
-        if ((keysize < 512) || (keysize > 2048) || (keysize % 64 != 0)) {
-            throw new InvalidParameterException("Keysize must be multiple "
-                                                + "of 64, and can only range "
-                                                + "from 512 to 2048 "
-                                                + "(inclusive)");
-        }
+        checkKeySize(keysize);
+
         this.pSize = keysize;
         this.lSize = 0;
         this.random = random;
@@ -115,11 +122,10 @@
 
         params = (DHParameterSpec)algParams;
         pSize = params.getP().bitLength();
-        if ((pSize < 512) || (pSize > 2048) ||
-            (pSize % 64 != 0)) {
-            throw new InvalidAlgorithmParameterException
-                ("Prime size must be multiple of 64, and can only range "
-                 + "from 512 to 2048 (inclusive)");
+        try {
+            checkKeySize(pSize);
+        } catch (InvalidParameterException ipe) {
+            throw new InvalidAlgorithmParameterException(ipe.getMessage());
         }
 
         // exponent size is optional, could be 0
--- a/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java	Mon Aug 08 15:29:16 2016 -0700
@@ -59,12 +59,13 @@
     private SecureRandom random = null;
 
     private static void checkKeySize(int keysize)
-        throws InvalidAlgorithmParameterException {
-        if ((keysize != 2048) &&
+            throws InvalidParameterException {
+            if ((keysize != 2048) &&
             ((keysize < 512) || (keysize > 1024) || (keysize % 64 != 0))) {
-            throw new InvalidAlgorithmParameterException(
-                "Keysize must be multiple of 64 ranging from "
-                + "512 to 1024 (inclusive), or 2048");
+            throw new InvalidParameterException(
+                    "DH key size must be multiple of 64 and range " +
+                    "from 512 to 1024 (inclusive), or 2048. " +
+                    "The specific key size " + keysize + " is not supported");
         }
     }
 
@@ -78,11 +79,7 @@
      */
     protected void engineInit(int keysize, SecureRandom random) {
         // Re-uses DSA parameters and thus have the same range
-        try {
-            checkKeySize(keysize);
-        } catch (InvalidAlgorithmParameterException ex) {
-            throw new InvalidParameterException(ex.getMessage());
-        }
+        checkKeySize(keysize);
         this.primeSize = keysize;
         this.random = random;
     }
@@ -111,7 +108,11 @@
         primeSize = dhParamSpec.getPrimeSize();
 
         // Re-uses DSA parameters and thus have the same range
-        checkKeySize(primeSize);
+        try {
+            checkKeySize(primeSize);
+        } catch (InvalidParameterException ipe) {
+            throw new InvalidAlgorithmParameterException(ipe.getMessage());
+        }
 
         exponentSize = dhParamSpec.getExponentSize();
         if (exponentSize <= 0) {
--- a/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
+import java.security.ProviderException;
 
 /**
  * This class represents ciphers in electronic codebook (ECB) mode.
@@ -96,28 +97,24 @@
     /**
      * Performs encryption operation.
      *
-     * <p>The input plain text <code>plain</code>, starting at
-     * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + len - 1)</code>, is encrypted.
-     * The result is stored in <code>cipher</code>, starting at
-     * <code>cipherOffset</code>.
-     *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
-     * as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
+     * <p>The input plain text <code>in</code>, starting at
+     * <code>inOff</code> and ending at * <code>(inOff + len - 1)</code>,
+     * is encrypted. The result is stored in <code>out</code>, starting at
+     * <code>outOff</code>.
      *
      * @param in the buffer with the input data to be encrypted
-     * @param inOffset the offset in <code>plain</code>
+     * @param inOff the offset in <code>plain</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOff the offset in <code>cipher</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
      * @return the length of the encrypted data
      */
     int encrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
+        if ((len % blockSize) != 0) {
+             throw new ProviderException("Internal error in input buffering");
+        }
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.encryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
@@ -129,28 +126,24 @@
     /**
      * Performs decryption operation.
      *
-     * <p>The input cipher text <code>cipher</code>, starting at
-     * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
-     * The result is stored in <code>plain</code>, starting at
-     * <code>plainOffset</code>.
-     *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the embedded cipher's block
-     * size, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
+     * <p>The input cipher text <code>in</code>, starting at
+     * <code>inOff</code> and ending at * <code>(inOff + len - 1)</code>,
+     * is decrypted.The result is stored in <code>out</code>, starting at
+     * <code>outOff</code>.
      *
      * @param in the buffer with the input data to be decrypted
      * @param inOff the offset in <code>cipherOffset</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOff the offset in <code>plain</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
      * @return the length of the decrypted data
      */
     int decrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
+        if ((len % blockSize) != 0) {
+             throw new ProviderException("Internal error in input buffering");
+        }
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.decryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
--- a/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java	Mon Aug 08 15:29:16 2016 -0700
@@ -403,23 +403,21 @@
      * and ending at <code>(inOff + len - 1)</code>, is encrypted. The result
      * is stored in <code>out</code>, starting at <code>outOfs</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>len</code> is a multiple of the embedded cipher's block size,
-     * otherwise, a ProviderException will be thrown.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param in the buffer with the input data to be encrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOfs the offset in <code>out</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
+     * @return the number of bytes placed into the <code>out</code> buffer
      */
     int encrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
         checkDataLength(processed, len);
 
+        if ((len % blockSize) != 0) {
+             throw new ProviderException("Internal error in input buffering");
+        }
         processAAD();
         if (len > 0) {
             gctrPAndC.update(in, inOfs, len, out, outOfs);
@@ -432,9 +430,6 @@
     /**
      * Performs encryption operation for the last time.
      *
-     * <p>NOTE: <code>len</code> may not be multiple of the embedded
-     * cipher's block size for this call.
-     *
      * @param in the input buffer with the data to be encrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
@@ -479,23 +474,21 @@
      * is decrypted. The result is stored in <code>out</code>, starting at
      * <code>outOfs</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>len</code> is a multiple of the embedded cipher's block
-     * size, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param in the buffer with the input data to be decrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOfs the offset in <code>out</code>
+     * @exception ProviderException if <code>len</code> is not
+     * a multiple of the block size
+     * @return the number of bytes placed into the <code>out</code> buffer
      */
     int decrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
         checkDataLength(ibuffer.size(), len);
 
+        if ((len % blockSize) != 0) {
+             throw new ProviderException("Internal error in input buffering");
+        }
         processAAD();
 
         if (len > 0) {
--- a/src/share/classes/com/sun/crypto/provider/JceKeyStore.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/JceKeyStore.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -864,7 +864,9 @@
                         if (computed[i] != actual[i]) {
                             throw new IOException(
                                 "Keystore was tampered with, or "
-                                + "password was incorrect");
+                                + "password was incorrect",
+                                    new UnrecoverableKeyException(
+                                            "Password verification failed"));
                         }
                     }
                 }
--- a/src/share/classes/com/sun/crypto/provider/OutputFeedback.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/OutputFeedback.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,6 +26,7 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
+import java.security.ProviderException;
 
 /**
  * This class represents ciphers in output-feedback (OFB) mode.
@@ -132,17 +133,52 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + len - 1)</code>, is encrypted.
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the stream unit size
-     * <code>numBytes</code>, as any excess bytes are ignored.
+     * @param plain the buffer with the input data to be encrypted
+     * @param plainOffset the offset in <code>plain</code>
+     * @param plainLen the length of the input data
+     * @param cipher the buffer for the result
+     * @param cipherOffset the offset in <code>cipher</code>
+     * @exception ProviderException if <code>plainLen</code> is not
+     * a multiple of the <code>numBytes</code>
+     * @return the length of the encrypted data
+     */
+    int encrypt(byte[] plain, int plainOffset, int plainLen,
+                byte[] cipher, int cipherOffset) {
+
+        if ((plainLen % numBytes) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
+        int nShift = blockSize - numBytes;
+        int loopCount = plainLen / numBytes;
+
+        for (; loopCount > 0;
+             plainOffset += numBytes, cipherOffset += numBytes,
+             loopCount--) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            for (int i = 0; i < numBytes; i++) {
+                cipher[i + cipherOffset] =
+                    (byte)(k[i] ^ plain[i + plainOffset]);
+                if (nShift != 0) {
+                    System.arraycopy(register, numBytes, register, 0, nShift);
+                }
+                System.arraycopy(k, 0, register, nShift, numBytes);
+            }
+        }
+        return plainLen;
+    }
+
+    /**
+     * Performs last encryption operation.
      *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
+     * <p>The input plain text <code>plain</code>, starting at
+     * <code>plainOffset</code> and ending at
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * The result is stored in <code>cipher</code>, starting at
+     * <code>cipherOffset</code>.
      *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
@@ -151,82 +187,34 @@
      * @param cipherOffset the offset in <code>cipher</code>
      * @return the length of the encrypted data
      */
-    int encrypt(byte[] plain, int plainOffset, int plainLen,
-                byte[] cipher, int cipherOffset)
-    {
-        int i;
-        int len = blockSize - numBytes;
-        int loopCount = plainLen / numBytes;
+    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
+                     byte[] cipher, int cipherOffset) {
         int oddBytes = plainLen % numBytes;
+        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
+                          cipher, cipherOffset);
+        plainOffset += len;
+        cipherOffset += len;
 
-        if (len == 0) {
-            for (; loopCount > 0;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<numBytes; i++)
-                    cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-                System.arraycopy(k, 0, register, 0, numBytes);
-            }
-            if (oddBytes > 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<oddBytes; i++)
-                    cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-                System.arraycopy(k, 0, register, 0, numBytes);
-            }
-        } else {
-            for (; loopCount > 0;
-                 plainOffset += numBytes, cipherOffset += numBytes,
-                 loopCount--) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<numBytes; i++)
-                    cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-                System.arraycopy(register, numBytes, register, 0, len);
-                System.arraycopy(k, 0, register, len, numBytes);
-            }
-            if (oddBytes > 0) {
-                embeddedCipher.encryptBlock(register, 0, k, 0);
-                for (i=0; i<oddBytes; i++)
-                    cipher[i+cipherOffset] =
-                        (byte)(k[i] ^ plain[i+plainOffset]);
-                System.arraycopy(register, numBytes, register, 0, len);
-                System.arraycopy(k, 0, register, len, numBytes);
+        if (oddBytes != 0) {
+            embeddedCipher.encryptBlock(register, 0, k, 0);
+            for (int i = 0; i < oddBytes; i++) {
+                cipher[i + cipherOffset] =
+                    (byte)(k[i] ^ plain[ i + plainOffset]);
             }
         }
         return plainLen;
     }
 
-    /**
-     * Performs decryption operation.
-     *
-     * <p>The input cipher text <code>cipher</code>, starting at
-     * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
-     * The result is stored in <code>plain</code>, starting at
-     * <code>plainOffset</code>.
-     *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the stream unit size
-     * <code>numBytes</code>, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
-     * @param cipher the buffer with the input data to be decrypted
-     * @param cipherOffset the offset in <code>cipherOffset</code>
-     * @param cipherLen the length of the input data
-     * @param plain the buffer for the result
-     * @param plainOffset the offset in <code>plain</code>
-     * @return the length of the decrypted data
-     */
+    // OFB encrypt and decrypt are identical
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
-                        byte[] plain, int plainOffset)
-    {
-        // OFB encrypt and decrypt are identical
+                byte[] plain, int plainOffset) {
         return encrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
     }
+
+    // OFB encrypt and decrypt are identical
+    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
+                     byte[] plain, int plainOffset) {
+        // OFB encrypt and decrypt are identical
+        return encryptFinal(cipher, cipherOffset, cipherLen, plain, plainOffset);
+    }
 }
--- a/src/share/classes/com/sun/crypto/provider/PCBC.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/crypto/provider/PCBC.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,6 +26,8 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
+import java.security.ProviderException;
+
 
 /**
  * This class represents ciphers in Plaintext Cipher Block Chaining (PCBC)
@@ -118,38 +120,36 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + len - 1)</code>, is encrypted.
+     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
-     * as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
+     * @exception ProviderException if <code>plainLen</code> is not
+     * a multiple of the block size
+     * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset)
     {
+        if ((plainLen % blockSize) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
         int i;
         int endIndex = plainOffset + plainLen;
 
         for (; plainOffset < endIndex;
              plainOffset += blockSize, cipherOffset += blockSize) {
-            for (i=0; i<blockSize; i++) {
-                k[i] ^= plain[i+plainOffset];
+            for (i = 0; i < blockSize; i++) {
+                k[i] ^= plain[i + plainOffset];
             }
             embeddedCipher.encryptBlock(k, 0, cipher, cipherOffset);
             for (i = 0; i < blockSize; i++) {
-                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
+                k[i] = (byte)(plain[i + plainOffset] ^ cipher[i + cipherOffset]);
             }
         }
         return plainLen;
@@ -160,27 +160,25 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
-     * <p>It is the application's responsibility to make sure that
-     * <code>cipherLen</code> is a multiple of the embedded cipher's block
-     * size, as any excess bytes are ignored.
-     *
-     * <p>It is also the application's responsibility to make sure that
-     * <code>init</code> has been called before this method is called.
-     * (This check is omitted here, to avoid double checking.)
-     *
      * @param cipher the buffer with the input data to be decrypted
      * @param cipherOffset the offset in <code>cipherOffset</code>
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
+     * @exception ProviderException if <code>cipherLen</code> is not
+     * a multiple of the block size
+     * @return the length of the decrypted data
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset)
     {
+        if ((cipherLen % blockSize) != 0) {
+             throw new ProviderException("Internal error in input buffering");
+        }
         int i;
         int endIndex = cipherOffset + cipherLen;
 
@@ -189,10 +187,10 @@
             embeddedCipher.decryptBlock(cipher, cipherOffset,
                                    plain, plainOffset);
             for (i = 0; i < blockSize; i++) {
-                plain[i+plainOffset] ^= k[i];
+                plain[i + plainOffset] ^= k[i];
             }
             for (i = 0; i < blockSize; i++) {
-                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
+                k[i] = (byte)(plain[i + plainOffset] ^ cipher[i + cipherOffset]);
             }
         }
         return cipherLen;
--- a/src/share/classes/com/sun/java/accessibility/util/package-info.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/java/accessibility/util/package-info.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2015, 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
--- a/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java	Mon Aug 08 15:29:16 2016 -0700
@@ -300,7 +300,7 @@
         errEx = e;
     }
 
-    protected abstract AbstractLdapNamingEnumeration<T> getReferredResults(
+    protected abstract AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
             LdapReferralContext refCtx) throws NamingException;
 
     /*
@@ -360,7 +360,7 @@
      * Merge the entries and/or referrals from the supplied enumeration
      * with those of the current enumeration.
      */
-    protected void update(AbstractLdapNamingEnumeration<T> ne) {
+    protected void update(AbstractLdapNamingEnumeration<? extends NameClassPair> ne) {
         // Cleanup previous context first
         homeCtx.decEnumCount();
 
--- a/src/share/classes/com/sun/jndi/ldap/DigestClientId.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/DigestClientId.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,6 @@
 
     final private String[] propvals;
     final private int myHash;
-    private int pHash = 0;
 
     DigestClientId(int version, String hostname, int port,
         String protocol, Control[] bindCtls, OutputStream trace,
@@ -78,12 +77,9 @@
             propvals = new String[SASL_PROPS.length];
             for (int i = 0; i < SASL_PROPS.length; i++) {
                 propvals[i] = (String) env.get(SASL_PROPS[i]);
-                if (propvals[i] != null) {
-                    pHash = pHash * 31 + propvals[i].hashCode();
-                }
             }
         }
-        myHash = super.hashCode() + pHash;
+        myHash = super.hashCode() ^ Arrays.hashCode(propvals);
     }
 
     public boolean equals(Object obj) {
@@ -92,7 +88,6 @@
         }
         DigestClientId other = (DigestClientId)obj;
         return myHash == other.myHash
-            && pHash == other.pHash
             && super.equals(obj)
             && Arrays.equals(propvals, other.propvals);
     }
--- a/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java	Mon Aug 08 15:29:16 2016 -0700
@@ -104,9 +104,9 @@
     }
 
     @Override
-    protected LdapBindingEnumeration getReferredResults(
+    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
             LdapReferralContext refCtx) throws NamingException{
         // repeat the original operation at the new context
-        return (LdapBindingEnumeration)refCtx.listBindings(listArg);
+        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.listBindings(listArg);
     }
 }
--- a/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java	Mon Aug 08 15:29:16 2016 -0700
@@ -72,9 +72,9 @@
     }
 
     @Override
-    protected LdapNamingEnumeration getReferredResults(
+    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
             LdapReferralContext refCtx) throws NamingException {
         // repeat the original operation at the new context
-        return (LdapNamingEnumeration)refCtx.list(listArg);
+        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.list(listArg);
     }
 }
--- a/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java	Mon Aug 08 15:29:16 2016 -0700
@@ -199,15 +199,15 @@
     }
 
     @Override
-    protected LdapSearchEnumeration getReferredResults(
+    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
             LdapReferralContext refCtx) throws NamingException {
         // repeat the original operation at the new context
-        return (LdapSearchEnumeration)refCtx.search(
+        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.search(
                 searchArgs.name, searchArgs.filter, searchArgs.cons);
     }
 
     @Override
-    protected void update(AbstractLdapNamingEnumeration<SearchResult> ne) {
+    protected void update(AbstractLdapNamingEnumeration<? extends NameClassPair> ne) {
         super.update(ne);
 
         // Update search-specific variables
--- a/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,21 +49,23 @@
                 socketFactory);
 
         this.username = username;
+        int pwdHashCode = 0;
         if (passwd == null) {
             this.passwd = null;
-        } else if (passwd instanceof String) {
-            this.passwd = passwd;
         } else if (passwd instanceof byte[]) {
             this.passwd = ((byte[])passwd).clone();
+            pwdHashCode = Arrays.hashCode((byte[])passwd);
         } else if (passwd instanceof char[]) {
             this.passwd = ((char[])passwd).clone();
+            pwdHashCode = Arrays.hashCode((char[])passwd);
         } else {
             this.passwd = passwd;
+            pwdHashCode = passwd.hashCode();
         }
 
         myHash = super.hashCode()
-            + (username != null ? username.hashCode() : 0)
-            + (passwd != null ? passwd.hashCode() : 0);
+            ^ (username != null ? username.hashCode() : 0)
+            ^ pwdHashCode;
     }
 
     public boolean equals(Object obj) {
--- a/src/share/classes/com/sun/jndi/ldap/pool/Pool.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/jndi/ldap/pool/Pool.java	Mon Aug 08 15:29:16 2016 -0700
@@ -118,7 +118,11 @@
         PooledConnectionFactory factory) throws NamingException {
 
         d("get(): ", id);
-        d("size: ", map.size());
+        if (debug) {
+            synchronized (map) {
+                d("size: ", map.size());
+            }
+        }
 
         expungeStaleConnections();
 
@@ -141,10 +145,9 @@
                 // Keep the weak reference through the element of a linked list
                 weakRefs.add(weakRef);
             }
+            d("get(): size after: ", map.size());
         }
 
-        d("get(): size after: ", map.size());
-
         return conns.get(timeout, factory); // get one connection from list
     }
 
@@ -209,19 +212,24 @@
         out.println("maximum pool size: " + maxSize);
         out.println("preferred pool size: " + prefSize);
         out.println("initial pool size: " + initSize);
-        out.println("current pool size: " + map.size());
 
-        for (Map.Entry<Object, ConnectionsRef> entry : map.entrySet()) {
-            id = entry.getKey();
-            conns = entry.getValue().getConnections();
-            out.println("   " + id + ":" + conns.getStats());
+        synchronized (map) {
+            out.println("current pool size: " + map.size());
+
+            for (Map.Entry<Object, ConnectionsRef> entry : map.entrySet()) {
+                id = entry.getKey();
+                conns = entry.getValue().getConnections();
+                out.println("   " + id + ":" + conns.getStats());
+            }
         }
 
         out.println("====== Pool end =====================");
     }
 
     public String toString() {
-        return super.toString() + " " + map.toString();
+        synchronized (map) {
+            return super.toString() + " " + map.toString();
+        }
     }
 
     private void d(String msg, int i) {
--- a/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -133,6 +133,10 @@
             if (!vmDied) {
                 vmDisconnectEvent(event);
             }
+            /*
+             * Inform jdb command line processor that jdb is being shutdown. JDK-8154144.
+             */
+            ((TTY)notifier).setShuttingDown(true);
             Env.shutdown(shutdownMessageKey);
             return false;
         } else {
--- a/src/share/classes/com/sun/tools/example/debug/tty/TTY.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/com/sun/tools/example/debug/tty/TTY.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,6 +56,16 @@
      */
     private static final String progname = "jdb";
 
+    private volatile boolean shuttingDown = false;
+
+    public void setShuttingDown(boolean s) {
+       shuttingDown = s;
+    }
+
+    public boolean isShuttingDown() {
+        return shuttingDown;
+    }
+
     @Override
     public void vmStartEvent(VMStartEvent se)  {
         Thread.yield();  // fetch output
@@ -750,7 +760,13 @@
             while (true) {
                 String ln = in.readLine();
                 if (ln == null) {
-                    MessageOutput.println("Input stream closed.");
+                    /*
+                     *  Jdb is being shutdown because debuggee exited, ignore any 'null'
+                     *  returned by readLine() during shutdown. JDK-8154144.
+                     */
+                    if (!isShuttingDown()) {
+                        MessageOutput.println("Input stream closed.");
+                    }
                     ln = "quit";
                 }
 
--- a/src/share/classes/java/awt/SplashScreen.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/java/awt/SplashScreen.java	Mon Aug 08 15:29:16 2016 -0700
@@ -250,7 +250,7 @@
             assert scale > 0;
             if (scale > 0 && scale != 1) {
                 bounds.setSize((int) (bounds.getWidth() / scale),
-                        (int) (bounds.getWidth() / scale));
+                        (int) (bounds.getHeight() / scale));
             }
             return bounds;
         }
--- a/src/share/classes/java/lang/invoke/MethodHandles.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/java/lang/invoke/MethodHandles.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -915,6 +915,9 @@
          * @throws NullPointerException if any argument is null
          */
         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
+            if (refc.isArray()) {
+                throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
+            }
             String name = "<init>";
             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
             return getDirectConstructor(refc, ctor);
--- a/src/share/classes/java/security/ProtectionDomain.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/java/security/ProtectionDomain.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,12 +25,16 @@
 
 package java.security;
 
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
 import java.util.Map;
-import java.util.WeakHashMap;
+import java.util.concurrent.ConcurrentHashMap;
 import sun.misc.JavaSecurityProtectionDomainAccess;
 import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
 import sun.security.util.Debug;
@@ -456,24 +460,14 @@
     /**
      * Used for storing ProtectionDomains as keys in a Map.
      */
-    final class Key {}
+    static final class Key {}
 
     static {
         SharedSecrets.setJavaSecurityProtectionDomainAccess(
             new JavaSecurityProtectionDomainAccess() {
+                @Override
                 public ProtectionDomainCache getProtectionDomainCache() {
-                    return new ProtectionDomainCache() {
-                        private final Map<Key, PermissionCollection> map =
-                            Collections.synchronizedMap
-                                (new WeakHashMap<Key, PermissionCollection>());
-                        public void put(ProtectionDomain pd,
-                            PermissionCollection pc) {
-                            map.put((pd == null ? null : pd.key), pc);
-                        }
-                        public PermissionCollection get(ProtectionDomain pd) {
-                            return pd == null ? map.get(null) : map.get(pd.key);
-                        }
-                    };
+                    return new PDCache();
                 }
 
                 @Override
@@ -482,4 +476,119 @@
                 }
             });
     }
+
+    /**
+     * A cache of ProtectionDomains and their Permissions.
+     *
+     * This class stores ProtectionDomains as weak keys in a ConcurrentHashMap
+     * with additional support for checking and removing weak keys that are no
+     * longer in use. There can be cases where the permission collection may
+     * have a chain of strong references back to the ProtectionDomain, which
+     * ordinarily would prevent the entry from being removed from the map. To
+     * address that, we wrap the permission collection in a SoftReference so
+     * that it can be reclaimed by the garbage collector due to memory demand.
+     */
+    private static class PDCache implements ProtectionDomainCache {
+        private final ConcurrentHashMap<WeakProtectionDomainKey,
+                                        SoftReference<PermissionCollection>>
+                                        pdMap = new ConcurrentHashMap<>();
+        private final ReferenceQueue<Key> queue = new ReferenceQueue<>();
+
+        @Override
+        public void put(ProtectionDomain pd, PermissionCollection pc) {
+            processQueue(queue, pdMap);
+            WeakProtectionDomainKey weakPd =
+                new WeakProtectionDomainKey(pd, queue);
+            pdMap.put(weakPd, new SoftReference<>(pc));
+        }
+
+        @Override
+        public PermissionCollection get(ProtectionDomain pd) {
+            processQueue(queue, pdMap);
+            WeakProtectionDomainKey weakPd = new WeakProtectionDomainKey(pd);
+            SoftReference<PermissionCollection> sr = pdMap.get(weakPd);
+            return (sr == null) ? null : sr.get();
+        }
+
+        /**
+         * Removes weak keys from the map that have been enqueued
+         * on the reference queue and are no longer in use.
+         */
+        private static void processQueue(ReferenceQueue<Key> queue,
+                                         ConcurrentHashMap<? extends
+                                         WeakReference<Key>, ?> pdMap) {
+            Reference<? extends Key> ref;
+            while ((ref = queue.poll()) != null) {
+                pdMap.remove(ref);
+            }
+        }
+    }
+
+    /**
+     * A weak key for a ProtectionDomain.
+     */
+    private static class WeakProtectionDomainKey extends WeakReference<Key> {
+        /**
+         * Saved value of the referent's identity hash code, to maintain
+         * a consistent hash code after the referent has been cleared
+         */
+        private final int hash;
+
+        /**
+         * A key representing a null ProtectionDomain.
+         */
+        private static final Key NULL_KEY = new Key();
+
+        /**
+         * Create a new WeakProtectionDomain with the specified domain and
+         * registered with a queue.
+         */
+        WeakProtectionDomainKey(ProtectionDomain pd, ReferenceQueue<Key> rq) {
+            this((pd == null ? NULL_KEY : pd.key), rq);
+        }
+
+        WeakProtectionDomainKey(ProtectionDomain pd) {
+            this(pd == null ? NULL_KEY : pd.key);
+        }
+
+        private WeakProtectionDomainKey(Key key, ReferenceQueue<Key> rq) {
+            super(key, rq);
+            hash = key.hashCode();
+        }
+
+        private WeakProtectionDomainKey(Key key) {
+            super(key);
+            hash = key.hashCode();
+        }
+
+        /**
+         * Returns the identity hash code of the original referent.
+         */
+        @Override
+        public int hashCode() {
+            return hash;
+        }
+
+        /**
+         * Returns true if the given object is an identical
+         * WeakProtectionDomainKey instance, or, if this object's referent
+         * has not been cleared and the given object is another
+         * WeakProtectionDomainKey instance with an identical non-null
+         * referent as this one.
+         */
+        @Override
+        public boolean equals(Object obj) {
+            if (obj == this) {
+                return true;
+            }
+
+            if (obj instanceof WeakProtectionDomainKey) {
+                Object referent = get();
+                return (referent != null) &&
+                       (referent == ((WeakProtectionDomainKey)obj).get());
+            } else {
+                return false;
+            }
+        }
+    }
 }
--- a/src/share/classes/java/security/SecureRandom.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/java/security/SecureRandom.java	Mon Aug 08 15:29:16 2016 -0700
@@ -464,7 +464,7 @@
      * @param bytes the array to be filled in with random bytes.
      */
     @Override
-    synchronized public void nextBytes(byte[] bytes) {
+    public void nextBytes(byte[] bytes) {
         secureRandomSpi.engineNextBytes(bytes);
     }
 
--- a/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -125,8 +125,6 @@
     protected MouseMotionListener popupMouseMotionListener;
     protected KeyListener popupKeyListener;
 
-    private MouseWheelListener mouseWheelListener;
-
     // This is used for knowing when to cache the minimum preferred size.
     // If the data in the list changes, the cached value get marked for recalc.
     // Added to the current JComboBox model
@@ -377,10 +375,6 @@
                 comboBox.getModel().addListDataListener( listDataListener );
             }
         }
-
-        if ((mouseWheelListener = createMouseWheelListener()) != null) {
-            comboBox.addMouseWheelListener(mouseWheelListener);
-        }
     }
 
     /**
@@ -427,9 +421,6 @@
                 comboBox.getModel().removeListDataListener( listDataListener );
             }
         }
-        if (mouseWheelListener != null) {
-            comboBox.removeMouseWheelListener(mouseWheelListener);
-        }
     }
 
     /**
@@ -543,10 +534,6 @@
         return handler;
     }
 
-    private MouseWheelListener createMouseWheelListener() {
-        return getHandler();
-    }
-
     //
     // end UI Initialization
     //======================
@@ -1682,8 +1669,7 @@
     //
     private class Handler implements ActionListener, FocusListener,
                                      KeyListener, LayoutManager,
-                                     ListDataListener, PropertyChangeListener,
-                                     MouseWheelListener {
+                                     ListDataListener, PropertyChangeListener {
         //
         // PropertyChangeListener
         //
@@ -1967,10 +1953,6 @@
                 }
             }
         }
-
-        public void mouseWheelMoved(MouseWheelEvent e) {
-            e.consume();
-        }
    }
 
     class DefaultKeySelectionManager implements JComboBox.KeySelectionManager, UIResource {
--- a/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -345,17 +345,26 @@
     // PopupMenuListeners.
 
     protected void firePopupMenuWillBecomeVisible() {
+        if (scrollerMouseWheelListener != null) {
+            comboBox.addMouseWheelListener(scrollerMouseWheelListener);
+        }
         super.firePopupMenuWillBecomeVisible();
         // comboBox.firePopupMenuWillBecomeVisible() is called from BasicComboPopup.show() method
         // to let the user change the popup menu from the PopupMenuListener.popupMenuWillBecomeVisible()
     }
 
     protected void firePopupMenuWillBecomeInvisible() {
+        if (scrollerMouseWheelListener != null) {
+            comboBox.removeMouseWheelListener(scrollerMouseWheelListener);
+        }
         super.firePopupMenuWillBecomeInvisible();
         comboBox.firePopupMenuWillBecomeInvisible();
     }
 
     protected void firePopupMenuCanceled() {
+        if (scrollerMouseWheelListener != null) {
+            comboBox.removeMouseWheelListener(scrollerMouseWheelListener);
+        }
         super.firePopupMenuCanceled();
         comboBox.firePopupMenuCanceled();
     }
@@ -997,6 +1006,8 @@
             if (e.getStateChange() == ItemEvent.SELECTED) {
                 JComboBox comboBox = (JComboBox)e.getSource();
                 setListSelection(comboBox.getSelectedIndex());
+            } else {
+                setListSelection(-1);
             }
         }
 
--- a/src/share/classes/javax/swing/plaf/nimbus/skin.laf	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/javax/swing/plaf/nimbus/skin.laf	Mon Aug 08 15:29:16 2016 -0700
@@ -13407,7 +13407,7 @@
             <cacheSettingsInherited>false</cacheSettingsInherited>
             <cacheMode>NO_CACHING</cacheMode>
             <uiproperties>
-               <uiProperty name="rendererUseListColors" type="BOOLEAN" value="true"/>
+               <uiProperty name="rendererUseListColors" type="BOOLEAN" value="false"/>
                <uiProperty name="rendererUseUIBorder" type="BOOLEAN" value="true"/>
                <uiProperty name="cellNoFocusBorder" type="BORDER">
                    <border type="empty" top="2" left="5" bottom="2" right="5"/>
@@ -13513,10 +13513,10 @@
                   <uiproperties/>
                </style>
                <backgroundStates>
-                  <state stateKeys="Disabled">
+                  <state stateKeys="Selected">
                      <style>
                         <textForeground>
-                           <matte red="142" green="143" blue="145" alpha="255" uiDefaultParentName="nimbusDisabledText" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
+                           <matte red="255" green="255" blue="255" alpha="255" uiDefaultParentName="nimbusLightBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
                         </textForeground>
                         <textBackground/>
                         <background>
@@ -13541,6 +13541,56 @@
                         </layer>
                      </canvas>
                   </state>
+                  <state stateKeys="Disabled+Selected">
+                     <style>
+                        <textForeground/>
+                        <textBackground/>
+                        <background>
+                           <matte red="57" green="105" blue="138" alpha="255" uiDefaultParentName="nimbusSelectionBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
+                        </background>
+                        <inherit-background>false</inherit-background>
+                        <uiproperties/>
+                     </style>
+                     <canvas>
+                        <size width="100" height="30"/>
+                        <nextLayerNameIndex>2</nextLayerNameIndex>
+                        <stretchingInsets top="0" bottom="0" left="0" right="0"/>
+                        <layer name="Layer 1">
+                           <opacity>1.0</opacity>
+                           <fillOpacity>1.0</fillOpacity>
+                           <blendingMode>NORMAL</blendingMode>
+                           <locked>false</locked>
+                           <visible>true</visible>
+                           <shapes/>
+                           <effects/>
+                        </layer>
+                     </canvas>
+                  </state>
+                  <state stateKeys="Disabled">
+                     <style>
+                        <textForeground>
+                           <matte red="142" green="143" blue="145" alpha="255" uiDefaultParentName="nimbusDisabledText" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
+                        </textForeground>
+                        <textBackground/>
+                        <background/>
+                        <inherit-textForeground>false</inherit-textForeground>
+                        <uiproperties/>
+                     </style>
+                     <canvas>
+                        <size width="100" height="30"/>
+                        <nextLayerNameIndex>2</nextLayerNameIndex>
+                        <stretchingInsets top="0" bottom="0" left="0" right="0"/>
+                        <layer name="Layer 1">
+                           <opacity>1.0</opacity>
+                           <fillOpacity>1.0</fillOpacity>
+                           <blendingMode>NORMAL</blendingMode>
+                           <locked>false</locked>
+                           <visible>true</visible>
+                           <shapes/>
+                           <effects/>
+                        </layer>
+                     </canvas>
+                  </state>
                </backgroundStates>
                <foregroundStates/>
                <borderStates/>
--- a/src/share/classes/javax/swing/text/html/parser/Parser.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/javax/swing/text/html/parser/Parser.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1986,57 +1986,69 @@
         while (true) {
             int i = 0;
             while (!insideComment && i < SCRIPT_END_TAG.length
-                       && (SCRIPT_END_TAG[i] == ch
-                           || SCRIPT_END_TAG_UPPER_CASE[i] == ch)) {
+                    && (SCRIPT_END_TAG[i] == ch
+                    || SCRIPT_END_TAG_UPPER_CASE[i] == ch)) {
                 charsToAdd[i] = (char) ch;
                 ch = readCh();
                 i++;
             }
             if (i == SCRIPT_END_TAG.length) {
+                return;
+            }
 
-                /*  '</script>' tag detected */
-                /* Here, ch == the first character after </script> */
+            if (!insideComment && i == 1 && charsToAdd[0] == START_COMMENT.charAt(0)) {
+                // it isn't end script tag, but may be it's start comment tag?
+                while (i < START_COMMENT.length()
+                        && START_COMMENT.charAt(i) == ch) {
+                    charsToAdd[i] = (char) ch;
+                    ch = readCh();
+                    i++;
+                }
+                if (i == START_COMMENT.length()) {
+                    insideComment = true;
+                }
+            }
+            if (insideComment) {
+                while (i < END_COMMENT.length()
+                        && END_COMMENT.charAt(i) == ch) {
+                    charsToAdd[i] = (char) ch;
+                    ch = readCh();
+                    i++;
+                }
+                if (i == END_COMMENT.length()) {
+                    insideComment = false;
+                }
+            }
+
+            /* To account for extra read()'s that happened */
+            for (int j = 0; j < i; j++) {
+                addString(charsToAdd[j]);
+            }
+            switch (ch) {
+            case -1:
+                error("eof.script");
                 return;
-            } else {
-
-                /* To account for extra read()'s that happened */
-                for (int j = 0; j < i; j++) {
-                    addString(charsToAdd[j]);
+            case '\n':
+                ln++;
+                ch = readCh();
+                lfCount++;
+                addString('\n');
+                break;
+            case '\r':
+                ln++;
+                if ((ch = readCh()) == '\n') {
+                    ch = readCh();
+                    crlfCount++;
+                } else {
+                    crCount++;
                 }
-
-                switch (ch) {
-                case -1:
-                    error("eof.script");
-                    return;
-                case '\n':
-                    ln++;
-                    ch = readCh();
-                    lfCount++;
-                    addString('\n');
-                    break;
-                case '\r':
-                    ln++;
-                    if ((ch = readCh()) == '\n') {
-                        ch = readCh();
-                        crlfCount++;
-                    } else {
-                        crCount++;
-                    }
-                    addString('\n');
-                    break;
-                default:
-                    addString(ch);
-                    String str = new String(getChars(0, strpos));
-                    if (!insideComment && str.endsWith(START_COMMENT)) {
-                        insideComment = true;
-                    }
-                    if (insideComment && str.endsWith(END_COMMENT)) {
-                        insideComment = false;
-                    }
-                    ch = readCh();
-                    break;
-                } // switch
-            }
+                addString('\n');
+                break;
+            default:
+                addString(ch);
+                ch = readCh();
+                break;
+            } // switch
         } // while
     }
 
--- a/src/share/classes/sun/font/CompositeFont.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/font/CompositeFont.java	Mon Aug 08 15:29:16 2016 -0700
@@ -270,10 +270,21 @@
                 if (componentNames[slot] == null) {
                     componentNames[slot] = name;
                 } else if (!componentNames[slot].equalsIgnoreCase(name)) {
-                    components[slot] =
-                        (PhysicalFont) fm.findFont2D(componentNames[slot],
-                                                     style,
+                    /* If a component specifies the file with a bad font,
+                     * the corresponding slot will be initialized by
+                     * default physical font. In such case findFont2D may
+                     * return composite font which cannot be casted to
+                     * physical font.
+                     */
+                    try {
+                        components[slot] =
+                            (PhysicalFont) fm.findFont2D(componentNames[slot],
+                                                         style,
                                                 FontManager.PHYSICAL_FALLBACK);
+                    } catch (ClassCastException cce) {
+                        /* Assign default physical font to the slot */
+                        components[slot] = fm.getDefaultPhysicalFont();
+                    }
                 }
             }
             deferredInitialisation[slot] = false;
--- a/src/share/classes/sun/font/FontFamily.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/font/FontFamily.java	Mon Aug 08 15:29:16 2016 -0700
@@ -335,10 +335,10 @@
         case Font.BOLD|Font.ITALIC:
             if (bolditalic != null) {
                 return bolditalic;
+            } else if (bold != null && bold.canDoStyle(style)) {
+                return bold;
             } else if (italic != null && italic.canDoStyle(style)) {
                     return italic;
-            } else if (bold != null && bold.canDoStyle(style)) {
-                    return italic;
             } else if (plain != null && plain.canDoStyle(style)) {
                     return plain;
             } else {
--- a/src/share/classes/sun/font/ScriptRunData.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/font/ScriptRunData.java	Mon Aug 08 15:29:16 2016 -0700
@@ -44,7 +44,7 @@
         if (cp >= data[cache] && cp < data[cache+2]) {
             return data[cache+1];
         }
-        if (cp >= CHAR_START & cp < CHAR_LIMIT) {
+        if ((cp >= CHAR_START) && (cp < CHAR_LIMIT)) {
             int probe = dataPower;
             int index = 0;
 
--- a/src/share/classes/sun/java2d/opengl/OGLMaskFill.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/java2d/opengl/OGLMaskFill.java	Mon Aug 08 15:29:16 2016 -0700
@@ -26,6 +26,7 @@
 package sun.java2d.opengl;
 
 import java.awt.Composite;
+import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.GraphicsPrimitive;
 import sun.java2d.loops.GraphicsPrimitiveMgr;
@@ -67,7 +68,14 @@
     protected void validateContext(SunGraphics2D sg2d,
                                    Composite comp, int ctxflags)
     {
-        OGLSurfaceData dstData = (OGLSurfaceData)sg2d.surfaceData;
+        OGLSurfaceData dstData;
+        try {
+            dstData = (OGLSurfaceData) sg2d.surfaceData;
+        } catch (ClassCastException e) {
+            throw new InvalidPipeException("wrong surface data type: " +
+                                           sg2d.surfaceData);
+        }
+
         OGLContext.validateContext(dstData, dstData,
                                    sg2d.getCompClip(), comp,
                                    null, sg2d.paint, sg2d, ctxflags);
--- a/src/share/classes/sun/java2d/pipe/BufferedContext.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/java2d/pipe/BufferedContext.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,8 @@
 import static sun.java2d.pipe.BufferedRenderPipe.BYTES_PER_SPAN;
 
 import java.lang.annotation.Native;
+import java.lang.ref.Reference;
+import java.lang.ref.WeakReference;
 
 /**
  * Base context class for managing state in a single-threaded rendering
@@ -87,11 +89,11 @@
      */
     protected static BufferedContext currentContext;
 
-    private AccelSurface    validatedSrcData;
-    private AccelSurface    validatedDstData;
-    private Region          validatedClip;
-    private Composite       validatedComp;
-    private Paint           validatedPaint;
+    private Reference<AccelSurface> validSrcDataRef = new WeakReference<>(null);
+    private Reference<AccelSurface> validDstDataRef = new WeakReference<>(null);
+    private Reference<Region> validClipRef = new WeakReference<>(null);
+    private Reference<Composite> validCompRef = new WeakReference<>(null);
+    private Reference<Paint> validPaintRef = new WeakReference<>(null);
     // renamed from isValidatedPaintAColor as part of a work around for 6764257
     private boolean         isValidatedPaintJustAColor;
     private int             validatedRGB;
@@ -127,9 +129,9 @@
                                        int flags)
     {
         // assert rq.lock.isHeldByCurrentThread();
-        BufferedContext d3dc = dstData.getContext();
-        d3dc.validate(srcData, dstData,
-                      clip, comp, xform, paint, sg2d, flags);
+        BufferedContext context = dstData.getContext();
+        context.validate(srcData, dstData,
+                         clip, comp, xform, paint, sg2d, flags);
     }
 
     /**
@@ -200,13 +202,15 @@
                 updatePaint = true;
                 isValidatedPaintJustAColor = true;
             }
-        } else if (validatedPaint != paint) {
+        } else if (validPaintRef.get() != paint) {
             updatePaint = true;
             // this should be set when we are switching from paint to color
             // in which case this condition will be true
             isValidatedPaintJustAColor = false;
         }
 
+        final AccelSurface validatedSrcData = validSrcDataRef.get();
+        final AccelSurface validatedDstData = validDstDataRef.get();
         if ((currentContext != this) ||
             (srcData != validatedSrcData) ||
             (dstData != validatedDstData))
@@ -228,11 +232,12 @@
             setSurfaces(srcData, dstData);
 
             currentContext = this;
-            validatedSrcData = srcData;
-            validatedDstData = dstData;
+            validSrcDataRef = new WeakReference<>(srcData);
+            validDstDataRef = new WeakReference<>(dstData);
         }
 
         // validate clip
+        final Region validatedClip = validClipRef.get();
         if ((clip != validatedClip) || updateClip) {
             if (clip != null) {
                 if (updateClip ||
@@ -248,13 +253,13 @@
             } else {
                 resetClip();
             }
-            validatedClip = clip;
+            validClipRef = new WeakReference<>(clip);
         }
 
         // validate composite (note that a change in the context flags
         // may require us to update the composite state, even if the
         // composite has not changed)
-        if ((comp != validatedComp) || (flags != validatedFlags)) {
+        if ((comp != validCompRef.get()) || (flags != validatedFlags)) {
             if (comp != null) {
                 setComposite(comp, flags);
             } else {
@@ -263,7 +268,7 @@
             // the paint state is dependent on the composite state, so make
             // sure we update the color below
             updatePaint = true;
-            validatedComp = comp;
+            validCompRef = new WeakReference<>(comp);
             validatedFlags = flags;
         }
 
@@ -297,7 +302,7 @@
             } else {
                 BufferedPaints.resetPaint(rq);
             }
-            validatedPaint = paint;
+            validPaintRef = new WeakReference<>(paint);
         }
 
         // mark dstData dirty
@@ -315,9 +320,9 @@
      * @see RenderQueue#lock
      * @see RenderQueue#unlock
      */
-    public void invalidateSurfaces() {
-        validatedSrcData = null;
-        validatedDstData = null;
+    private void invalidateSurfaces() {
+        validSrcDataRef.clear();
+        validDstDataRef.clear();
     }
 
     private void setSurfaces(AccelSurface srcData,
@@ -434,9 +439,9 @@
         resetClip();
         BufferedPaints.resetPaint(rq);
         invalidateSurfaces();
-        validatedComp = null;
-        validatedClip = null;
-        validatedPaint = null;
+        validCompRef.clear();
+        validClipRef.clear();
+        validPaintRef.clear();
         isValidatedPaintJustAColor = false;
         xformInUse = false;
     }
--- a/src/share/classes/sun/reflect/annotation/AnnotationType.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/reflect/annotation/AnnotationType.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -118,16 +118,22 @@
         members = new HashMap<String, Method>(methods.length+1, 1.0f);
 
         for (Method method :  methods) {
-            if (method.getParameterTypes().length != 0)
-                throw new IllegalArgumentException(method + " has params");
-            String name = method.getName();
-            Class<?> type = method.getReturnType();
-            memberTypes.put(name, invocationHandlerReturnType(type));
-            members.put(name, method);
+            if (Modifier.isPublic(method.getModifiers()) &&
+                Modifier.isAbstract(method.getModifiers()) &&
+                !method.isSynthetic()) {
+                if (method.getParameterTypes().length != 0) {
+                    throw new IllegalArgumentException(method + " has params");
+                }
+                String name = method.getName();
+                Class<?> type = method.getReturnType();
+                memberTypes.put(name, invocationHandlerReturnType(type));
+                members.put(name, method);
 
-            Object defaultValue = method.getDefaultValue();
-            if (defaultValue != null)
-                memberDefaults.put(name, defaultValue);
+                Object defaultValue = method.getDefaultValue();
+                if (defaultValue != null) {
+                    memberDefaults.put(name, defaultValue);
+                }
+            }
         }
 
         // Initialize retention, & inherited fields.  Special treatment
--- a/src/share/classes/sun/security/jca/ProviderConfig.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/jca/ProviderConfig.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -255,6 +255,15 @@
                         disableLoad();
                     }
                     return null;
+                } catch (ExceptionInInitializerError err) {
+                    // unexpected exception thrown from static initialization block in provider
+                    // (ex: insufficient permission to initialize provider class)
+                    if (debug != null) {
+                        debug.println("Error loading provider " + ProviderConfig.this);
+                        err.printStackTrace();
+                    }
+                    disableLoad();
+                    return null;
                 }
             }
         });
--- a/src/share/classes/sun/security/krb5/Config.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/krb5/Config.java	Mon Aug 08 15:29:16 2016 -0700
@@ -525,9 +525,9 @@
                 String previous = null;
                 while ((line = br.readLine()) != null) {
                     line = line.trim();
-                    if (line.startsWith("#") || line.isEmpty()) {
+                    if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) {
                         // ignore comments and blank line
-                        // Comments start with #.
+                        // Comments start with '#' or ';'
                         continue;
                     }
                     // In practice, a subsection might look like:
--- a/src/share/classes/sun/security/krb5/KrbKdcRep.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/krb5/KrbKdcRep.java	Mon Aug 08 15:29:16 2016 -0700
@@ -62,7 +62,8 @@
             throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
         }
 
-        for (int i = 1; i < 6; i++) {
+        // We allow KDC to return a non-forwardable ticket if request has -f
+        for (int i = 2; i < 6; i++) {
             if (req.reqBody.kdcOptions.get(i) !=
                    rep.encKDCRepPart.flags.get(i)) {
                 if (Krb5.DEBUG) {
--- a/src/share/classes/sun/security/krb5/KrbTgsReq.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/krb5/KrbTgsReq.java	Mon Aug 08 15:29:16 2016 -0700
@@ -150,19 +150,11 @@
         ctime = KerberosTime.now();
 
         // check if they are valid arguments. The optional fields
-        // should be  consistent with settings in KDCOptions.
-
-        // TODO: Is this necessary? If the TGT is not FORWARDABLE,
-        // you can still request for a FORWARDABLE ticket, just the
-        // KDC will give you a non-FORWARDABLE one. Even if you
-        // cannot use the ticket expected, it still contains info.
-        // This means there will be problem later. We already have
-        // flags check in KrbTgsRep. Of course, sometimes the KDC
-        // will not issue the ticket at all.
+        // should be consistent with settings in KDCOptions.
 
         if (options.get(KDCOptions.FORWARDABLE) &&
                 (!(asCreds.flags.get(Krb5.TKT_OPTS_FORWARDABLE)))) {
-            throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS);
+            options.set(KDCOptions.FORWARDABLE, false);
         }
         if (options.get(KDCOptions.FORWARDED)) {
             if (!(asCreds.flags.get(KDCOptions.FORWARDABLE)))
--- a/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java	Mon Aug 08 15:29:16 2016 -0700
@@ -58,6 +58,9 @@
             // TODO: we do not support kerberos referral now
             throw new KrbException("Cross realm impersonation not supported");
         }
+        if (!ccreds.isForwardable()) {
+            throw new KrbException("S4U2self needs a FORWARDABLE ticket");
+        }
         KrbTgsReq req = new KrbTgsReq(
                 ccreds,
                 ccreds.getClient(),
@@ -68,6 +71,9 @@
         if (!creds.getClient().equals(client)) {
             throw new KrbException("S4U2self request not honored by KDC");
         }
+        if (!creds.isForwardable()) {
+            throw new KrbException("S4U2self ticket must be FORWARDABLE");
+        }
         return creds;
     }
 
--- a/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java	Mon Aug 08 15:29:16 2016 -0700
@@ -228,29 +228,34 @@
         // check native range first
         if ((minKeySize != -1) && (keySize < minKeySize)) {
             throw new InvalidAlgorithmParameterException(algorithm +
-                " key must be at least " + minKeySize + " bits");
+                " key must be at least " + minKeySize + " bits. " +
+                "The specific key size " + keySize + " is not supported");
         }
         if ((maxKeySize != -1) && (keySize > maxKeySize)) {
             throw new InvalidAlgorithmParameterException(algorithm +
-                " key must be at most " + maxKeySize + " bits");
+                " key must be at most " + maxKeySize + " bits. " +
+                "The specific key size " + keySize + " is not supported");
         }
 
         // check our own algorithm-specific limits also
         if (algorithm.equals("EC")) {
             if (keySize < 112) {
-                throw new InvalidAlgorithmParameterException
-                    ("Key size must be at least 112 bit");
+                    throw new InvalidAlgorithmParameterException(
+                    "EC key size must be at least 112 bit. " +
+                    "The specific key size " + keySize + " is not supported");
             }
             if (keySize > 2048) {
                 // sanity check, nobody really wants keys this large
-                throw new InvalidAlgorithmParameterException
-                    ("Key size must be at most 2048 bit");
+                throw new InvalidAlgorithmParameterException(
+                    "EC key size must be at most 2048 bit. " +
+                    "The specific key size " + keySize + " is not supported");
             }
         } else {
             // RSA, DH, DSA
             if (keySize < 512) {
-                throw new InvalidAlgorithmParameterException
-                    ("Key size must be at least 512 bit");
+                throw new InvalidAlgorithmParameterException(algorithm +
+                    " key size must be at least 512 bit. " +
+                    "The specific key size " + keySize + " is not supported");
             }
             if (algorithm.equals("RSA")) {
                 BigInteger tmpExponent = rsaPublicExponent;
@@ -271,8 +276,10 @@
                 if (algorithm.equals("DH") && (params != null)) {
                     // sanity check, nobody really wants keys this large
                     if (keySize > 64 * 1024) {
-                        throw new InvalidAlgorithmParameterException
-                            ("Key size must be at most 65536 bit");
+                        throw new InvalidAlgorithmParameterException(
+                            "DH key size must be at most 65536 bit. " +
+                            "The specific key size " +
+                            keySize + " is not supported");
                     }
                 } else {
                     // this restriction is in the spec for DSA
@@ -282,7 +289,9 @@
                         ((keySize > 1024) || ((keySize & 0x3f) != 0))) {
                         throw new InvalidAlgorithmParameterException(algorithm +
                             " key must be multiples of 64 if less than 1024 bits" +
-                            ", or 2048 bits");
+                            ", or 2048 bits. " +
+                            "The specific key size " +
+                            keySize + " is not supported");
                     }
                 }
             }
--- a/src/share/classes/sun/security/pkcs11/P11KeyStore.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/pkcs11/P11KeyStore.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -752,6 +752,21 @@
             } else {
                 login(new PasswordCallbackHandler(password));
             }
+        } catch(LoginException e) {
+            Throwable cause = e.getCause();
+            if (cause instanceof PKCS11Exception) {
+                PKCS11Exception pe = (PKCS11Exception) cause;
+                if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
+                    // if password is wrong, the cause of the IOException
+                    // should be an UnrecoverableKeyException
+                    throw new IOException("load failed",
+                            new UnrecoverableKeyException().initCause(e));
+                }
+            }
+            throw new IOException("load failed", e);
+        }
+
+        try {
             if (mapLabels() == true) {
                 // CKA_LABELs are shared by multiple certs
                 writeDisabled = true;
@@ -759,7 +774,7 @@
             if (debug != null) {
                 dumpTokenMap();
             }
-        } catch (LoginException | KeyStoreException | PKCS11Exception e) {
+        } catch (KeyStoreException | PKCS11Exception e) {
             throw new IOException("load failed", e);
         }
     }
--- a/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java	Mon Aug 08 15:29:16 2016 -0700
@@ -2051,7 +2051,7 @@
                 }
 
                 if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
-                   throw new SecurityException("Failed PKCS12" +
+                   throw new UnrecoverableKeyException("Failed PKCS12" +
                                         " integrity checking");
                 }
            } catch (Exception e) {
--- a/src/share/classes/sun/security/ssl/CipherBox.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/CipherBox.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1044,40 +1044,6 @@
         return nonce;
     }
 
-    /*
-     * Is this cipher available?
-     *
-     * This method can only be called by CipherSuite.BulkCipher.isAvailable()
-     * to test the availability of a cipher suites.  Please DON'T use it in
-     * other places, otherwise, the behavior may be unexpected because we may
-     * initialize AEAD cipher improperly in the method.
-     */
-    Boolean isAvailable() {
-        // We won't know whether a cipher for a particular key size is
-        // available until the cipher is successfully initialized.
-        //
-        // We do not initialize AEAD cipher in the constructor.  Need to
-        // initialize the cipher to ensure that the AEAD mode for a
-        // particular key size is supported.
-        if (cipherType == AEAD_CIPHER) {
-            try {
-                Authenticator authenticator =
-                    new Authenticator(protocolVersion);
-                byte[] nonce = authenticator.sequenceNumber();
-                byte[] iv = Arrays.copyOf(fixedIv,
-                                            fixedIv.length + nonce.length);
-                System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
-                GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
-
-                cipher.init(mode, key, spec, random);
-            } catch (Exception e) {
-                return Boolean.FALSE;
-            }
-        }   // Otherwise, we have initialized the cipher in the constructor.
-
-        return Boolean.TRUE;
-    }
-
     /**
      * Sanity check the length of a fragment before decryption.
      *
--- a/src/share/classes/sun/security/ssl/CipherSuite.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/CipherSuite.java	Mon Aug 08 15:29:16 2016 -0700
@@ -75,12 +75,6 @@
     // minimum priority for default enabled CipherSuites
     final static int DEFAULT_SUITES_PRIORITY = 300;
 
-    // Flag indicating if CipherSuite availability can change dynamically.
-    // This is the case when we rely on a JCE cipher implementation that
-    // may not be available in the installed JCE providers.
-    // It is true because we might not have an ECC implementation.
-    final static boolean DYNAMIC_AVAILABILITY = true;
-
     private final static boolean ALLOW_ECC = Debug.getBooleanProperty
         ("com.sun.net.ssl.enableECC", true);
 
@@ -186,9 +180,6 @@
      * Return whether this CipherSuite is available for use. A
      * CipherSuite may be unavailable even if it is supported
      * (i.e. allowed == true) if the required JCE cipher is not installed.
-     * In some configuration, this situation may change over time, call
-     * CipherSuiteList.clearAvailableCache() before this method to obtain
-     * the most current status.
      */
     boolean isAvailable() {
         return allowed && keyExchange.isAvailable() && cipher.isAvailable();
@@ -404,10 +395,6 @@
      */
     final static class BulkCipher {
 
-        // Map BulkCipher -> Boolean(available)
-        private final static Map<BulkCipher,Boolean> availableCache =
-                                            new HashMap<>(8);
-
         // descriptive name including key size, e.g. AES/128
         final String description;
 
@@ -451,6 +438,9 @@
         // The secure random used to detect the cipher availability.
         private final static SecureRandom secureRandom;
 
+        // runtime availability
+        private final boolean isAvailable;
+
         static {
             try {
                 secureRandom = JsseJce.getSecureRandom();
@@ -475,6 +465,17 @@
 
             this.expandedKeySize = expandedKeySize;
             this.exportable = true;
+
+            // availability of this bulk cipher
+            //
+            // Currently all supported ciphers except AES are always available
+            // via the JSSE internal implementations. We also assume AES/128 of
+            // CBC mode is always available since it is shipped with the SunJCE
+            // provider.  However, AES/256 is unavailable when the default JCE
+            // policy jurisdiction files are installed because of key length
+            // restrictions.
+            this.isAvailable =
+                    allowed ? isUnlimited(keySize, transformation) : false;
         }
 
         BulkCipher(String transformation, CipherType cipherType, int keySize,
@@ -491,6 +492,17 @@
 
             this.expandedKeySize = keySize;
             this.exportable = false;
+
+            // availability of this bulk cipher
+            //
+            // Currently all supported ciphers except AES are always available
+            // via the JSSE internal implementations. We also assume AES/128 of
+            // CBC mode is always available since it is shipped with the SunJCE
+            // provider.  However, AES/256 is unavailable when the default JCE
+            // policy jurisdiction files are installed because of key length
+            // restrictions.
+            this.isAvailable =
+                    allowed ? isUnlimited(keySize, transformation) : false;
         }
 
         /**
@@ -508,86 +520,29 @@
 
         /**
          * Test if this bulk cipher is available. For use by CipherSuite.
-         *
-         * Currently all supported ciphers except AES are always available
-         * via the JSSE internal implementations. We also assume AES/128 of
-         * CBC mode is always available since it is shipped with the SunJCE
-         * provider.  However, AES/256 is unavailable when the default JCE
-         * policy jurisdiction files are installed because of key length
-         * restrictions, and AEAD is unavailable when the underlying providers
-         * do not support AEAD/GCM mode.
          */
         boolean isAvailable() {
-            if (allowed == false) {
-                return false;
+            return this.isAvailable;
+        }
+
+        private static boolean isUnlimited(int keySize, String transformation) {
+            int keySizeInBits = keySize * 8;
+            if (keySizeInBits > 128) {    // need the JCE unlimited
+                                          // strength jurisdiction policy
+                try {
+                    if (Cipher.getMaxAllowedKeyLength(
+                            transformation) < keySizeInBits) {
+
+                        return false;
+                    }
+                } catch (Exception e) {
+                    return false;
+                }
             }
 
-            if ((this == B_AES_256) ||
-                    (this.cipherType == CipherType.AEAD_CIPHER)) {
-                return isAvailable(this);
-            }
-
-            // always available
             return true;
         }
 
-        // for use by CipherSuiteList.clearAvailableCache();
-        static synchronized void clearAvailableCache() {
-            if (DYNAMIC_AVAILABILITY) {
-                availableCache.clear();
-            }
-        }
-
-        private static synchronized boolean isAvailable(BulkCipher cipher) {
-            Boolean b = availableCache.get(cipher);
-            if (b == null) {
-                int keySizeInBits = cipher.keySize * 8;
-                if (keySizeInBits > 128) {    // need the JCE unlimited
-                                               // strength jurisdiction policy
-                    try {
-                        if (Cipher.getMaxAllowedKeyLength(
-                                cipher.transformation) < keySizeInBits) {
-                            b = Boolean.FALSE;
-                        }
-                    } catch (Exception e) {
-                        b = Boolean.FALSE;
-                    }
-                }
-
-                if (b == null) {
-                    b = Boolean.FALSE;          // may be reset to TRUE if
-                                                // the cipher is available
-                    CipherBox temporary = null;
-                    try {
-                        SecretKey key = new SecretKeySpec(
-                                            new byte[cipher.expandedKeySize],
-                                            cipher.algorithm);
-                        IvParameterSpec iv;
-                        if (cipher.cipherType == CipherType.AEAD_CIPHER) {
-                            iv = new IvParameterSpec(
-                                            new byte[cipher.fixedIvSize]);
-                        } else {
-                            iv = new IvParameterSpec(new byte[cipher.ivSize]);
-                        }
-                        temporary = cipher.newCipher(
-                                            ProtocolVersion.DEFAULT,
-                                            key, iv, secureRandom, true);
-                        b = temporary.isAvailable();
-                    } catch (NoSuchAlgorithmException e) {
-                        // not available
-                    } finally {
-                        if (temporary != null) {
-                            temporary.dispose();
-                        }
-                    }
-                }
-
-                availableCache.put(cipher, b);
-            }
-
-            return b.booleanValue();
-        }
-
         @Override
         public String toString() {
             return description;
--- a/src/share/classes/sun/security/ssl/CipherSuiteList.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/CipherSuiteList.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2015, 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
@@ -74,24 +74,12 @@
             throw new IllegalArgumentException("CipherSuites may not be null");
         }
         cipherSuites = new ArrayList<CipherSuite>(names.length);
-        // refresh available cache once if a CipherSuite is not available
-        // (maybe new JCE providers have been installed)
-        boolean refreshed = false;
         for (int i = 0; i < names.length; i++) {
             String suiteName = names[i];
             CipherSuite suite = CipherSuite.valueOf(suiteName);
             if (suite.isAvailable() == false) {
-                if (refreshed == false) {
-                    // clear the cache so that the isAvailable() call below
-                    // does a full check
-                    clearAvailableCache();
-                    refreshed = true;
-                }
-                // still missing?
-                if (suite.isAvailable() == false) {
-                    throw new IllegalArgumentException("Cannot support "
-                        + suiteName + " with currently installed providers");
-                }
+                throw new IllegalArgumentException("Cannot support "
+                    + suiteName + " with currently installed providers");
             }
             cipherSuites.add(suite);
         }
@@ -195,16 +183,4 @@
         }
         s.putBytes16(suiteBytes);
     }
-
-    /**
-     * Clear cache of available ciphersuites. If we support all ciphers
-     * internally, there is no need to clear the cache and calling this
-     * method has no effect.
-     */
-    static synchronized void clearAvailableCache() {
-        if (CipherSuite.DYNAMIC_AVAILABILITY) {
-            CipherSuite.BulkCipher.clearAvailableCache();
-            JsseJce.clearEcAvailable();
-        }
-    }
 }
--- a/src/share/classes/sun/security/ssl/JsseJce.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/JsseJce.java	Mon Aug 08 15:29:16 2016 -0700
@@ -55,11 +55,6 @@
 
     private final static ProviderList fipsProviderList;
 
-    // Flag indicating whether EC crypto is available.
-    // If null, then we have not checked yet.
-    // If yes, then all the EC based crypto we need is available.
-    private static Boolean ecAvailable;
-
     // Flag indicating whether Kerberos crypto is available.
     // If true, then all the Kerberos-based crypto we need is available.
     private final static boolean kerberosAvailable;
@@ -195,24 +190,8 @@
         // no instantiation of this class
     }
 
-    synchronized static boolean isEcAvailable() {
-        if (ecAvailable == null) {
-            try {
-                JsseJce.getSignature(SIGNATURE_ECDSA);
-                JsseJce.getSignature(SIGNATURE_RAWECDSA);
-                JsseJce.getKeyAgreement("ECDH");
-                JsseJce.getKeyFactory("EC");
-                JsseJce.getKeyPairGenerator("EC");
-                ecAvailable = true;
-            } catch (Exception e) {
-                ecAvailable = false;
-            }
-        }
-        return ecAvailable;
-    }
-
-    synchronized static void clearEcAvailable() {
-        ecAvailable = null;
+    static boolean isEcAvailable() {
+        return EcAvailability.isAvailable;
     }
 
     static boolean isKerberosAvailable() {
@@ -414,4 +393,27 @@
         }
     }
 
+
+    // lazy initialization holder class idiom for static default parameters
+    //
+    // See Effective Java Second Edition: Item 71.
+    private static class EcAvailability {
+        // Is EC crypto available?
+        private final static boolean isAvailable;
+
+        static {
+            boolean mediator = true;
+            try {
+                JsseJce.getSignature(SIGNATURE_ECDSA);
+                JsseJce.getSignature(SIGNATURE_RAWECDSA);
+                JsseJce.getKeyAgreement("ECDH");
+                JsseJce.getKeyFactory("EC");
+                JsseJce.getKeyPairGenerator("EC");
+            } catch (Exception e) {
+                mediator = false;
+            }
+
+            isAvailable = mediator;
+        }
+    }
 }
--- a/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java	Mon Aug 08 15:29:16 2016 -0700
@@ -90,6 +90,30 @@
     }
 
     /*
+     * Retrieving the cipher's provider name for the debug purposes
+     * can throw an exception by itself.
+     */
+    private static String safeProviderName(Cipher cipher) {
+        try {
+            return cipher.getProvider().toString();
+        } catch (Exception e) {
+            if (debug != null && Debug.isOn("handshake")) {
+                System.out.println("Retrieving The Cipher provider name" +
+                        " caused exception " + e.getMessage());
+            }
+        }
+        try {
+            return cipher.toString() + " (provider name not available)";
+        } catch (Exception e) {
+            if (debug != null && Debug.isOn("handshake")) {
+                System.out.println("Retrieving The Cipher name" +
+                        " caused exception " + e.getMessage());
+            }
+        }
+        return "(cipher/provider names not available)";
+    }
+
+    /*
      * Server gets the PKCS #1 (block format 02) data, decrypts
      * it with its private key.
      */
@@ -130,15 +154,19 @@
                         cipher.getProvider().getName());
             } catch (InvalidKeyException | UnsupportedOperationException iue) {
                 if (debug != null && Debug.isOn("handshake")) {
-                    System.out.println("The Cipher provider " +
-                        cipher.getProvider().getName() +
-                        " caused exception: " + iue.getMessage());
+                    System.out.println("The Cipher provider "
+                            + safeProviderName(cipher)
+                            + " caused exception: " + iue.getMessage());
                 }
 
                 needFailover = true;
             }
 
             if (needFailover) {
+                // The cipher might be spoiled by unsuccessful call to init(),
+                // so request a fresh instance
+                cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
+
                 // Use DECRYPT_MODE and dispose the previous initialization.
                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
                 boolean failed = false;
--- a/src/share/classes/sun/security/ssl/SSLContextImpl.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/SSLContextImpl.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2015, 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
@@ -52,16 +52,6 @@
     private X509TrustManager trustManager;
     private SecureRandom secureRandom;
 
-    // supported and default protocols
-    private ProtocolList defaultServerProtocolList;
-    private ProtocolList defaultClientProtocolList;
-    private ProtocolList supportedProtocolList;
-
-    // supported and default cipher suites
-    private CipherSuiteList defaultServerCipherSuiteList;
-    private CipherSuiteList defaultClientCipherSuiteList;
-    private CipherSuiteList supportedCipherSuiteList;
-
     SSLContextImpl() {
         ephemeralKeyManager = new EphemeralKeyManager();
         clientCache = new SSLSessionContextImpl();
@@ -191,6 +181,8 @@
         }
         return new SSLServerSocketFactoryImpl(this);
     }
+    abstract SSLEngine createSSLEngineImpl();
+    abstract SSLEngine createSSLEngineImpl(String host, int port);
 
     @Override
     protected SSLEngine engineCreateSSLEngine() {
@@ -198,7 +190,7 @@
             throw new IllegalStateException(
                 "SSLContextImpl is not initialized");
         }
-        return new SSLEngineImpl(this);
+        return createSSLEngineImpl();
     }
 
     @Override
@@ -207,7 +199,7 @@
             throw new IllegalStateException(
                 "SSLContextImpl is not initialized");
         }
-        return new SSLEngineImpl(this, host, port);
+        return createSSLEngineImpl(host, port);
     }
 
     @Override
@@ -236,78 +228,35 @@
         return ephemeralKeyManager;
     }
 
-    abstract SSLParameters getDefaultServerSSLParams();
-    abstract SSLParameters getDefaultClientSSLParams();
-    abstract SSLParameters getSupportedSSLParams();
 
     // Get supported ProtocolList.
-    ProtocolList getSuportedProtocolList() {
-        if (supportedProtocolList == null) {
-            supportedProtocolList =
-                new ProtocolList(getSupportedSSLParams().getProtocols());
-        }
+    abstract ProtocolList getSuportedProtocolList();
 
-        return supportedProtocolList;
-    }
+    // Get default ProtocolList for server mode.
+    abstract ProtocolList getServerDefaultProtocolList();
+
+    // Get default ProtocolList for client mode.
+    abstract ProtocolList getClientDefaultProtocolList();
+
+    // Get supported CipherSuiteList.
+    abstract CipherSuiteList getSupportedCipherSuiteList();
+
+    // Get default CipherSuiteList for server mode.
+    abstract CipherSuiteList getServerDefaultCipherSuiteList();
+
+    // Get default CipherSuiteList for client mode.
+    abstract CipherSuiteList getClientDefaultCipherSuiteList();
 
     // Get default ProtocolList.
     ProtocolList getDefaultProtocolList(boolean roleIsServer) {
-        if (roleIsServer) {
-            if (defaultServerProtocolList == null) {
-                defaultServerProtocolList = new ProtocolList(
-                        getDefaultServerSSLParams().getProtocols());
-            }
-
-            return defaultServerProtocolList;
-        } else {
-            if (defaultClientProtocolList == null) {
-                defaultClientProtocolList = new ProtocolList(
-                        getDefaultClientSSLParams().getProtocols());
-            }
-
-            return defaultClientProtocolList;
-        }
-    }
-
-    // Get supported CipherSuiteList.
-    CipherSuiteList getSupportedCipherSuiteList() {
-        // The maintenance of cipher suites needs to be synchronized.
-        synchronized (this) {
-            // Clear cache of available ciphersuites.
-            clearAvailableCache();
-
-            if (supportedCipherSuiteList == null) {
-                supportedCipherSuiteList = getApplicableCipherSuiteList(
-                        getSuportedProtocolList(), false);
-            }
-
-            return supportedCipherSuiteList;
-        }
+        return roleIsServer ? getServerDefaultProtocolList()
+                : getClientDefaultProtocolList();
     }
 
     // Get default CipherSuiteList.
     CipherSuiteList getDefaultCipherSuiteList(boolean roleIsServer) {
-        // The maintenance of cipher suites needs to be synchronized.
-        synchronized (this) {
-            // Clear cache of available ciphersuites.
-            clearAvailableCache();
-
-            if (roleIsServer) {
-                if (defaultServerCipherSuiteList == null) {
-                    defaultServerCipherSuiteList = getApplicableCipherSuiteList(
-                        getDefaultProtocolList(true), true);
-                }
-
-                return defaultServerCipherSuiteList;
-            } else {
-                if (defaultClientCipherSuiteList == null) {
-                    defaultClientCipherSuiteList = getApplicableCipherSuiteList(
-                        getDefaultProtocolList(false), true);
-                }
-
-                return defaultClientCipherSuiteList;
-            }
-        }
+        return roleIsServer ? getServerDefaultCipherSuiteList()
+                : getClientDefaultCipherSuiteList();
     }
 
     /**
@@ -315,16 +264,24 @@
      * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
      */
     boolean isDefaultProtocolList(ProtocolList protocols) {
-        return (protocols == defaultServerProtocolList) ||
-               (protocols == defaultClientProtocolList);
+        return (protocols == getServerDefaultProtocolList()) ||
+                (protocols == getClientDefaultProtocolList());
     }
 
+    /**
+     * Return whether a protocol list is the original default enabled
+     * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
+     */
+    boolean isDefaultCipherSuiteList(CipherSuiteList cipherSuites) {
+        return (cipherSuites == getServerDefaultCipherSuiteList()) ||
+                (cipherSuites == getClientDefaultCipherSuiteList());
+    }
 
     /*
      * Return the list of all available CipherSuites with a priority of
      * minPriority or above.
      */
-    private CipherSuiteList getApplicableCipherSuiteList(
+    private static CipherSuiteList getApplicableCipherSuiteList(
             ProtocolList protocols, boolean onlyEnabled) {
 
         int minPriority = CipherSuite.SUPPORTED_SUITES_PRIORITY;
@@ -370,22 +327,20 @@
         return new CipherSuiteList(suites);
     }
 
-    /**
-     * Clear cache of available ciphersuites. If we support all ciphers
-     * internally, there is no need to clear the cache and calling this
-     * method has no effect.
-     *
-     * Note that every call to clearAvailableCache() and the maintenance of
-     * cipher suites need to be synchronized with this instance.
-     */
-    private void clearAvailableCache() {
-        if (CipherSuite.DYNAMIC_AVAILABILITY) {
-            supportedCipherSuiteList = null;
-            defaultServerCipherSuiteList = null;
-            defaultClientCipherSuiteList = null;
-            CipherSuite.BulkCipher.clearAvailableCache();
-            JsseJce.clearEcAvailable();
+    private static String[] getAvailableProtocols(
+            ProtocolVersion[] protocolCandidates) {
+
+        List<String> availableProtocols = Collections.<String>emptyList();
+        if (protocolCandidates !=  null && protocolCandidates.length != 0) {
+            availableProtocols = new ArrayList<>(protocolCandidates.length);
+            for (ProtocolVersion p : protocolCandidates) {
+                if (ProtocolVersion.availableProtocols.contains(p)) {
+                    availableProtocols.add(p.name);
+                }
+            }
         }
+
+        return availableProtocols.toArray(new String[0]);
     }
 
     /*
@@ -418,39 +373,37 @@
      */
 
     /*
-     * The base abstract SSLContext implementation.
+     * The base abstract SSLContext implementation for the Transport Layer
+     * Security (TLS) protocols.
      *
      * This abstract class encapsulates supported and the default server
-     * SSL parameters.
+     * SSL/TLS parameters.
      *
      * @see SSLContext
      */
-    private abstract static class AbstractSSLContext extends SSLContextImpl {
-        // parameters
-        private static final SSLParameters defaultServerSSLParams;
-        private static final SSLParameters supportedSSLParams;
+    private abstract static class AbstractTLSContext extends SSLContextImpl {
+        private static final ProtocolList supportedProtocolList;
+        private static final ProtocolList serverDefaultProtocolList;
+
+        private static final CipherSuiteList supportedCipherSuiteList;
+        private static final CipherSuiteList serverDefaultCipherSuiteList;
 
         static {
-            // supported SSL parameters
-            supportedSSLParams = new SSLParameters();
-
-            // candidates for available protocols
-            ProtocolVersion[] candidates;
-
             if (SunJSSE.isFIPS()) {
-                supportedSSLParams.setProtocols(new String[] {
+                supportedProtocolList = new ProtocolList(new String[] {
                     ProtocolVersion.TLS10.name,
                     ProtocolVersion.TLS11.name,
                     ProtocolVersion.TLS12.name
                 });
 
-                candidates = new ProtocolVersion[] {
+                serverDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                };
+                }));
             } else {
-                supportedSSLParams.setProtocols(new String[] {
+                supportedProtocolList = new ProtocolList(new String[] {
                     ProtocolVersion.SSL20Hello.name,
                     ProtocolVersion.SSL30.name,
                     ProtocolVersion.TLS10.name,
@@ -458,44 +411,50 @@
                     ProtocolVersion.TLS12.name
                 });
 
-                candidates = new ProtocolVersion[] {
+                serverDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.SSL20Hello,
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                };
+                }));
             }
 
-            defaultServerSSLParams = new SSLParameters();
-            defaultServerSSLParams.setProtocols(
-                getAvailableProtocols(candidates).toArray(new String[0]));
+            supportedCipherSuiteList = getApplicableCipherSuiteList(
+                    supportedProtocolList, false);          // all supported
+            serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
+                    serverDefaultProtocolList, true);       // enabled only
         }
 
         @Override
-        SSLParameters getDefaultServerSSLParams() {
-            return defaultServerSSLParams;
+        ProtocolList getSuportedProtocolList() {
+            return supportedProtocolList;
         }
 
         @Override
-        SSLParameters getSupportedSSLParams() {
-            return supportedSSLParams;
+        CipherSuiteList getSupportedCipherSuiteList() {
+            return supportedCipherSuiteList;
         }
 
-        static List<String> getAvailableProtocols(
-                ProtocolVersion[] protocolCandidates) {
+        @Override
+        ProtocolList getServerDefaultProtocolList() {
+            return serverDefaultProtocolList;
+        }
 
-            List<String> availableProtocols = Collections.<String>emptyList();
-            if (protocolCandidates !=  null && protocolCandidates.length != 0) {
-                availableProtocols = new ArrayList<>(protocolCandidates.length);
-                for (ProtocolVersion p : protocolCandidates) {
-                    if (ProtocolVersion.availableProtocols.contains(p)) {
-                        availableProtocols.add(p.name);
-                    }
-                }
-            }
+        @Override
+        CipherSuiteList getServerDefaultCipherSuiteList() {
+            return serverDefaultCipherSuiteList;
+        }
 
-            return availableProtocols;
+        @Override
+        SSLEngine createSSLEngineImpl() {
+            return new SSLEngineImpl(this);
+        }
+
+        @Override
+        SSLEngine createSSLEngineImpl(String host, int port) {
+            return new SSLEngineImpl(this, host, port);
         }
     }
 
@@ -504,31 +463,36 @@
      *
      * @see SSLContext
      */
-    public static final class TLS10Context extends AbstractSSLContext {
-        private static final SSLParameters defaultClientSSLParams;
+    public static final class TLS10Context extends AbstractTLSContext {
+        private static final ProtocolList clientDefaultProtocolList;
+        private static final CipherSuiteList clientDefaultCipherSuiteList;
 
         static {
-            // candidates for available protocols
-            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.TLS10
-                };
+                }));
             } else {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10
-                };
+                }));
             }
 
-            defaultClientSSLParams = new SSLParameters();
-            defaultClientSSLParams.setProtocols(
-                getAvailableProtocols(candidates).toArray(new String[0]));
+            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
+                    clientDefaultProtocolList, true);       // enabled only
         }
 
         @Override
-        SSLParameters getDefaultClientSSLParams() {
-            return defaultClientSSLParams;
+        ProtocolList getClientDefaultProtocolList() {
+            return clientDefaultProtocolList;
+        }
+
+        @Override
+        CipherSuiteList getClientDefaultCipherSuiteList() {
+            return clientDefaultCipherSuiteList;
         }
     }
 
@@ -537,33 +501,38 @@
      *
      * @see SSLContext
      */
-    public static final class TLS11Context extends AbstractSSLContext {
-        private static final SSLParameters defaultClientSSLParams;
+    public static final class TLS11Context extends AbstractTLSContext {
+        private static final ProtocolList clientDefaultProtocolList;
+        private static final CipherSuiteList clientDefaultCipherSuiteList;
 
         static {
-            // candidates for available protocols
-            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11
-                };
+                }));
             } else {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11
-                };
+                }));
             }
 
-            defaultClientSSLParams = new SSLParameters();
-            defaultClientSSLParams.setProtocols(
-                getAvailableProtocols(candidates).toArray(new String[0]));
+            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
+                    clientDefaultProtocolList, true);       // enabled only
         }
 
         @Override
-        SSLParameters getDefaultClientSSLParams() {
-            return defaultClientSSLParams;
+        ProtocolList getClientDefaultProtocolList() {
+            return clientDefaultProtocolList;
+        }
+
+        @Override
+        CipherSuiteList getClientDefaultCipherSuiteList() {
+            return clientDefaultCipherSuiteList;
         }
     }
 
@@ -572,35 +541,101 @@
      *
      * @see SSLContext
      */
-    public static final class TLS12Context extends AbstractSSLContext {
-        private static final SSLParameters defaultClientSSLParams;
+    public static final class TLS12Context extends AbstractTLSContext {
+        private static final ProtocolList clientDefaultProtocolList;
+        private static final CipherSuiteList clientDefaultCipherSuiteList;
 
         static {
-            // candidates for available protocols
-            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                };
+                }));
             } else {
-                candidates = new ProtocolVersion[] {
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                };
+                }));
             }
 
-            defaultClientSSLParams = new SSLParameters();
-            defaultClientSSLParams.setProtocols(
-                getAvailableProtocols(candidates).toArray(new String[0]));
+            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
+                    clientDefaultProtocolList, true);       // enabled only
         }
 
         @Override
-        SSLParameters getDefaultClientSSLParams() {
-            return defaultClientSSLParams;
+        ProtocolList getClientDefaultProtocolList() {
+            return clientDefaultProtocolList;
+        }
+
+        @Override
+        CipherSuiteList getClientDefaultCipherSuiteList() {
+            return clientDefaultCipherSuiteList;
+        }
+    }
+
+    /*
+     * The interface for the customized SSL/(D)TLS SSLContext.
+     *
+     * @see SSLContext
+     */
+    private static class CustomizedSSLProtocols {
+        private static final String PROPERTY_NAME = "jdk.tls.client.protocols";
+        static IllegalArgumentException reservedException = null;
+        static ArrayList<ProtocolVersion>
+                customizedProtocols = new ArrayList<>();
+
+        // Don't want a java.lang.LinkageError for illegal system property.
+        //
+        // Please don't throw exception in this static block.  Otherwise,
+        // java.lang.LinkageError may be thrown during the instantiation of
+        // the provider service. Instead, please handle the initialization
+        // exception in the caller's constructor.
+        static {
+            String property = AccessController.doPrivileged(
+                    new GetPropertyAction(PROPERTY_NAME));
+            if (property != null && property.length() != 0) {
+                // remove double quote marks from beginning/end of the property
+                if (property.length() > 1 && property.charAt(0) == '"' &&
+                        property.charAt(property.length() - 1) == '"') {
+                    property = property.substring(1, property.length() - 1);
+                }
+            }
+
+            if (property != null && property.length() != 0) {
+                String[] protocols = property.split(",");
+                for (int i = 0; i < protocols.length; i++) {
+                    protocols[i] = protocols[i].trim();
+                    // Is it a supported protocol name?
+                    try {
+                        ProtocolVersion pro =
+                                ProtocolVersion.valueOf(protocols[i]);
+
+                        if (SunJSSE.isFIPS() &&
+                                ((pro.v == ProtocolVersion.SSL30.v) ||
+                                        (pro.v == ProtocolVersion.SSL20Hello.v))) {
+                            reservedException = new IllegalArgumentException(
+                                    PROPERTY_NAME + ": " + pro +
+                                            " is not FIPS compliant");
+
+                            break;
+                        }
+
+                        // ignore duplicated protocols
+                        if (!customizedProtocols.contains(pro)) {
+                            customizedProtocols.add(pro);
+                        }
+                    } catch (IllegalArgumentException iae) {
+                        reservedException = new IllegalArgumentException(
+                                PROPERTY_NAME + ": " + protocols[i] +
+                                        " is not a standard SSL protocol name", iae);
+                    }
+                }
+            }
         }
     }
 
@@ -609,9 +644,11 @@
      *
      * @see SSLContext
      */
-    private static class CustomizedSSLContext extends AbstractSSLContext {
-        private static final String PROPERTY_NAME = "jdk.tls.client.protocols";
-        private static final SSLParameters defaultClientSSLParams;
+    private static class CustomizedTLSContext extends AbstractTLSContext {
+
+        private static final ProtocolList clientDefaultProtocolList;
+        private static final CipherSuiteList clientDefaultCipherSuiteList;
+
         private static IllegalArgumentException reservedException = null;
 
         // Don't want a java.lang.LinkageError for illegal system property.
@@ -621,86 +658,65 @@
         // the provider service. Instead, let's handle the initialization
         // exception in constructor.
         static {
-            // candidates for available protocols
-            ProtocolVersion[] candidates;
-
-            String property = AccessController.doPrivileged(
-                    new GetPropertyAction(PROPERTY_NAME));
-            if (property == null || property.length() == 0) {
-                // the default enabled client TLS protocols
-                if (SunJSSE.isFIPS()) {
-                    candidates = new ProtocolVersion[] {
-                        ProtocolVersion.TLS10,
-                        ProtocolVersion.TLS11,
-                        ProtocolVersion.TLS12
-                    };
-                } else {
-                    candidates = new ProtocolVersion[] {
-                        ProtocolVersion.SSL30,
-                        ProtocolVersion.TLS10,
-                        ProtocolVersion.TLS11,
-                        ProtocolVersion.TLS12
-                    };
-                }
-            } else {
-                // remove double quote marks from beginning/end of the property
-                if (property.length() > 1 && property.charAt(0) == '"' &&
-                        property.charAt(property.length() - 1) == '"') {
-                    property = property.substring(1, property.length() - 1);
+            reservedException = CustomizedSSLProtocols.reservedException;
+            if (reservedException == null) {
+                ArrayList<ProtocolVersion>
+                        customizedTLSProtocols = new ArrayList<>();
+                for (ProtocolVersion protocol :
+                        CustomizedSSLProtocols.customizedProtocols) {
+                        customizedTLSProtocols.add(protocol);
                 }
 
-                String[] protocols = null;
-                if (property != null && property.length() != 0) {
-                    protocols = property.split(",");
+                // candidates for available protocols
+                ProtocolVersion[] candidates;
+                if (customizedTLSProtocols.isEmpty()) {
+                    // Use the default enabled client protocols if no
+                    // customized TLS protocols.
+                    if (SunJSSE.isFIPS()) {
+                        candidates = new ProtocolVersion[] {
+                                ProtocolVersion.TLS10,
+                                ProtocolVersion.TLS11,
+                                ProtocolVersion.TLS12
+                        };
+                    } else {
+                        candidates = new ProtocolVersion[] {
+                                ProtocolVersion.SSL30,
+                                ProtocolVersion.TLS10,
+                                ProtocolVersion.TLS11,
+                                ProtocolVersion.TLS12
+                        };
+                    }
                 } else {
-                    reservedException = new IllegalArgumentException(
-                        "No protocol specified in " +
-                        PROPERTY_NAME + " system property");
-                    protocols = new String[0];
+                    // Use the customized TLS protocols.
+                    candidates =
+                            new ProtocolVersion[customizedTLSProtocols.size()];
+                    candidates = customizedTLSProtocols.toArray(candidates);
                 }
 
-                candidates = new ProtocolVersion[protocols.length];
-                for (int i = 0; i < protocols.length; i++) {
-                    protocols[i] = protocols[i].trim();
-                    // Is it a supported protocol name?
-                    try {
-                        candidates[i] = ProtocolVersion.valueOf(protocols[i]);
-                    } catch (IllegalArgumentException iae) {
-                        reservedException = new IllegalArgumentException(
-                            PROPERTY_NAME + ": " + protocols[i] +
-                            " is not a standard SSL/TLS protocol name", iae);
-                        break;
-                    }
-                }
-
-                if ((reservedException == null) && SunJSSE.isFIPS()) {
-                    for (ProtocolVersion protocolVersion : candidates) {
-                        if (ProtocolVersion.SSL20Hello.v == protocolVersion.v ||
-                                ProtocolVersion.SSL30.v == protocolVersion.v) {
-                            reservedException = new IllegalArgumentException(
-                                    PROPERTY_NAME + ": " + protocolVersion +
-                                    " is not FIPS compliant");
-                        }
-                    }
-                }
-            }
-
-            defaultClientSSLParams = new SSLParameters();
-            if (reservedException == null) {
-                defaultClientSSLParams.setProtocols(
-                    getAvailableProtocols(candidates).toArray(new String[0]));
+                clientDefaultProtocolList = new ProtocolList(
+                        getAvailableProtocols(candidates));
+                clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
+                        clientDefaultProtocolList, true);   // enabled only
+            } else {
+                clientDefaultProtocolList = null;       // unlikely to be used
+                clientDefaultCipherSuiteList = null;    // unlikely to be used
             }
         }
 
-        protected CustomizedSSLContext() {
+        protected CustomizedTLSContext() {
             if (reservedException != null) {
                 throw reservedException;
             }
         }
 
         @Override
-        SSLParameters getDefaultClientSSLParams() {
-            return defaultClientSSLParams;
+        ProtocolList getClientDefaultProtocolList() {
+            return clientDefaultProtocolList;
+        }
+
+        @Override
+        CipherSuiteList getClientDefaultCipherSuiteList() {
+            return clientDefaultCipherSuiteList;
         }
     }
 
@@ -709,75 +725,57 @@
      *
      * @see SSLContext
      */
-    public static final class TLSContext extends CustomizedSSLContext {
+    public static final class TLSContext extends CustomizedTLSContext {
         // use the default constructor and methods
     }
 
-    /*
-     * The SSLContext implementation for default "Default" algorithm
-     *
-     * @see SSLContext
-     */
-    public static final class DefaultSSLContext extends CustomizedSSLContext {
+    // lazy initialization holder class idiom for static default parameters
+    //
+    // See Effective Java Second Edition: Item 71.
+    private static final class DefaultManagersHolder {
         private static final String NONE = "NONE";
         private static final String P11KEYSTORE = "PKCS11";
 
-        private static volatile SSLContextImpl defaultImpl;
+        private static final TrustManager[] trustManagers;
+        private static final KeyManager[] keyManagers;
 
-        private static TrustManager[] defaultTrustManagers;
-        private static KeyManager[] defaultKeyManagers;
+        static Exception reservedException = null;
 
-        public DefaultSSLContext() throws Exception {
+        static {
+            TrustManager[] tmMediator;
             try {
-                super.engineInit(getDefaultKeyManager(),
-                        getDefaultTrustManager(), null);
+                tmMediator = getTrustManagers();
             } catch (Exception e) {
-                if (debug != null && Debug.isOn("defaultctx")) {
-                    System.out.println("default context init failed: " + e);
+                reservedException = e;
+                tmMediator = new TrustManager[0];
+            }
+            trustManagers = tmMediator;
+
+            if (reservedException == null) {
+                KeyManager[] kmMediator;
+                try {
+                    kmMediator = getKeyManagers();
+                } catch (Exception e) {
+                    reservedException = e;
+                    kmMediator = new KeyManager[0];
                 }
-                throw e;
-            }
-
-            if (defaultImpl == null) {
-                defaultImpl = this;
+                keyManagers = kmMediator;
+            } else {
+                keyManagers = new KeyManager[0];
             }
         }
 
-        @Override
-        protected void engineInit(KeyManager[] km, TrustManager[] tm,
-            SecureRandom sr) throws KeyManagementException {
-            throw new KeyManagementException
-                ("Default SSLContext is initialized automatically");
-        }
-
-        static synchronized SSLContextImpl getDefaultImpl() throws Exception {
-            if (defaultImpl == null) {
-                new DefaultSSLContext();
-            }
-            return defaultImpl;
-        }
-
-        private static synchronized TrustManager[] getDefaultTrustManager()
-                throws Exception {
-            if (defaultTrustManagers != null) {
-                return defaultTrustManagers;
-            }
-
+        private static TrustManager[] getTrustManagers() throws Exception {
             KeyStore ks =
                 TrustManagerFactoryImpl.getCacertsKeyStore("defaultctx");
 
             TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                 TrustManagerFactory.getDefaultAlgorithm());
             tmf.init(ks);
-            defaultTrustManagers = tmf.getTrustManagers();
-            return defaultTrustManagers;
+            return tmf.getTrustManagers();
         }
 
-        private static synchronized KeyManager[] getDefaultKeyManager()
-                throws Exception {
-            if (defaultKeyManagers != null) {
-                return defaultKeyManagers;
-            }
+        private static KeyManager[] getKeyManagers() throws Exception {
 
             final Map<String,String> props = new HashMap<>();
             AccessController.doPrivileged(
@@ -874,11 +872,75 @@
                 kmf.init(ks, passwd);
             }
 
-            defaultKeyManagers = kmf.getKeyManagers();
-            return defaultKeyManagers;
+            return kmf.getKeyManagers();
         }
     }
 
+    // lazy initialization holder class idiom for static default parameters
+    //
+    // See Effective Java Second Edition: Item 71.
+    private static final class DefaultSSLContextHolder {
+
+        private static final SSLContextImpl sslContext;
+        static Exception reservedException = null;
+
+        static {
+            SSLContextImpl mediator = null;
+            if (DefaultManagersHolder.reservedException != null) {
+                reservedException = DefaultManagersHolder.reservedException;
+            } else {
+                try {
+                    mediator = new DefaultSSLContext();
+                } catch (Exception e) {
+                    reservedException = e;
+                }
+            }
+
+            sslContext = mediator;
+        }
+    }
+
+    /*
+     * The SSLContext implementation for default "Default" algorithm
+     *
+     * @see SSLContext
+     */
+    public static final class DefaultSSLContext extends CustomizedTLSContext {
+
+        // public constructor for SSLContext.getInstance("Default")
+        public DefaultSSLContext() throws Exception {
+            if (DefaultManagersHolder.reservedException != null) {
+                throw DefaultManagersHolder.reservedException;
+            }
+
+            try {
+                super.engineInit(DefaultManagersHolder.keyManagers,
+                        DefaultManagersHolder.trustManagers, null);
+            } catch (Exception e) {
+                if (debug != null && Debug.isOn("defaultctx")) {
+                    System.out.println("default context init failed: " + e);
+                }
+                throw e;
+            }
+        }
+
+        @Override
+        protected void engineInit(KeyManager[] km, TrustManager[] tm,
+                                  SecureRandom sr) throws KeyManagementException {
+            throw new KeyManagementException
+                    ("Default SSLContext is initialized automatically");
+        }
+
+        static SSLContextImpl getDefaultImpl() throws Exception {
+            if (DefaultSSLContextHolder.reservedException != null) {
+                throw DefaultSSLContextHolder.reservedException;
+            }
+
+            return DefaultSSLContextHolder.sslContext;
+        }
+    }
+
+
 }
 
 
--- a/src/share/classes/sun/security/ssl/ServerHandshaker.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/security/ssl/ServerHandshaker.java	Mon Aug 08 15:29:16 2016 -0700
@@ -137,8 +137,10 @@
                 customizedDHKeySize = Integer.parseUnsignedInt(property);
                 if (customizedDHKeySize < 1024 || customizedDHKeySize > 2048) {
                     throw new IllegalArgumentException(
-                        "Customized DH key size should be positive integer " +
-                        "between 1024 and 2048 bits, inclusive");
+                        "Unsupported customized DH key size: " +
+                        customizedDHKeySize + ". " +
+                        "The key size can only range from 1024" +
+                        " to 2048 (inclusive)");
                 }
             } catch (NumberFormatException nfe) {
                 throw new IllegalArgumentException(
--- a/src/share/classes/sun/tools/native2ascii/Main.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/classes/sun/tools/native2ascii/Main.java	Mon Aug 08 15:29:16 2016 -0700
@@ -71,11 +71,8 @@
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.Charset;
 import java.nio.charset.IllegalCharsetNameException;
-import java.nio.file.Files;
 import java.io.UnsupportedEncodingException;
 import java.nio.charset.UnsupportedCharsetException;
-import sun.tools.native2ascii.A2NFilter;
-import sun.tools.native2ascii.N2AFilter;
 
 /**
  * Main program of the native2ascii
@@ -94,7 +91,7 @@
     /**
      * Run the converter
      */
-    public synchronized boolean convert(String argv[]){
+    public synchronized boolean convert(String argv[]) {
         List<String> v = new ArrayList<>(2);
         File outputFile = null;
         boolean createOutputFile = false;
@@ -102,14 +99,14 @@
         // Parse arguments
         for (int i = 0; i < argv.length; i++) {
             if (argv[i].equals("-encoding")) {
-                if ((i + 1) < argv.length){
+                if ((i + 1) < argv.length) {
                     encodingString = argv[++i];
                 } else {
                     error(getMsg("err.bad.arg"));
                     usage();
                     return false;
                 }
-            } else if (argv[i].equals("-reverse")){
+            } else if (argv[i].equals("-reverse")) {
                 reverse = true;
             } else {
                 if (v.size() > 1) {
@@ -119,15 +116,18 @@
                 v.add(argv[i]);
             }
         }
-        if (encodingString == null)
-           defaultEncoding = Charset.defaultCharset().name();
 
+        if (encodingString == null) {
+            defaultEncoding = Charset.defaultCharset().name();
+        }
         char[] lineBreak = System.getProperty("line.separator").toCharArray();
+
         try {
             initializeConverter();
 
-            if (v.size() == 1)
+            if (v.size() == 1) {
                 inputFileName = v.get(0);
+            }
 
             if (v.size() == 2) {
                 inputFileName = v.get(0);
@@ -137,40 +137,38 @@
 
             if (createOutputFile) {
                 outputFile = new File(outputFileName);
-                    if (outputFile.exists() && !outputFile.canWrite()) {
-                        throw new Exception(formatMsg("err.cannot.write", outputFileName));
-                    }
+                if (outputFile.exists() && !outputFile.canWrite()) {
+                    throw new Exception(formatMsg("err.cannot.write", outputFileName));
+                }
             }
 
-            if (reverse){
-                BufferedReader reader = getA2NInput(inputFileName);
-                Writer osw = getA2NOutput(outputFileName);
-                String line;
-
-                while ((line = reader.readLine()) != null) {
-                    osw.write(line.toCharArray());
-                    osw.write(lineBreak);
-                    if (outputFileName == null) { // flush stdout
-                        osw.flush();
+            if (reverse) {
+                try (BufferedReader reader = getA2NInput(inputFileName);
+                        Writer osw = getA2NOutput(outputFileName);) {
+                    String line;
+                    while ((line = reader.readLine()) != null) {
+                        osw.write(line.toCharArray());
+                        osw.write(lineBreak);
+                        if (outputFileName == null) { // flush stdout
+                            osw.flush();
+                        }
                     }
                 }
-                reader.close();  // Close the stream.
-                osw.close();
             } else {
-             //N2A
-                String inLine;
-                BufferedReader in = getN2AInput(inputFileName);
-                BufferedWriter out = getN2AOutput(outputFileName);
-
-                while ((inLine = in.readLine()) != null) {
-                    out.write(inLine.toCharArray());
-                    out.write(lineBreak);
-                    if (outputFileName == null) { // flush stdout
-                        out.flush();
+                // N2A
+                try (BufferedReader in = getN2AInput(inputFileName);
+                        BufferedWriter out = getN2AOutput(outputFileName);) {
+                    String inLine;
+                    while ((inLine = in.readLine()) != null) {
+                        out.write(inLine.toCharArray());
+                        out.write(lineBreak);
+                        if (outputFileName == null) { // flush stdout
+                            out.flush();
+                        }
                     }
                 }
-                out.close();
             }
+
             // Since we are done rename temporary file to desired output file
             if (createOutputFile) {
                 if (outputFile.exists()) {
@@ -182,8 +180,7 @@
                 }
                 tempFile.renameTo(outputFile);
             }
-
-        } catch(Exception e){
+        } catch (Exception e) {
             error(e.toString());
             return false;
         }
--- a/src/share/lib/security/sunpkcs11-solaris.cfg	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/share/lib/security/sunpkcs11-solaris.cfg	Mon Aug 08 15:29:16 2016 -0700
@@ -18,6 +18,7 @@
 
 disabledMechanisms = {
   CKM_DSA_KEY_PAIR_GEN
+  SecureRandom
 # the following mechanisms are disabled due to performance issues
 # (Solaris bug 6337157)
   CKM_DSA_SHA1
--- a/src/solaris/bin/jexec.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/bin/jexec.c	Mon Aug 08 15:29:16 2016 -0700
@@ -331,6 +331,7 @@
                 off_t end   = start  + xlen;
 
                 if (end <= count) {
+                    end -= 4; // make sure there are 4 bytes to read at start
                     while (start < end) {
                         off_t xhid  = SH(buf, start);
                         off_t xdlen = SH(buf, start + 2);
--- a/src/solaris/classes/sun/java2d/xr/XRRenderer.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/classes/sun/java2d/xr/XRRenderer.java	Mon Aug 08 15:29:16 2016 -0700
@@ -28,6 +28,7 @@
 import java.awt.*;
 import java.awt.geom.*;
 import sun.awt.SunToolkit;
+import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.*;
 import sun.java2d.pipe.Region;
@@ -69,7 +70,12 @@
      * destination context.
      */
     private final void validateSurface(SunGraphics2D sg2d) {
-        XRSurfaceData xrsd = (XRSurfaceData) sg2d.surfaceData;
+        XRSurfaceData xrsd;
+        try {
+            xrsd = (XRSurfaceData) sg2d.surfaceData;
+        } catch (ClassCastException e) {
+            throw new InvalidPipeException("wrong surface data type: " + sg2d.surfaceData);
+        }
         xrsd.validateAsDestination(sg2d, sg2d.getCompClip());
         xrsd.maskBuffer.validateCompositeState(sg2d.composite, sg2d.transform,
                                                sg2d.paint, sg2d);
--- a/src/solaris/classes/sun/security/provider/NativePRNG.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/classes/sun/security/provider/NativePRNG.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,8 @@
 import java.io.*;
 import java.net.*;
 import java.security.*;
+import java.util.Arrays;
+
 import sun.security.util.Debug;
 
 /**
@@ -334,7 +336,9 @@
         private final static long MAX_BUFFER_TIME = 100;
 
         // size of the "next" buffer
-        private final static int BUFFER_SIZE = 32;
+        private static final int MAX_BUFFER_SIZE = 65536;
+        private static final int MIN_BUFFER_SIZE = 32;
+        private int bufferSize = 256;
 
         // Holder for the seedFile.  Used if we ever add seed material.
         File seedFile;
@@ -351,7 +355,7 @@
         private volatile sun.security.provider.SecureRandom mixRandom;
 
         // buffer for next bits
-        private final byte[] nextBuffer;
+        private byte[] nextBuffer;
 
         // number of bytes left in nextBuffer
         private int buffered;
@@ -359,6 +363,16 @@
         // time we read the data into the nextBuffer
         private long lastRead;
 
+        // Count for the number of buffer size changes requests
+        // Positive value in increase size, negative to lower it.
+        private int change_buffer = 0;
+
+        // Request limit to trigger an increase in nextBuffer size
+        private static final int REQ_LIMIT_INC = 1000;
+
+        // Request limit to trigger a decrease in nextBuffer size
+        private static final int REQ_LIMIT_DEC = -100;
+
         // mutex lock for nextBytes()
         private final Object LOCK_GET_BYTES = new Object();
 
@@ -373,7 +387,7 @@
             this.seedFile = seedFile;
             seedIn = new FileInputStream(seedFile);
             nextIn = new FileInputStream(nextFile);
-            nextBuffer = new byte[BUFFER_SIZE];
+            nextBuffer = new byte[bufferSize];
         }
 
         // get the SHA1PRNG for mixing
@@ -466,9 +480,47 @@
         // if not, read new bytes
         private void ensureBufferValid() throws IOException {
             long time = System.currentTimeMillis();
-            if ((buffered > 0) && (time - lastRead < MAX_BUFFER_TIME)) {
-                return;
+            int new_buffer_size = 0;
+
+            // Check if buffer has bytes available that are not too old
+            if (buffered > 0) {
+                if (time - lastRead < MAX_BUFFER_TIME) {
+                    return;
+                } else {
+                    // byte is old, so subtract from counter to shrink buffer
+                    change_buffer--;
+                }
+            } else {
+                // No bytes available, so add to count to increase buffer
+                change_buffer++;
             }
+
+            // If counter has it a limit, increase or decrease size
+            if (change_buffer > REQ_LIMIT_INC) {
+                new_buffer_size = nextBuffer.length * 2;
+            } else if (change_buffer < REQ_LIMIT_DEC) {
+                new_buffer_size = nextBuffer.length / 2;
+            }
+
+            // If buffer size is to be changed, replace nextBuffer.
+            if (new_buffer_size > 0) {
+                if (new_buffer_size <= MAX_BUFFER_SIZE &&
+                        new_buffer_size >= MIN_BUFFER_SIZE) {
+                    nextBuffer = new byte[new_buffer_size];
+                    if (debug != null) {
+                        debug.println("Buffer size changed to " +
+                                new_buffer_size);
+                    }
+                } else {
+                    if (debug != null) {
+                        debug.println("Buffer reached limit: " +
+                                nextBuffer.length);
+                    }
+                }
+                change_buffer = 0;
+            }
+
+            // Load fresh random bytes into nextBuffer
             lastRead = time;
             readFully(nextIn, nextBuffer);
             buffered = nextBuffer.length;
@@ -478,24 +530,40 @@
         // read from "next" and XOR with bytes generated by the
         // mixing SHA1PRNG
         private void implNextBytes(byte[] data) {
-            synchronized (LOCK_GET_BYTES) {
                 try {
                     getMixRandom().engineNextBytes(data);
-                    int len = data.length;
+                    int data_len = data.length;
                     int ofs = 0;
-                    while (len > 0) {
-                        ensureBufferValid();
-                        int bufferOfs = nextBuffer.length - buffered;
-                        while ((len > 0) && (buffered > 0)) {
-                            data[ofs++] ^= nextBuffer[bufferOfs++];
-                            len--;
-                            buffered--;
+                    int len;
+                    int buf_pos;
+                    int localofs;
+                    byte[] localBuffer;
+
+                    while (data_len > 0) {
+                        synchronized (LOCK_GET_BYTES) {
+                            ensureBufferValid();
+                            buf_pos = nextBuffer.length - buffered;
+                            if (data_len > buffered) {
+                                len = buffered;
+                                buffered = 0;
+                            } else {
+                                len = data_len;
+                                buffered -= len;
+                            }
+                            localBuffer = Arrays.copyOfRange(nextBuffer, buf_pos,
+                                    buf_pos + len);
                         }
+                        localofs = 0;
+                        while (len > localofs) {
+                            data[ofs] ^= localBuffer[localofs];
+                            ofs++;
+                            localofs++;
+                        }
+                    data_len -= len;
                     }
-                } catch (IOException e) {
+                } catch (IOException e){
                     throw new ProviderException("nextBytes() failed", e);
                 }
-            }
         }
-    }
+        }
 }
--- a/src/solaris/native/java/net/NetworkInterface.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/native/java/net/NetworkInterface.c	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,6 @@
  * questions.
  */
 
-
 #include <errno.h>
 #include <strings.h>
 #if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
@@ -38,14 +37,14 @@
 #include <net/if.h>
 #include <net/if_arp.h>
 
-#ifdef __solaris__
+#if defined(__solaris__)
 #include <sys/dlpi.h>
 #include <fcntl.h>
 #include <stropts.h>
 #include <sys/sockio.h>
 #endif
 
-#ifdef __linux__
+#if defined(__linux__)
 #include <sys/ioctl.h>
 #include <bits/ioctls.h>
 #include <sys/utsname.h>
@@ -59,10 +58,6 @@
 #include <sys/kinfo.h>
 #endif
 
-#ifdef __linux__
-#define _PATH_PROCNET_IFINET6           "/proc/net/if_inet6"
-#endif
-
 #if defined(_ALLBSD_SOURCE)
 #include <sys/param.h>
 #include <sys/ioctl.h>
@@ -80,6 +75,10 @@
 #include "jni_util.h"
 #include "net_util.h"
 
+#if defined(__linux__)
+#define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
+#endif
+
 typedef struct _netaddr  {
     struct sockaddr *addr;
     struct sockaddr *brdcast;
@@ -140,29 +139,32 @@
 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 #endif
 
-static netif  *addif(JNIEnv *env, int sock, const char * if_name, netif *ifs, struct sockaddr* ifr_addrP, int family, short prefix);
+static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
+                     struct sockaddr *ifr_addrP, int family, short prefix);
 static void    freeif(netif *ifs);
 
 static int     openSocket(JNIEnv *env, int proto);
 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 
 
-static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name, struct sockaddr *brdcast_store);
+static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name,
+                                      struct sockaddr *brdcast_store);
 static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
 static int     getIndex(int sock, const char *ifname);
 
 static int     getFlags(int sock, const char *ifname, int *flags);
-static int     getMacAddress(JNIEnv *env, int sock,  const char* ifname, const struct in_addr* addr, unsigned char *buf);
+static int     getMacAddress(JNIEnv *env, int sock,  const char *ifname,
+                             const struct in_addr *addr, unsigned char *buf);
 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 
 
-
-#ifdef __solaris__
-static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
-static int    getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf);
+#if defined(__solaris__)
+static netif  *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
+static int     getMacFromDevice(JNIEnv *env, const char *ifname,
+                                unsigned char *retbuf);
 
 #ifndef SIOCGLIFHWADDR
-#define SIOCGLIFHWADDR  _IOWR('i', 192, struct lifreq)
+#define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
 #endif
 
 #endif
@@ -174,31 +176,36 @@
  * Method:    init
  * Signature: ()V
  */
-JNIEXPORT void JNICALL
-Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls) {
-    ni_class = (*env)->FindClass(env,"java/net/NetworkInterface");
+JNIEXPORT void JNICALL Java_java_net_NetworkInterface_init
+  (JNIEnv *env, jclass cls)
+{
+    ni_class = (*env)->FindClass(env, "java/net/NetworkInterface");
     CHECK_NULL(ni_class);
     ni_class = (*env)->NewGlobalRef(env, ni_class);
     CHECK_NULL(ni_class);
-    ni_nameID = (*env)->GetFieldID(env, ni_class,"name", "Ljava/lang/String;");
+    ni_nameID = (*env)->GetFieldID(env, ni_class, "name", "Ljava/lang/String;");
     CHECK_NULL(ni_nameID);
     ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
     CHECK_NULL(ni_indexID);
-    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs", "[Ljava/net/InetAddress;");
+    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs",
+                                    "[Ljava/net/InetAddress;");
     CHECK_NULL(ni_addrsID);
-    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings", "[Ljava/net/InterfaceAddress;");
+    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings",
+                                    "[Ljava/net/InterfaceAddress;");
     CHECK_NULL(ni_bindsID);
-    ni_descID = (*env)->GetFieldID(env, ni_class, "displayName", "Ljava/lang/String;");
+    ni_descID = (*env)->GetFieldID(env, ni_class, "displayName",
+                                   "Ljava/lang/String;");
     CHECK_NULL(ni_descID);
     ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
     CHECK_NULL(ni_virutalID);
-    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs", "[Ljava/net/NetworkInterface;");
+    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs",
+                                     "[Ljava/net/NetworkInterface;");
     CHECK_NULL(ni_childsID);
-    ni_parentID = (*env)->GetFieldID(env, ni_class, "parent", "Ljava/net/NetworkInterface;");
+    ni_parentID = (*env)->GetFieldID(env, ni_class, "parent",
+                                     "Ljava/net/NetworkInterface;");
     CHECK_NULL(ni_parentID);
     ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
     CHECK_NULL(ni_ctrID);
-
     ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
     CHECK_NULL(ni_iacls);
     ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
@@ -221,24 +228,26 @@
     CHECK_NULL(ni_ia6ctrID);
     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
     CHECK_NULL(ni_ibctrID);
-    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
+    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address",
+                                        "Ljava/net/InetAddress;");
     CHECK_NULL(ni_ibaddressID);
-    ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
+    ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast",
+                                           "Ljava/net/Inet4Address;");
     CHECK_NULL(ni_ib4broadcastID);
     ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
     CHECK_NULL(ni_ib4maskID);
-    ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex", "I");
+    ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex",
+                                                 "I");
 }
 
-
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getByName0
  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
-    (JNIEnv *env, jclass cls, jstring name) {
-
+  (JNIEnv *env, jclass cls, jstring name)
+{
     netif *ifs, *curr;
     jboolean isCopy;
     const char* name_utf;
@@ -256,9 +265,8 @@
        freeif(ifs);
        return NULL;
     }
-    /*
-     * Search the list of interface based on name
-     */
+
+    // Search the list of interface based on name
     curr = ifs;
     while (curr != NULL) {
         if (strcmp(name_utf, curr->name) == 0) {
@@ -267,27 +275,26 @@
         curr = curr->next;
     }
 
-    /* if found create a NetworkInterface */
+    // if found create a NetworkInterface
     if (curr != NULL) {;
         obj = createNetworkInterface(env, curr);
     }
 
-    /* release the UTF string and interface list */
+    // release the UTF string and interface list
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
     freeif(ifs);
 
     return obj;
 }
 
-
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getByIndex0
  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
-    (JNIEnv *env, jclass cls, jint index) {
-
+  (JNIEnv *env, jclass cls, jint index)
+{
     netif *ifs, *curr;
     jobject obj = NULL;
 
@@ -300,9 +307,7 @@
         return NULL;
     }
 
-    /*
-     * Search the list of interface based on index
-     */
+    // Search the list of interface based on index
     curr = ifs;
     while (curr != NULL) {
         if (index == curr->index) {
@@ -311,7 +316,7 @@
         curr = curr->next;
     }
 
-    /* if found create a NetworkInterface */
+    // if found create a NetworkInterface
     if (curr != NULL) {;
         obj = createNetworkInterface(env, curr);
     }
@@ -326,8 +331,8 @@
  * Signature: (Ljava/net/InetAddress;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
-    (JNIEnv *env, jclass cls, jobject iaObj) {
-
+  (JNIEnv *env, jclass cls, jobject iaObj)
+{
     netif *ifs, *curr;
 
 #ifdef AF_INET6
@@ -348,14 +353,13 @@
     while (curr != NULL) {
         netaddr *addrP = curr->addr;
 
-        /*
-         * Iterate through each address on the interface
-         */
+        // Iterate through each address on the interface
         while (addrP != NULL) {
 
             if (family == addrP->family) {
                 if (family == AF_INET) {
-                    int address1 = htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
+                    int address1 = htonl(
+                        ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
                     int address2 = getInetAddress_addr(env, iaObj);
 
                     if (address1 == address2) {
@@ -366,7 +370,8 @@
 
 #ifdef AF_INET6
                 if (family == AF_INET6) {
-                    jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
+                    jbyte *bytes = (jbyte *)&(
+                        ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
                     jbyte caddr[16];
                     int i;
                     getInet6Address_ipaddress(env, iaObj, (char *)caddr);
@@ -383,7 +388,6 @@
                     }
                 }
 #endif
-
             }
 
             if (match) {
@@ -398,7 +402,7 @@
         curr = curr->next;
     }
 
-    /* if found create a NetworkInterface */
+    // if found create a NetworkInterface
     if (match) {;
         obj = createNetworkInterface(env, curr);
     }
@@ -407,15 +411,14 @@
     return obj;
 }
 
-
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getAll
  * Signature: ()[Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
-    (JNIEnv *env, jclass cls) {
-
+  (JNIEnv *env, jclass cls)
+{
     netif *ifs, *curr;
     jobjectArray netIFArr;
     jint arr_index, ifCount;
@@ -425,7 +428,7 @@
         return NULL;
     }
 
-    /* count the interface */
+    // count the interface
     ifCount = 0;
     curr = ifs;
     while (curr != NULL) {
@@ -433,17 +436,15 @@
         curr = curr->next;
     }
 
-    /* allocate a NetworkInterface array */
+    // allocate a NetworkInterface array
     netIFArr = (*env)->NewObjectArray(env, ifCount, cls, NULL);
     if (netIFArr == NULL) {
         freeif(ifs);
         return NULL;
     }
 
-    /*
-     * Iterate through the interfaces, create a NetworkInterface instance
-     * for each array element and populate the object.
-     */
+    // Iterate through the interfaces, create a NetworkInterface instance
+    // for each array element and populate the object.
     curr = ifs;
     arr_index = 0;
     while (curr != NULL) {
@@ -455,7 +456,7 @@
             return NULL;
         }
 
-        /* put the NetworkInterface into the array */
+        // put the NetworkInterface into the array
         (*env)->SetObjectArrayElement(env, netIFArr, arr_index++, netifObj);
 
         curr = curr->next;
@@ -465,13 +466,14 @@
     return netIFArr;
 }
 
-
 /*
  * Class:     java_net_NetworkInterface
  * Method:    isUp0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0(JNIEnv *env, jclass cls, jstring name, jint index) {
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0
+  (JNIEnv *env, jclass cls, jstring name, jint index)
+{
     int ret = getFlags0(env, name);
     return ((ret & IFF_UP) && (ret & IFF_RUNNING)) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -481,7 +483,9 @@
  * Method:    isP2P0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0(JNIEnv *env, jclass cls, jstring name, jint index) {
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
+  (JNIEnv *env, jclass cls, jstring name, jint index)
+{
     int ret = getFlags0(env, name);
     return (ret & IFF_POINTOPOINT) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -491,7 +495,9 @@
  * Method:    isLoopback0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0(JNIEnv *env, jclass cls, jstring name, jint index) {
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0
+  (JNIEnv *env, jclass cls, jstring name, jint index)
+{
     int ret = getFlags0(env, name);
     return (ret & IFF_LOOPBACK) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -501,7 +507,9 @@
  * Method:    supportsMulticast0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0(JNIEnv *env, jclass cls, jstring name, jint index) {
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0
+  (JNIEnv *env, jclass cls, jstring name, jint index)
+{
     int ret = getFlags0(env, name);
     return (ret & IFF_MULTICAST) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -511,7 +519,9 @@
  * Method:    getMacAddr0
  * Signature: ([bLjava/lang/String;I)[b
  */
-JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0(JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
+JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
+  (JNIEnv *env, jclass cls, jbyteArray addrArray, jstring name, jint index)
+{
     jint addr;
     jbyte caddr[4];
     struct in_addr iaddr;
@@ -533,7 +543,6 @@
        return NULL;
     }
 
-
     if (!IS_NULL(addrArray)) {
        (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
        addr = ((caddr[0]<<24) & 0xff000000);
@@ -543,7 +552,7 @@
        iaddr.s_addr = htonl(addr);
        len = getMacAddress(env, sock, name_utf, &iaddr, mac);
     } else {
-       len = getMacAddress(env, sock, name_utf,NULL, mac);
+       len = getMacAddress(env, sock, name_utf, NULL, mac);
     }
     if (len > 0) {
        ret = (*env)->NewByteArray(env, len);
@@ -551,10 +560,10 @@
           /* we may have memory to free at the end of this */
           goto fexit;
        }
-       (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) (mac));
+       (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
     }
  fexit:
-   /* release the UTF string and interface list */
+   // release the UTF string and interface list
    (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
    close(sock);
@@ -566,8 +575,9 @@
  * Method:      getMTU0
  * Signature:   ([bLjava/lang/String;I)I
  */
-
-JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0(JNIEnv *env, jclass class, jstring name, jint index) {
+JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
+  (JNIEnv *env, jclass cls, jstring name, jint index)
+{
     jboolean isCopy;
     int ret = -1;
     int sock;
@@ -585,7 +595,7 @@
        return ret;
     }
 
-    if ((sock =openSocketWithFallback(env, name_utf)) < 0) {
+    if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
        (*env)->ReleaseStringUTFChars(env, name, name_utf);
        return JNI_FALSE;
     }
@@ -628,19 +638,17 @@
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
     if (ret < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGLIFFLAGS failed");
         return -1;
     }
 
     return flags;
 }
 
-
-
-
 /*
- * Create a NetworkInterface object, populate the name and index, and
- * populate the InetAddress array based on the IP addresses for this
+ * Creates a NetworkInterface object, populates the name, the index, and
+ * populates the InetAddress array based on the IP addresses for this
  * interface.
  */
 jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
@@ -656,9 +664,7 @@
     netif *childP;
     jobject tmp;
 
-    /*
-     * Create a NetworkInterface object and populate it
-     */
+    // Create a NetworkInterface object and populate it
     netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
     CHECK_NULL_RETURN(netifObj, NULL);
     name = (*env)->NewStringUTF(env, ifs->name);
@@ -666,11 +672,10 @@
     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
     (*env)->SetObjectField(env, netifObj, ni_descID, name);
     (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);
-    (*env)->SetBooleanField(env, netifObj, ni_virutalID, ifs->virtual ? JNI_TRUE : JNI_FALSE);
+    (*env)->SetBooleanField(env, netifObj, ni_virutalID,
+                            ifs->virtual ? JNI_TRUE : JNI_FALSE);
 
-    /*
-     * Count the number of address on this interface
-     */
+    //Count the number of address on this interface
     addr_count = 0;
     addrP = ifs->addr;
     while (addrP != NULL) {
@@ -678,10 +683,8 @@
         addrP = addrP->next;
     }
 
-    /*
-     * Create the array of InetAddresses
-     */
-    addrArr = (*env)->NewObjectArray(env, addr_count,  ni_iacls, NULL);
+    // Create the array of InetAddresses
+    addrArr = (*env)->NewObjectArray(env, addr_count, ni_iacls, NULL);
     if (addrArr == NULL) {
         return NULL;
     }
@@ -700,7 +703,8 @@
         if (addrP->family == AF_INET) {
             iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
             if (iaObj) {
-                 setInetAddress_addr(env, iaObj, htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
+                 setInetAddress_addr(env, iaObj, htonl(
+                     ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
             } else {
                 return NULL;
             }
@@ -711,7 +715,8 @@
                     jobject ia2Obj = NULL;
                     ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
                     if (ia2Obj) {
-                       setInetAddress_addr(env, ia2Obj, htonl(((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
+                       setInetAddress_addr(env, ia2Obj, htonl(
+                           ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
                        (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
                     } else {
                         return NULL;
@@ -729,7 +734,8 @@
             int scope=0;
             iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
-                int ret = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
+                jboolean ret = setInet6Address_ipaddress(env, iaObj,
+                    (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
                 if (ret == JNI_FALSE) {
                     return NULL;
                 }
@@ -758,9 +764,7 @@
         addrP = addrP->next;
     }
 
-    /*
-     * See if there is any virtual interface attached to this one.
-     */
+    // See if there is any virtual interface attached to this one.
     child_count = 0;
     childP = ifs->childs;
     while (childP) {
@@ -773,10 +777,7 @@
         return NULL;
     }
 
-    /*
-     * Create the NetworkInterface instances for the sub-interfaces as
-     * well.
-     */
+    // Create the NetworkInterface instances for the sub-interfaces as well.
     child_index = 0;
     childP = ifs->childs;
     while(childP) {
@@ -792,7 +793,7 @@
     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
     (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);
 
-    /* return the NetworkInterface */
+    // return the NetworkInterface
     return netifObj;
 }
 
@@ -803,10 +804,7 @@
     netif *ifs;
     int sock;
 
-    /*
-     * Enumerate IPv4 addresses
-     */
-
+    // Enumerate IPv4 addresses
     sock = openSocket(env, AF_INET);
     if (sock < 0 && (*env)->ExceptionOccurred(env)) {
         return NULL;
@@ -819,19 +817,16 @@
         return NULL;
     }
 
-    /* return partial list if an exception occurs in the middle of process ???*/
+    // return partial list if an exception occurs in the middle of process ???
 
-    /*
-     * If IPv6 is available then enumerate IPv6 addresses.
-     */
+    // If IPv6 is available then enumerate IPv6 addresses.
 #ifdef AF_INET6
 
-        /* User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
-         * so we have to call ipv6_available()
-         */
+        // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
+        // so we have to call ipv6_available()
         if (ipv6_available()) {
 
-           sock =  openSocket(env, AF_INET6);
+           sock = openSocket(env, AF_INET6);
            if (sock < 0 && (*env)->ExceptionOccurred(env)) {
                freeif(ifs);
                return NULL;
@@ -851,18 +846,18 @@
     return ifs;
 }
 
-#define CHECKED_MALLOC3(_pointer,_type,_size) \
-       do{ \
-        _pointer = (_type)malloc( _size ); \
+#define CHECKED_MALLOC3(_pointer, _type, _size) \
+    do { \
+        _pointer = (_type)malloc(_size); \
         if (_pointer == NULL) { \
             JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
             return ifs; /* return untouched list */ \
         } \
-       } while(0)
+    } while(0)
 
 
 /*
- * Free an interface list (including any attached addresses)
+ * Frees an interface list (including any attached addresses)
  */
 void freeif(netif *ifs) {
     netif *currif = ifs;
@@ -874,24 +869,21 @@
             netaddr *next = addrP->next;
             free(addrP);
             addrP = next;
-         }
+        }
 
-            /*
-            * Don't forget to free the sub-interfaces.
-            */
-          if (currif->childs != NULL) {
-                freeif(currif->childs);
-          }
+        // Don't forget to free the sub-interfaces.
+        if (currif->childs != NULL) {
+            freeif(currif->childs);
+        }
 
-          ifs = currif->next;
-          free(currif);
-          currif = ifs;
+        ifs = currif->next;
+        free(currif);
+        currif = ifs;
     }
 }
 
-netif *addif(JNIEnv *env, int sock, const char * if_name,
-             netif *ifs, struct sockaddr* ifr_addrP, int family,
-             short prefix)
+netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
+             struct sockaddr *ifr_addrP, int family, short prefix)
 {
     netif *currif = ifs, *parent;
     netaddr *addrP;
@@ -904,37 +896,34 @@
     char name[IFNAMSIZ], vname[IFNAMSIZ];
 #endif
 
-    char  *name_colonP;
+    char *name_colonP;
     int mask;
     int isVirtual = 0;
     int addr_size;
     int flags = 0;
 
-    /*
-     * If the interface name is a logical interface then we
-     * remove the unit number so that we have the physical
-     * interface (eg: hme0:1 -> hme0). NetworkInterface
-     * currently doesn't have any concept of physical vs.
-     * logical interfaces.
-     */
+    // If the interface name is a logical interface then we remove the unit
+    // number so that we have the physical interface (eg: hme0:1 -> hme0).
+    // NetworkInterface currently doesn't have any concept of physical vs.
+    // logical interfaces.
     strncpy(name, if_name, ifnam_size);
     name[ifnam_size - 1] = '\0';
     *vname = 0;
 
-    /*
-     * Create and populate the netaddr node. If allocation fails
-     * return an un-updated list.
-     */
-    /*Allocate for addr and brdcast at once*/
+     // Create and populate the netaddr node. If allocation fails
+     // return an un-updated list.
+
+     // Allocate for addr and brdcast at once
 
 #ifdef AF_INET6
-    addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
+    addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
+                                    : sizeof(struct sockaddr_in6);
 #else
     addr_size = sizeof(struct sockaddr_in);
 #endif
 
-    CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr)+2*addr_size);
-    addrP->addr = (struct sockaddr *)( (char *) addrP+sizeof(netaddr) );
+    CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr) + 2 * addr_size);
+    addrP->addr = (struct sockaddr *)((char *)addrP + sizeof(netaddr));
     memcpy(addrP->addr, ifr_addrP, addr_size);
 
     addrP->family = family;
@@ -943,8 +932,9 @@
     addrP->next = 0;
     if (family == AF_INET) {
        // Deal with broadcast addr & subnet mask
-       struct sockaddr * brdcast_to = (struct sockaddr *) ((char *) addrP + sizeof(netaddr) + addr_size);
-       addrP->brdcast = getBroadcast(env, sock, name,  brdcast_to );
+       struct sockaddr *brdcast_to =
+              (struct sockaddr *) ((char *)addrP + sizeof(netaddr) + addr_size);
+       addrP->brdcast = getBroadcast(env, sock, name, brdcast_to);
        if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
            return ifs;
        }
@@ -955,36 +945,28 @@
        }
      }
 
-    /**
-     * Deal with virtual interface with colon notation e.g. eth0:1
-     */
+    // Deal with virtual interface with colon notation e.g. eth0:1
     name_colonP = strchr(name, ':');
     if (name_colonP != NULL) {
-      /**
-       * This is a virtual interface. If we are able to access the parent
-       * we need to create a new entry if it doesn't exist yet *and* update
-       * the 'parent' interface with the new records.
-       */
+        // This is a virtual interface. If we are able to access the parent
+        // we need to create a new entry if it doesn't exist yet *and* update
+        // the 'parent' interface with the new records.
         *name_colonP = 0;
         if (getFlags(sock, name, &flags) < 0 || flags < 0) {
-            // failed to access parent interface do not create parent.
-            // We are a virtual interface with no parent.
-            isVirtual = 1;
-            *name_colonP = ':';
-        }
-        else{
-           // Got access to parent, so create it if necessary.
-           // Save original name to vname and truncate name by ':'
-            memcpy(vname, name, sizeof(vname) );
-            vname[name_colonP - name] = ':';
+             // failed to access parent interface do not create parent.
+             // We are a virtual interface with no parent.
+             isVirtual = 1;
+             *name_colonP = ':';
+        } else {
+             // Got access to parent, so create it if necessary.
+             // Save original name to vname and truncate name by ':'
+             memcpy(vname, name, sizeof(vname) );
+             vname[name_colonP - name] = ':';
         }
     }
 
-    /*
-     * Check if this is a "new" interface. Use the interface
-     * name for matching because index isn't supported on
-     * Solaris 2.6 & 7.
-     */
+    // Check if this is a "new" interface. Use the interface name for
+    // matching because index isn't supported on Solaris 2.6 & 7.
     while (currif != NULL) {
         if (strcmp(name, currif->name) == 0) {
             break;
@@ -992,13 +974,10 @@
         currif = currif->next;
     }
 
-    /*
-     * If "new" then create an netif structure and
-     * insert it onto the list.
-     */
+    // If "new" then create an netif structure and insert it into the list.
     if (currif == NULL) {
          CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
-         currif->name = (char *) currif+sizeof(netif);
+         currif->name = (char *)currif + sizeof(netif);
          strncpy(currif->name, name, ifnam_size);
          currif->name[ifnam_size - 1] = '\0';
          currif->index = getIndex(sock, name);
@@ -1009,17 +988,13 @@
          ifs = currif;
     }
 
-    /*
-     * Finally insert the address on the interface
-     */
+    // Finally insert the address on the interface
     addrP->next = currif->addr;
     currif->addr = addrP;
 
     parent = currif;
 
-    /**
-     * Let's deal with the virtual interface now.
-     */
+    // Deal with the virtual interface now.
     if (vname[0]) {
         netaddr *tmpaddr;
 
@@ -1034,27 +1009,29 @@
 
         if (currif == NULL) {
             CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
-            currif->name = (char *) currif + sizeof(netif);
+            currif->name = (char *)currif + sizeof(netif);
             strncpy(currif->name, vname, ifnam_size);
             currif->name[ifnam_size - 1] = '\0';
             currif->index = getIndex(sock, vname);
             currif->addr = NULL;
-           /* Need to duplicate the addr entry? */
+            // Need to duplicate the addr entry?
             currif->virtual = 1;
             currif->childs = NULL;
             currif->next = parent->childs;
             parent->childs = currif;
         }
 
-        CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr)+2*addr_size);
+        CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr) + 2 * addr_size);
         memcpy(tmpaddr, addrP, sizeof(netaddr));
         if (addrP->addr != NULL) {
-            tmpaddr->addr = (struct sockaddr *) ( (char*)tmpaddr + sizeof(netaddr) ) ;
+            tmpaddr->addr = (struct sockaddr *)
+                ((char*)tmpaddr + sizeof(netaddr));
             memcpy(tmpaddr->addr, addrP->addr, addr_size);
         }
 
         if (addrP->brdcast != NULL) {
-            tmpaddr->brdcast = (struct sockaddr *) ((char *) tmpaddr + sizeof(netaddr)+addr_size);
+            tmpaddr->brdcast = (struct sockaddr *)
+                ((char *)tmpaddr + sizeof(netaddr) + addr_size);
             memcpy(tmpaddr->brdcast, addrP->brdcast, addr_size);
         }
 
@@ -1065,19 +1042,18 @@
     return ifs;
 }
 
-/* Open socket for further ioct calls
- * proto is AF_INET/AF_INET6
+/*
+ * Opens a socket for further ioct calls. proto is one of AF_INET or AF_INET6.
  */
-static int  openSocket(JNIEnv *env, int proto){
+static int openSocket(JNIEnv *env, int proto) {
     int sock;
 
     if ((sock = JVM_Socket(proto, SOCK_DGRAM, 0)) < 0) {
-        /*
-         * If EPROTONOSUPPORT is returned it means we don't have
-         * support  for this proto so don't throw an exception.
-         */
+        // If EPROTONOSUPPORT is returned it means we don't have
+        // support for this proto so don't throw an exception.
         if (errno != EPROTONOSUPPORT) {
-            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "Socket creation failed");
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "Socket creation failed");
         }
         return -1;
     }
@@ -1088,36 +1064,38 @@
 
 /** Linux, AIX **/
 #if defined(__linux__) || defined(_AIX)
-/* Open socket for further ioct calls, try v4 socket first and
- * if it falls return v6 socket
- */
 
 #ifdef AF_INET6
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+/*
+ * Opens a socket for further ioct calls. Tries AF_INET socket first and
+ * if it falls return AF_INET6 socket.
+ */
+// unused arg ifname and struct if2
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
     struct ifreq if2;
 
-     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-         if (errno == EPROTONOSUPPORT){
-              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
-                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                 return -1;
-              }
-         }
-         else{ // errno is not NOSUPPORT
-             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-             return -1;
-         }
-   }
+    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                             "IPV6 Socket creation failed");
+                return -1;
+            }
+        } else { // errno is not NOSUPPORT
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
 
-     /* Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or IPv6 socket regardless of type
-        of address of an interface */
-
-       return sock;
+    // Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or
+    // IPv6 socket regardless of type of address of an interface.
+    return sock;
 }
 
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     return openSocket(env,AF_INET);
 }
 #endif
@@ -1130,52 +1108,48 @@
     unsigned i;
     int siocgifconfRequest = SIOCGIFCONF;
 
-
 #if defined(__linux__)
-    /* need to do a dummy SIOCGIFCONF to determine the buffer size.
-     * SIOCGIFCOUNT doesn't work
-     */
+    // need to do a dummy SIOCGIFCONF to determine the buffer size.
+    // SIOCGIFCOUNT doesn't work
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFCONF failed");
         return ifs;
     }
 #elif defined(_AIX)
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGSIZIFCONF failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGSIZIFCONF failed");
         return ifs;
     }
 #endif /* __linux__ */
 
-    CHECKED_MALLOC3(buf,char *, ifc.ifc_len);
+    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
 
     ifc.ifc_buf = buf;
 #if defined(_AIX)
     siocgifconfRequest = CSIOCGIFCONF;
 #endif
     if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
-        (void) free(buf);
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFCONF failed");
+        free(buf);
         return ifs;
     }
 
-    /*
-     * Iterate through each interface
-     */
+    // Iterate through each interface
     ifreqP = ifc.ifc_req;
-    for (i=0; i<ifc.ifc_len/sizeof (struct ifreq); i++, ifreqP++) {
+    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
 #if defined(_AIX)
         if (ifreqP->ifr_addr.sa_family != AF_INET) continue;
 #endif
-        /*
-         * Add to the list
-         */
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs, (struct sockaddr *) & (ifreqP->ifr_addr), AF_INET, 0);
+        // Add to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->ifr_addr), AF_INET, 0);
 
-        /*
-         * If an exception occurred then free the list
-         */
+        // If an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             freeif(ifs);
@@ -1183,37 +1157,37 @@
         }
     }
 
-    /*
-     * Free socket and buffer
-     */
+    // Free socket and buffer
     free(buf);
     return ifs;
 }
 
 
+#if defined(AF_INET6) && defined(__linux__)
+
 /*
- * Enumerates and returns all IPv6 interfaces on Linux
+ * Enumerates and returns all IPv6 interfaces on Linux.
  */
-
-#if defined(AF_INET6) && defined(__linux__)
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     FILE *f;
     char addr6[40], devname[21];
     char addr6p[8][5];
-    int plen, scope, dad_status, if_idx;
+    int prefix, scope, dad_status, if_idx;
     uint8_t ipv6addr[16];
 
     if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
         while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
-                         addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7],
-                         &if_idx, &plen, &scope, &dad_status, devname) != EOF) {
+                      addr6p[0], addr6p[1], addr6p[2], addr6p[3],
+                      addr6p[4], addr6p[5], addr6p[6], addr6p[7],
+                      &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
 
             struct netif *ifs_ptr = NULL;
             struct netif *last_ptr = NULL;
             struct sockaddr_in6 addr;
 
             sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
-                           addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
+                    addr6p[0], addr6p[1], addr6p[2], addr6p[3],
+                    addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
             inet_pton(AF_INET6, addr6, ipv6addr);
 
             memset(&addr, 0, sizeof(struct sockaddr_in6));
@@ -1221,12 +1195,10 @@
 
             addr.sin6_scope_id = if_idx;
 
-            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr, AF_INET6, plen);
+            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
+                        AF_INET6, (short)prefix);
 
-
-            /*
-             * If an exception occurred then return the list as is.
-             */
+            // If an exception occurred then return the list as is.
             if ((*env)->ExceptionOccurred(env)) {
                 fclose(f);
                 return ifs;
@@ -1239,11 +1211,11 @@
 #endif
 
 
+#if defined(AF_INET6) && defined(_AIX)
+
 /*
- * Enumerates and returns all IPv6 interfaces on AIX
+ * Enumerates and returns all IPv6 interfaces on AIX.
  */
-
-#if defined(AF_INET6) && defined(_AIX)
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifconf ifc;
     struct ifreq *ifreqP;
@@ -1253,12 +1225,12 @@
     unsigned bufsize;
     char *cp, *cplimit;
 
-    /* use SIOCGSIZIFCONF to get size for  SIOCGIFCONF */
+    // use SIOCGSIZIFCONF to get size for  SIOCGIFCONF
 
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
-                        "ioctl SIOCGSIZIFCONF failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                    "ioctl SIOCGSIZIFCONF failed");
         return ifs;
     }
     bufsize = ifc.ifc_len;
@@ -1271,29 +1243,27 @@
     ifc.ifc_len = bufsize;
     ifc.ifc_buf = buf;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
-                       "ioctl CSIOCGIFCONF failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl CSIOCGIFCONF failed");
         free(buf);
         return ifs;
     }
 
-    /*
-     * Iterate through each interface
-     */
+    // Iterate through each interface
     ifreqP = ifc.ifc_req;
     cp = (char *)ifc.ifc_req;
     cplimit = cp + ifc.ifc_len;
 
-    for ( ; cp < cplimit; cp += (sizeof(ifreqP->ifr_name) + MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr)))) {
+    for (; cp < cplimit;
+        cp += (sizeof(ifreqP->ifr_name) +
+               MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
+    {
         ifreqP = (struct ifreq *)cp;
         struct ifreq if2;
+        memset((char *)&if2, 0, sizeof(if2));
+        strncpy(if2.ifr_name, ifreqP->ifr_name, sizeof(if2.ifr_name) - 1);
 
-        memset((char *)&if2, 0, sizeof(if2));
-        strcpy(if2.ifr_name, ifreqP->ifr_name);
-
-        /*
-         * Skip interface that aren't UP
-         */
+        // Skip interface that aren't UP
         if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
             if (!(if2.ifr_flags & IFF_UP)) {
                 continue;
@@ -1308,16 +1278,11 @@
             s6->sin6_scope_id = if2.ifr_site6;
         }
 
-        /*
-         * Add to the list
-         */
+        // Add to the list
         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->ifr_addr),
-                    AF_INET6, 0);
+                    (struct sockaddr *)&(ifreqP->ifr_addr), AF_INET6, 0);
 
-        /*
-         * If an exception occurred then free the list
-         */
+        // If an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             freeif(ifs);
@@ -1325,24 +1290,21 @@
         }
     }
 
-    /*
-     * Free socket and buffer
-     */
+    // Free socket and buffer
     free(buf);
     return ifs;
 }
 #endif
 
 
-static int getIndex(int sock, const char *name){
-     /*
-      * Try to get the interface index
-      */
+static int getIndex(int sock, const char *name) {
+     // Try to get the interface index
 #if defined(_AIX)
     return if_nametoindex(name);
 #else
     struct ifreq if2;
-    strcpy(if2.ifr_name, name);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
         return -1;
@@ -1352,38 +1314,41 @@
 #endif
 }
 
-/**
+/*
  * Returns the IPv4 broadcast address of a named interface, if it exists.
  * Returns 0 if it doesn't have one.
  */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
-  struct sockaddr *ret = NULL;
-  struct ifreq if2;
+static struct sockaddr *getBroadcast
+  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
+{
+    struct sockaddr *ret = NULL;
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
-  memset((char *) &if2, 0, sizeof(if2));
-  strcpy(if2.ifr_name, ifname);
+    // Let's make sure the interface does have a broadcast address.
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFFLAGS failed");
+        return ret;
+    }
 
-  /* Let's make sure the interface does have a broadcast address */
-  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
-      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGIFFLAGS failed");
-      return ret;
-  }
+    if (if2.ifr_flags & IFF_BROADCAST) {
+        // It does, let's retrieve it
+        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "ioctl SIOCGIFBRDADDR failed");
+            return ret;
+        }
 
-  if (if2.ifr_flags & IFF_BROADCAST) {
-      /* It does, let's retrieve it*/
-      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
-          return ret;
-      }
+        ret = brdcast_store;
+        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
+    }
 
-      ret = brdcast_store;
-      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-  }
-
-  return ret;
+    return ret;
 }
 
-/**
+/*
  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
  * interface, if it has one, otherwise return -1.
  */
@@ -1391,12 +1356,12 @@
     unsigned int mask;
     short ret;
     struct ifreq if2;
-
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.ifr_name, ifname);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFNETMASK failed");
         return -1;
     }
 
@@ -1410,12 +1375,15 @@
     return ret;
 }
 
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
+/*
+ * Gets the Hardware address (usually MAC address) for the named interface.
+ * On return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
+static int getMacAddress
+  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+   unsigned char *buf)
+{
 #if defined (_AIX)
     int size;
     struct kinfo_ndd *nddp;
@@ -1434,7 +1402,8 @@
     nddp = (struct kinfo_ndd *)malloc(size);
 
     if (!nddp) {
-        JNU_ThrowOutOfMemoryError(env, "Network interface getMacAddress native buffer allocation failed");
+        JNU_ThrowOutOfMemoryError(env,
+            "Network interface getMacAddress native buffer allocation failed");
         return -1;
     }
 
@@ -1455,22 +1424,20 @@
     }
 
     return -1;
-
 #elif defined(__linux__)
     static struct ifreq ifr;
     int i;
-
-    strcpy(ifr.ifr_name, ifname);
+    memset((char *)&ifr, 0, sizeof(ifr));
+    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
     if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFHWADDR failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFHWADDR failed");
         return -1;
     }
 
     memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
 
-   /*
-    * All bytes to 0 means no hardware address.
-    */
+    // All bytes to 0 means no hardware address.
 
     for (i = 0; i < IFHWADDRLEN; i++) {
         if (buf[i] != 0)
@@ -1483,17 +1450,18 @@
 
 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
     struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
 
-    memset((char *) &if2, 0, sizeof(if2));
     if (ifname != NULL) {
-        strcpy(if2.ifr_name, ifname);
+        strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
     } else {
         JNU_ThrowNullPointerException(env, "network interface name is NULL");
         return -1;
     }
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "IOCTL SIOCGIFMTU failed");
         return -1;
     }
 
@@ -1502,11 +1470,10 @@
 
 static int getFlags(int sock, const char *ifname, int *flags) {
   struct ifreq if2;
+  memset((char *)&if2, 0, sizeof(if2));
+  strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
-  memset((char *) &if2, 0, sizeof(if2));
-  strcpy(if2.ifr_name, ifname);
-
-  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
+  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
       return -1;
   }
 
@@ -1518,53 +1485,54 @@
   return 0;
 }
 
-#endif
+#endif  /* defined(__linux__) || defined(_AIX) */
 
 /** Solaris **/
-#ifdef __solaris__
-/* Open socket for further ioct calls, try v4 socket first and
- * if it falls return v6 socket
+#if defined(__solaris__)
+
+/*
+ * Opens a socket for further ioct calls. Tries AF_INET socket first and
+ * if it falls return AF_INET6 socket.
  */
-
 #ifdef AF_INET6
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock, alreadyV6 = 0;
     struct lifreq if2;
 
-     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-         if (errno == EPROTONOSUPPORT){
-              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
-                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                 return -1;
-              }
+    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                             "IPV6 Socket creation failed");
+                return -1;
+            }
 
-              alreadyV6=1;
-         }
-         else{ // errno is not NOSUPPORT
-             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-             return -1;
-         }
-   }
+            alreadyV6=1;
+        } else { // errno is not NOSUPPORT
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
 
-     /**
-      * Solaris requires that we have an IPv6 socket to query an
-      * interface without an IPv4 address - check it here.
-      * POSIX 1 require the kernel to return ENOTTY if the call is
-      * inappropriate for a device e.g. the NETMASK for a device having IPv6
-      * only address but not all devices follow the standard so
-      * fall back on any error. It's not an ecologically friendly gesture
-      * but more reliable.
-      */
 
-    if (! alreadyV6 ){
-        memset((char *) &if2, 0, sizeof(if2));
-        strcpy(if2.lifr_name, ifname);
+    // Solaris requires that we have an IPv6 socket to query an  interface
+    // without an IPv4 address - check it here. POSIX 1 require the kernel to
+    // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
+    // for a device having IPv6 only address but not all devices follow the
+    // standard so fall back on any error. It's not an ecologically friendly
+    // gesture but more reliable.
+
+    if (!alreadyV6) {
+        memset((char *)&if2, 0, sizeof(if2));
+        strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
         if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
-                close(sock);
-                if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
-                      NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                      return -1;
-                }
+            close(sock);
+            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                             "IPV6 Socket creation failed");
+                return -1;
+            }
         }
     }
 
@@ -1572,18 +1540,16 @@
 }
 
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     return openSocket(env,AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces
- * (linux verision)
+ * Enumerates and returns all IPv4 interfaces.
  */
-
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
-     return enumIPvXInterfaces(env,sock, ifs, AF_INET);
+    return enumIPvXInterfaces(env,sock, ifs, AF_INET);
 }
 
 #ifdef AF_INET6
@@ -1593,8 +1559,8 @@
 #endif
 
 /*
-   Enumerates and returns all interfaces on Solaris
-   use the same code for IPv4 and IPv6
+ * Enumerates and returns all interfaces on Solaris.
+ * Uses the same code for IPv4 and IPv6.
  */
 static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
     struct lifconf ifc;
@@ -1604,19 +1570,16 @@
     struct lifnum numifs;
     unsigned bufsize;
 
-    /*
-     * Get the interface count
-     */
+    // Get the interface count
     numifs.lifn_family = family;
     numifs.lifn_flags = 0;
     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFNUM failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGLIFNUM failed");
         return ifs;
     }
 
-    /*
-     *  Enumerate the interface configurations
-     */
+    //  Enumerate the interface configurations
     bufsize = numifs.lifn_count * sizeof (struct lifreq);
     CHECKED_MALLOC3(buf, char *, bufsize);
 
@@ -1625,22 +1588,19 @@
     ifc.lifc_len = bufsize;
     ifc.lifc_buf = buf;
     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFCONF failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGLIFCONF failed");
         free(buf);
         return ifs;
     }
 
-    /*
-     * Iterate through each interface
-     */
+    // Iterate through each interface
     ifr = ifc.lifc_req;
     for (n=0; n<numifs.lifn_count; n++, ifr++) {
         int index = -1;
         struct lifreq if2;
 
-        /*
-        * Ignore either IPv4 or IPv6 addresses
-        */
+        // Ignore either IPv4 or IPv6 addresses
         if (ifr->lifr_addr.ss_family != family) {
             continue;
         }
@@ -1652,12 +1612,12 @@
         }
 #endif
 
-        /* add to the list */
-        ifs = addif(env, sock,ifr->lifr_name, ifs, (struct sockaddr *)&(ifr->lifr_addr),family, (short) ifr->lifr_addrlen);
+        // add to the list
+        ifs = addif(env, sock,ifr->lifr_name, ifs,
+                    (struct sockaddr *)&(ifr->lifr_addr), family,
+                    (short)ifr->lifr_addrlen);
 
-        /*
-        * If an exception occurred we return immediately
-        */
+        // If an exception occurred we return immediately
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             return ifs;
@@ -1669,13 +1629,11 @@
     return ifs;
 }
 
-static int getIndex(int sock, const char *name){
-   /*
-    * Try to get the interface index
-    * (Not supported on Solaris 2.6 or 7)
-    */
+static int getIndex(int sock, const char *name) {
+    // Try to get the interface index.  (Not supported on Solaris 2.6 or 7)
     struct lifreq if2;
-    strcpy(if2.lifr_name, name);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
 
     if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
         return -1;
@@ -1684,27 +1642,30 @@
     return if2.lifr_index;
 }
 
-/**
+/*
  * Returns the IPv4 broadcast address of a named interface, if it exists.
  * Returns 0 if it doesn't have one.
  */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
+static struct sockaddr *getBroadcast
+  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
+{
     struct sockaddr *ret = NULL;
     struct lifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.lifr_name, ifname);
-
-    /* Let's make sure the interface does have a broadcast address */
+    // Let's make sure the interface does have a broadcast address
     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGLIFFLAGS failed");
         return ret;
     }
 
     if (if2.lifr_flags & IFF_BROADCAST) {
-        /* It does, let's retrieve it*/
+        // It does, let's retrieve it
         if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFBRDADDR failed");
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "ioctl SIOCGLIFBRDADDR failed");
             return ret;
         }
 
@@ -1715,7 +1676,7 @@
     return ret;
 }
 
-/**
+/*
  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
  * interface, if it has one, otherwise return -1.
  */
@@ -1723,12 +1684,12 @@
     unsigned int mask;
     short ret;
     struct lifreq if2;
-
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.lifr_name, ifname);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
     if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFNETMASK failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGLIFNETMASK failed");
         return -1;
     }
 
@@ -1744,15 +1705,16 @@
 }
 
 
-
 #define DEV_PREFIX  "/dev/"
 
-/**
+/*
  * Solaris specific DLPI code to get hardware address from a device.
  * Unfortunately, at least up to Solaris X, you have to have special
  * privileges (i.e. be root).
  */
-static int getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf) {
+static int getMacFromDevice
+  (JNIEnv *env, const char* ifname, unsigned char* retbuf)
+{
     char style1dev[MAXPATHLEN];
     int fd;
     dl_phys_addr_req_t dlpareq;
@@ -1761,17 +1723,12 @@
     char buf[128];
     int flags = 0;
 
-   /**
-    * Device is in /dev
-    * e.g.: /dev/bge0
-    */
+    // Device is in /dev.  e.g.: /dev/bge0
     strcpy(style1dev, DEV_PREFIX);
     strcat(style1dev, ifname);
     if ((fd = open(style1dev, O_RDWR)) < 0) {
-        /*
-         * Can't open it. We probably are missing the privilege.
-         * We'll have to try something else
-         */
+         // Can't open it. We probably are missing the privilege.
+         // We'll have to try something else
          return 0;
     }
 
@@ -1782,7 +1739,8 @@
     msg.len = DL_PHYS_ADDR_REQ_SIZE;
 
     if (putmsg(fd, &msg, NULL, 0) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "putmsg failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "putmsg failed");
         return -1;
     }
 
@@ -1792,12 +1750,14 @@
     msg.len = 0;
     msg.maxlen = sizeof (buf);
     if (getmsg(fd, &msg, NULL, &flags) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "getmsg failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "getmsg failed");
         return -1;
     }
 
     if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Couldn't obtain phys addr\n");
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
+                        "Couldn't obtain phys addr\n");
         return -1;
     }
 
@@ -1805,21 +1765,23 @@
     return dlpaack->dl_addr_length;
 }
 
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
+/*
+ * Gets the Hardware address (usually MAC address) for the named interface.
+ * On return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress(JNIEnv *env, int sock, const char *ifname,  const struct in_addr* addr, unsigned char *buf) {
+static int getMacAddress
+  (JNIEnv *env, int sock, const char *ifname, const struct in_addr* addr,
+   unsigned char *buf)
+{
     struct arpreq arpreq;
     struct sockaddr_in* sin;
     struct sockaddr_in ipAddr;
     int len, i;
     struct lifreq lif;
 
-    /* First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
-     * try the old way.
-     */
+    // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
+    // try the old way.
     memset(&lif, 0, sizeof(lif));
     strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
 
@@ -1830,18 +1792,14 @@
         return sp->sdl_alen;
     }
 
-   /**
-    * On Solaris we have to use DLPI, but it will only work if we have
-    * privileged access (i.e. root). If that fails, we try a lookup
-    * in the ARP table, which requires an IPv4 address.
-    */
+    // On Solaris we have to use DLPI, but it will only work if we have
+    // privileged access (i.e. root). If that fails, we try a lookup
+    // in the ARP table, which requires an IPv4 address.
     if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
-        /*DLPI failed - trying to do arp lookup*/
+        // DLPI failed - trying to do arp lookup
 
         if (addr == NULL) {
-            /**
-             * No IPv4 address for that interface, so can't do an ARP lookup.
-             */
+             // No IPv4 address for that interface, so can't do an ARP lookup.
              return -1;
          }
 
@@ -1862,10 +1820,7 @@
          memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
     }
 
-    /*
-     * All bytes to 0 means no hardware address.
-     */
-
+    // All bytes to 0 means no hardware address.
     for (i = 0; i < len; i++) {
       if (buf[i] != 0)
          return len;
@@ -1876,56 +1831,57 @@
 
 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
     struct lifreq if2;
-
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.lifr_name, ifname);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
     if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFMTU failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                    "ioctl SIOCGLIFMTU failed");
         return -1;
     }
 
-    return  if2.lifr_mtu;
+    return if2.lifr_mtu;
 }
 
+static int getFlags(int sock, const char *ifname, int *flags) {
+    struct lifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
-static int getFlags(int sock, const char *ifname, int *flags) {
-     struct   lifreq lifr;
-     memset((caddr_t)&lifr, 0, sizeof(lifr));
-     strcpy((caddr_t)&(lifr.lifr_name), ifname);
+    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
+        return -1;
+    }
 
-     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) {
-         return -1;
-     }
-
-     *flags = lifr.lifr_flags;
-     return 0;
+    *flags = if2.lifr_flags;
+    return 0;
 }
 
 
-#endif
+#endif  /* __solaris__ */
 
 
 /** BSD **/
 #ifdef _ALLBSD_SOURCE
-/* Open socket for further ioct calls, try v4 socket first and
- * if it falls return v6 socket
+
+/*
+ * Opens a socket for further ioct calls. Tries AF_INET socket first and
+ * if it falls return AF_INET6 socket.
  */
-
 #ifdef AF_INET6
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
     struct ifreq if2;
 
      if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-         if (errno == EPROTONOSUPPORT){
-              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
-                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+         if (errno == EPROTONOSUPPORT) {
+              if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                 NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                              "IPV6 Socket creation failed");
                  return -1;
               }
-         }
-         else{ // errno is not NOSUPPORT
-             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+         } else { // errno is not NOSUPPORT
+             NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                          "IPV4 Socket creation failed");
              return -1;
          }
    }
@@ -1934,39 +1890,33 @@
 }
 
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     return openSocket(env,AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces
+ * Enumerates and returns all IPv4 interfaces.
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
-                         "getifaddrs() function failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "getifaddrs() function failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
 
-        /*
-         * Skip non-AF_INET entries.
-         */
+        // Skip non-AF_INET entries.
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
             continue;
 
-        /*
-         * Add to the list.
-         */
+        // Add to the list.
         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET, 0);
 
-        /*
-         * If an exception occurred then free the list.
-         */
+        // If an exception occurred then free the list.
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -1974,33 +1924,25 @@
         }
     }
 
-    /*
-     * Free socket and buffer
-     */
+    // Free socket and buffer
     freeifaddrs(origifa);
     return ifs;
 }
 
-
-/*
- * Enumerates and returns all IPv6 interfaces on Linux
- */
-
 #ifdef AF_INET6
 /*
  * Determines the prefix on BSD for IPv6 interfaces.
  */
-static
-int prefix(void *val, int size) {
+static int prefix(void *val, int size) {
     u_char *name = (u_char *)val;
-    int byte, bit, plen = 0;
+    int byte, bit, prefix = 0;
 
-    for (byte = 0; byte < size; byte++, plen += 8)
+    for (byte = 0; byte < size; byte++, prefix += 8)
         if (name[byte] != 0xff)
             break;
     if (byte == size)
-        return (plen);
-    for (bit = 7; bit != 0; bit--, plen++)
+        return prefix;
+    for (bit = 7; bit != 0; bit--, prefix++)
         if (!(name[byte] & (1 << bit)))
             break;
     for (; bit != 0; bit--)
@@ -2010,11 +1952,11 @@
     for (; byte < size; byte++)
         if (name[byte])
             return (0);
-    return (plen);
+    return prefix;
 }
 
 /*
- * Enumerates and returns all IPv6 interfaces on BSD
+ * Enumerates and returns all IPv6 interfaces on BSD.
  */
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
@@ -2022,37 +1964,36 @@
     struct in6_ifreq ifr6;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
-                         "getifaddrs() function failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "getifaddrs() function failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
 
-        /*
-         * Skip non-AF_INET6 entries.
-         */
+        // Skip non-AF_INET6 entries.
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
             continue;
 
         memset(&ifr6, 0, sizeof(ifr6));
         strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
-        memcpy(&ifr6.ifr_addr, ifa->ifa_addr, MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
+        memcpy(&ifr6.ifr_addr, ifa->ifa_addr,
+               MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
 
         if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
-            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
-                             "ioctl SIOCGIFNETMASK_IN6 failed");
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "ioctl SIOCGIFNETMASK_IN6 failed");
             freeifaddrs(origifa);
             freeif(ifs);
             return NULL;
         }
 
-        /* Add to the list.  */
+        // Add to the list.
         sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET6,
-                    prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
+            (short)prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
 
-        /* If an exception occurred then free the list.  */
+        // If an exception occurred then free the list.
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -2060,22 +2001,19 @@
         }
     }
 
-    /*
-     * Free socket and ifaddrs buffer
-     */
+    // Free socket and ifaddrs buffer
     freeifaddrs(origifa);
     return ifs;
 }
 #endif
 
-static int getIndex(int sock, const char *name){
+static int getIndex(int sock, const char *name) {
 #ifdef __FreeBSD__
-     /*
-      * Try to get the interface index
-      * (Not supported on Solaris 2.6 or 7)
-      */
+    // Try to get the interface index
+    // (Not supported on Solaris 2.6 or 7)
     struct ifreq if2;
-    strcpy(if2.ifr_name, name);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
         return -1;
@@ -2083,46 +2021,47 @@
 
     return if2.ifr_index;
 #else
-    /*
-     * Try to get the interface index using BSD specific if_nametoindex
-     */
+    // Try to get the interface index using BSD specific if_nametoindex
     int index = if_nametoindex(name);
     return (index == 0) ? -1 : index;
 #endif
 }
 
-/**
+/*
  * Returns the IPv4 broadcast address of a named interface, if it exists.
  * Returns 0 if it doesn't have one.
  */
-static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
-  struct sockaddr *ret = NULL;
-  struct ifreq if2;
+static struct sockaddr *getBroadcast
+  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
+{
+    struct sockaddr *ret = NULL;
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
-  memset((char *) &if2, 0, sizeof(if2));
-  strcpy(if2.ifr_name, ifname);
+    // Make sure the interface does have a broadcast address
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFFLAGS failed");
+        return ret;
+    }
 
-  /* Let's make sure the interface does have a broadcast address */
-  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFFLAGS failed");
-      return ret;
-  }
+    if (if2.ifr_flags & IFF_BROADCAST) {
+        // It does, let's retrieve it
+        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                         "ioctl SIOCGIFBRDADDR failed");
+            return ret;
+        }
 
-  if (if2.ifr_flags & IFF_BROADCAST) {
-      /* It does, let's retrieve it*/
-      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
-          return ret;
-      }
+        ret = brdcast_store;
+        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
+    }
 
-      ret = brdcast_store;
-      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-  }
-
-  return ret;
+    return ret;
 }
 
-/**
+/*
  * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
  * interface, if it has one, otherwise return -1.
  */
@@ -2130,12 +2069,12 @@
     unsigned int mask;
     short ret;
     struct ifreq if2;
-
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.ifr_name, ifname);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFNETMASK failed");
         return -1;
     }
 
@@ -2149,25 +2088,28 @@
     return ret;
 }
 
-/**
- * Get the Hardware address (usually MAC address) for the named interface.
+/*
+ * Gets the Hardware address (usually MAC address) for the named interface.
  * return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
+static int getMacAddress
+  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+   unsigned char *buf)
+{
     struct ifaddrs *ifa0, *ifa;
     struct sockaddr *saddr;
     int i;
 
-    /* Grab the interface list */
+    // Grab the interface list
     if (!getifaddrs(&ifa0)) {
-        /* Cycle through the interfaces */
+        // Cycle through the interfaces
         for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
             saddr = ifa->ifa_addr;
-            /* Link layer contains the MAC address */
+            // Link layer contains the MAC address
             if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
                 struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
-                /* Check the address is the correct length */
+                // Check the address is the correct length
                 if (sadl->sdl_alen == ETHER_ADDR_LEN) {
                     memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
                     freeifaddrs(ifa0);
@@ -2183,12 +2125,12 @@
 
 static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
     struct ifreq if2;
-
-    memset((char *) &if2, 0, sizeof(if2));
-    strcpy(if2.ifr_name, ifname);
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
+                                     "ioctl SIOCGIFMTU failed");
         return -1;
     }
 
@@ -2196,22 +2138,20 @@
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
-  struct ifreq if2;
-  int ret = -1;
+    struct ifreq if2;
+    int ret = -1;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
-  memset((char *) &if2, 0, sizeof(if2));
-  strcpy(if2.ifr_name, ifname);
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+        return -1;
+    }
 
-  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
-      return -1;
-  }
-
-  if (sizeof(if2.ifr_flags) == sizeof(short)) {
-    *flags = (if2.ifr_flags & 0xffff);
-  } else {
-    *flags = if2.ifr_flags;
-  }
-  return 0;
+    if (sizeof(if2.ifr_flags) == sizeof(short)) {
+        *flags = (if2.ifr_flags & 0xffff);
+    } else {
+        *flags = if2.ifr_flags;
+    }
+    return 0;
 }
-
-#endif
+#endif /* __ALLBSD_SOURCE__ */
--- a/src/solaris/native/java/net/PlainDatagramSocketImpl.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/native/java/net/PlainDatagramSocketImpl.c	Mon Aug 08 15:29:16 2016 -0700
@@ -992,17 +992,24 @@
                        (char *)&arg, sizeof(arg)) < 0) {
         getErrorString(errno, tmpbuf, sizeof(tmpbuf));
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
+        close(fd);
         return;
     }
     if (JVM_SetSockOpt(fd, SOL_SOCKET, SO_RCVBUF,
                        (char *)&arg, sizeof(arg)) < 0) {
         getErrorString(errno, tmpbuf, sizeof(tmpbuf));
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
+        close(fd);
         return;
     }
 #endif /* __APPLE__ */
 
-     setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char*) &t, sizeof(int));
+    if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char*) &t, sizeof (int)) < 0) {
+        getErrorString(errno, tmpbuf, sizeof(tmpbuf));
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
+        close(fd);
+        return;
+    }
 
 #if defined(__linux__)
     arg = 0;
@@ -1024,8 +1031,13 @@
      */
     if (domain == AF_INET6) {
         int ttl = 1;
-        setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&ttl,
-                   sizeof(ttl));
+        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *) &ttl,
+                sizeof (ttl)) < 0) {
+            getErrorString(errno, tmpbuf, sizeof(tmpbuf));
+            JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
+            close(fd);
+            return;
+        }
     }
 #endif /* __linux__ */
 
@@ -2182,7 +2194,7 @@
             caddr[14] = ((address >> 8) & 0xff);
             caddr[15] = (address & 0xff);
         } else {
-            getInet6Address_ipaddress(env, iaObj, caddr);
+            getInet6Address_ipaddress(env, iaObj, (char *) caddr);
         }
 
         memcpy((void *)&(mname6.ipv6mr_multiaddr), caddr, sizeof(struct in6_addr));
--- a/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -94,6 +94,7 @@
                     return 0;
                 }
                 start = now;
+                a.dp_timeout = remaining;
             }
         } else {
             return res;
--- a/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -53,7 +53,7 @@
     start = t.tv_sec * 1000 + t.tv_usec / 1000;
 
     for (;;) {
-        int res = epoll_wait(epfd, events, numfds, timeout);
+        int res = epoll_wait(epfd, events, numfds, remaining);
         if (res < 0 && errno == EINTR) {
             if (remaining >= 0) {
                 gettimeofday(&t, NULL);
--- a/src/windows/bin/cmdtoargs.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/bin/cmdtoargs.c	Mon Aug 08 15:29:16 2016 -0700
@@ -155,6 +155,7 @@
                 }
             }
             dest += copyCh(ch, dest);
+            slashes = 0;
             break;
 
         default:
--- a/src/windows/classes/sun/awt/windows/fontconfig.properties	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/classes/sun/awt/windows/fontconfig.properties	Mon Aug 08 15:29:16 2016 -0700
@@ -40,6 +40,7 @@
 allfonts.dingbats=Wingdings
 allfonts.lucida=Lucida Sans Regular
 allfonts.symbol=Symbol
+allfonts.symbols=Segoe UI Symbol
 allfonts.thai=Lucida Sans Regular
 allfonts.georgian=Sylfaen
 
@@ -236,7 +237,7 @@
 
 sequence.allfonts.x-windows-874=alphabetic,thai,dingbats,symbol
 
-sequence.fallback=lucida,\
+sequence.fallback=lucida,symbols,\
                   chinese-ms950,chinese-hkscs,chinese-ms936,chinese-gb18030,\
                   japanese,korean,chinese-ms950-extb,chinese-ms936-extb,georgian
 
@@ -298,3 +299,4 @@
 filename.Wingdings=WINGDING.TTF
 
 filename.Sylfaen=sylfaen.ttf
+filename.Segoe_UI_Symbol=SEGUISYM.TTF
--- a/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java	Mon Aug 08 15:29:16 2016 -0700
@@ -26,6 +26,7 @@
 package sun.java2d.d3d;
 
 import java.awt.Composite;
+import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.GraphicsPrimitive;
 import sun.java2d.loops.GraphicsPrimitiveMgr;
@@ -67,7 +68,13 @@
     protected void validateContext(SunGraphics2D sg2d,
                                    Composite comp, int ctxflags)
     {
-        D3DSurfaceData dstData = (D3DSurfaceData)sg2d.surfaceData;
+        D3DSurfaceData dstData;
+        try {
+            dstData = (D3DSurfaceData) sg2d.surfaceData;
+        } catch (ClassCastException e) {
+            throw new InvalidPipeException("wrong surface data type: " +
+                                           sg2d.surfaceData);
+        }
         D3DContext.validateContext(dstData, dstData,
                                    sg2d.getCompClip(), comp,
                                    null, sg2d.paint, sg2d, ctxflags);
--- a/src/windows/native/java/lang/ProcessEnvironment_md.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/java/lang/ProcessEnvironment_md.c	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
--- a/src/windows/native/java/net/Inet4AddressImpl.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/java/net/Inet4AddressImpl.c	Mon Aug 08 15:29:16 2016 -0700
@@ -292,7 +292,6 @@
 }
 
 
-
 static BOOL
 WindowsVersionCheck(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor) {
     OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
@@ -316,7 +315,7 @@
 }
 
 static jboolean
-wxp_ping4(JNIEnv *env,
+tcp_ping4(JNIEnv *env,
           jbyteArray addrArray,
           jint timeout,
           jbyteArray ifArray,
@@ -471,23 +470,17 @@
 ping4(JNIEnv *env,
       unsigned long src_addr,
       unsigned long dest_addr,
-      jint timeout)
+      jint timeout,
+      HANDLE hIcmpFile)
 {
     // See https://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx
 
-    HANDLE hIcmpFile;
     DWORD dwRetVal = 0;
     char SendData[32] = {0};
     LPVOID ReplyBuffer = NULL;
     DWORD ReplySize = 0;
     jboolean ret = JNI_FALSE;
 
-    hIcmpFile = IcmpCreateFile();
-    if (hIcmpFile == INVALID_HANDLE_VALUE) {
-        NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle");
-        return JNI_FALSE;
-    }
-
     ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
     ReplyBuffer = (VOID*) malloc(ReplySize);
     if (ReplyBuffer == NULL) {
@@ -553,6 +546,7 @@
         jint dest_addr = 0;
         jbyte caddr[4];
         int sz;
+        HANDLE hIcmpFile;
 
         /**
          * Convert IP address from byte array to integer
@@ -583,8 +577,20 @@
             src_addr = htonl(src_addr);
         }
 
-        return ping4(env, src_addr, dest_addr, timeout);
+        hIcmpFile = IcmpCreateFile();
+        if (hIcmpFile == INVALID_HANDLE_VALUE) {
+            int err = WSAGetLastError();
+            if (err == ERROR_ACCESS_DENIED) {
+                // fall back to TCP echo if access is denied to ICMP
+                return tcp_ping4(env, addrArray, timeout, ifArray, ttl);
+            } else {
+                NET_ThrowNew(env, err, "Unable to create ICMP file handle");
+                return JNI_FALSE;
+            }
+        } else {
+            return ping4(env, src_addr, dest_addr, timeout, hIcmpFile);
+        }
     } else {
-        wxp_ping4(env, addrArray, timeout, ifArray, ttl);
+        tcp_ping4(env, addrArray, timeout, ifArray, ttl);
     }
 }
--- a/src/windows/native/java/net/Inet6AddressImpl.c	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/java/net/Inet6AddressImpl.c	Mon Aug 08 15:29:16 2016 -0700
@@ -360,6 +360,109 @@
 
 #ifdef AF_INET6
 
+/**
+ * ping implementation using tcp port 7 (echo)
+ */
+static jboolean
+tcp_ping6(JNIEnv *env,
+          jint timeout,
+          jint ttl,
+          struct sockaddr_in6 him6,
+          struct sockaddr_in6* netif,
+          int len)
+{
+    jint fd;
+    WSAEVENT hEvent;
+    int connect_rv = -1;
+
+    fd = NET_Socket(AF_INET6, SOCK_STREAM, 0);
+    if (fd == SOCKET_ERROR) {
+        /* note: if you run out of fds, you may not be able to load
+         * the exception class, and get a NoClassDefFoundError
+         * instead.
+         */
+        NET_ThrowNew(env, errno, "Can't create socket");
+        return JNI_FALSE;
+    }
+
+    /**
+     * A TTL was specified, let's set the socket option.
+     */
+    if (ttl > 0) {
+      setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char *)&ttl, sizeof(ttl));
+    }
+
+    /**
+     * A network interface was specified, let's bind to it.
+     */
+    if (netif != NULL) {
+      if (NET_Bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) < 0) {
+        NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket to interface");
+        closesocket(fd);
+        return JNI_FALSE;
+      }
+    }
+
+    /**
+     * Make the socket non blocking.
+     */
+    hEvent = WSACreateEvent();
+    WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);
+
+    /* no need to use NET_Connect as non-blocking */
+    him6.sin6_port = htons((short) 7); /* Echo port */
+    connect_rv = connect(fd, (struct sockaddr *)&him6, len);
+
+    /**
+     * connection established or refused immediately, either way it means
+     * we were able to reach the host!
+     */
+    if (connect_rv == 0 || WSAGetLastError() == WSAECONNREFUSED) {
+        WSACloseEvent(hEvent);
+        closesocket(fd);
+        return JNI_TRUE;
+    } else {
+        int optlen;
+
+        switch (WSAGetLastError()) {
+        case WSAEHOSTUNREACH:   /* Host Unreachable */
+        case WSAENETUNREACH:    /* Network Unreachable */
+        case WSAENETDOWN:       /* Network is down */
+        case WSAEPFNOSUPPORT:   /* Protocol Family unsupported */
+          WSACloseEvent(hEvent);
+          closesocket(fd);
+          return JNI_FALSE;
+        }
+
+        if (WSAGetLastError() != WSAEWOULDBLOCK) {
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
+                                         "connect failed");
+            WSACloseEvent(hEvent);
+            closesocket(fd);
+            return JNI_FALSE;
+        }
+
+        timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+
+        if (timeout >= 0) {
+          /* has connection been established? */
+          optlen = sizeof(connect_rv);
+          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
+                         &optlen) <0) {
+            connect_rv = WSAGetLastError();
+          }
+
+          if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
+            WSACloseEvent(hEvent);
+            closesocket(fd);
+            return JNI_TRUE;
+          }
+        }
+    }
+    WSACloseEvent(hEvent);
+    closesocket(fd);
+    return JNI_FALSE;
+}
 
 /**
  * ping implementation.
@@ -371,9 +474,9 @@
 ping6(JNIEnv *env,
       struct sockaddr_in6* src,
       struct sockaddr_in6* dest,
-      jint timeout)
+      jint timeout,
+      HANDLE hIcmpFile)
 {
-    HANDLE hIcmpFile;
     DWORD dwRetVal = 0;
     char SendData[32] = {0};
     LPVOID ReplyBuffer = NULL;
@@ -381,12 +484,6 @@
     IP_OPTION_INFORMATION ipInfo = {255, 0, 0, 0, NULL};
     struct sockaddr_in6 sa6Source;
 
-    hIcmpFile = Icmp6CreateFile();
-    if (hIcmpFile == INVALID_HANDLE_VALUE) {
-        NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle");
-        return JNI_FALSE;
-    }
-
     ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData);
     ReplyBuffer = (VOID*) malloc(ReplySize);
     if (ReplyBuffer == NULL) {
@@ -445,7 +542,7 @@
     struct sockaddr_in6* netif = NULL;
     struct sockaddr_in6 inf6;
     int len = 0;
-    int connect_rv = -1;
+    HANDLE hIcmpFile;
 
     /*
      * If IPv6 is not enable, then we can't reach an IPv6 address, can we?
@@ -489,7 +586,21 @@
       inf6.sin6_scope_id = if_scope;
       netif = &inf6;
     }
-    return ping6(env, netif, &him6, timeout);
+
+    hIcmpFile = Icmp6CreateFile();
+    if (hIcmpFile == INVALID_HANDLE_VALUE) {
+        int err = WSAGetLastError();
+        if (err == ERROR_ACCESS_DENIED) {
+            // fall back to TCP echo if access is denied to ICMP
+            return tcp_ping6(env, timeout, ttl, him6, netif, len);
+        } else {
+            NET_ThrowNew(env, err, "Unable to create ICMP file handle");
+            return JNI_FALSE;
+        }
+    } else {
+        return ping6(env, netif, &him6, timeout, hIcmpFile);
+    }
+
 #endif /* AF_INET6 */
     return JNI_FALSE;
 }
--- a/src/windows/native/sun/bridge/WinAccessBridge.cpp	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/sun/bridge/WinAccessBridge.cpp	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1125,7 +1125,7 @@
 
     PrintDebugString("WinAccessBridge::getAccessibleContextWithFocus(%p, %X, )", window, vmID);
     // find vmID, etc. from HWND; ask that VM for the AC w/Focus
-        HWND pkgVMID = (HWND)ABLongToHandle( pkg->rVMID ) ;
+    HWND pkgVMID;
     if (getAccessibleContextFromHWND(window, (long *)&(pkgVMID), &(pkg->rAccessibleContext)) == TRUE) {
         HWND destABWindow = javaVMs->findAccessBridgeWindow((long)pkgVMID);     // ineffecient [[[FIXME]]]
         if (sendMemoryPackage(buffer, sizeof(buffer), destABWindow) == TRUE) {
--- a/src/windows/native/sun/windows/awt_TrayIcon.cpp	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/sun/windows/awt_TrayIcon.cpp	Mon Aug 08 15:29:16 2016 -0700
@@ -93,6 +93,12 @@
 
 void AwtTrayIcon::Dispose() {
     SendTrayMessage(NIM_DELETE);
+
+    // Destroy the icon to avoid leak of GDI objects
+    if (m_nid.hIcon != NULL) {
+        ::DestroyIcon(m_nid.hIcon);
+    }
+
     UnlinkObjects();
 
     if (--sm_instCount == 0) {
--- a/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp	Thu Aug 04 18:37:15 2016 +0300
+++ b/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp	Mon Aug 08 15:29:16 2016 -0700
@@ -875,6 +875,9 @@
     // Only want to call this once per session
     make_uns_ordered_dither_array(img_oda_alpha, 256);
 
+    // workaround JDK-6477756, ignore return value to keep dll in memory
+    JDK_LoadSystemLibrary("opengl32.dll");
+
     CATCH_BAD_ALLOC;
 }
 
--- a/test/ProblemList.txt	Thu Aug 04 18:37:15 2016 +0300
+++ b/test/ProblemList.txt	Mon Aug 08 15:29:16 2016 -0700
@@ -234,6 +234,12 @@
 java/security/KeyPairGenerator/SolarisShortDSA.java             solaris-all
 sun/security/tools/keytool/standard.sh                          solaris-all
 
+# 8026393
+sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java      generic-all
+
+# 8158827
+sun/security/krb5/auto/tools/KinitConfPlusProps.java                       windows-all
+
 ############################################################################
 
 # jdk_sound
--- a/test/com/sun/corba/cachedSocket/7056731.sh	Thu Aug 04 18:37:15 2016 +0300
+++ b/test/com/sun/corba/cachedSocket/7056731.sh	Mon Aug 08 15:29:16 2016 -0700
@@ -102,7 +102,7 @@
 sleep 5 # give time for Client to throw exception
 
 # JVM_PROC should have exited but just in case, include it.
-kill -9 $ORB_PROC $JVM_PROC
+kill -9 $ORB_PROC $JVM_PROC $SERVER_PROC
 
 grep "ORBUtilSystemException.writeErrorSend" client.$$
 result=$?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestAESCiphers/Dynamic.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.PrintStream;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.Arrays;
+import java.util.Random;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.IvParameterSpec;
+
+public class Dynamic {
+
+    static final String ALGORITHM = "AES";
+    static final String[] MODE = {
+        "ECb", "CbC", "CTR", "PCBC", "OFB", "OFB150", "cFB", "CFB7",
+        "cFB8", "cFB16", "cFB24", "cFB32", "Cfb40", "cfB48", "cfB56",
+        "cfB64", "cfB72", "cfB80", "cfB88", "cfB96", "cfb104", "cfB112",
+        "cfB120", "cfB128", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40",
+        "OFB48", "OFB56", "OFB64", "OFB72", "OFB80", "OFB88", "OFB96",
+        "OFB104", "OFB112", "OFB120", "OFB128", "GCM"
+    };
+    static final String[] PADDING = {
+        "NoPadding", "PKCS5Padding", "ISO10126Padding"
+    };
+    static final String SUNJCE = "SunJCE";
+
+    Cipher ci = null;
+    byte[] iv = null;
+    AlgorithmParameterSpec aps = null;
+    SecretKey key = null;
+    int keyStrength;
+    static int DefaultSize = 128;
+
+    public void run(String[] argv) throws Exception {
+        if (!runAllTest(argv, System.out)) {
+            throw new Exception("Test Failed");
+        }
+    }
+
+    protected boolean runAllTest(String argv[], PrintStream out) {
+        boolean result = true;
+        StringBuilder failedList = new StringBuilder();
+        int failedCnt = 0;
+        int testCount = 0;
+        int padKinds; // how many kinds of padding mode such as PKCS5padding and
+        // NoPadding.
+
+        try {
+            for (int i = 0; i < 3; i++) {
+                keyStrength = DefaultSize + i * 64; // obtain the key size 128,
+                // 192, 256
+
+                for (int j = 0; j < MODE.length; j++) {
+                    if (MODE[j].equalsIgnoreCase("ECB")
+                            || MODE[j].equalsIgnoreCase("PCBC")
+                            || MODE[j].equalsIgnoreCase("CBC")) {
+                        padKinds = PADDING.length;
+                    } else {
+                        padKinds = 1;
+                    }
+
+                    for (int k = 0; k < padKinds; k++) {
+                        testCount++;
+                        try {
+                            if (!runTest(ALGORITHM, MODE[j], PADDING[k])) {
+                                result = false;
+                                failedCnt++;
+                                failedList.append(ALGORITHM + "/" + MODE[j]
+                                        + "/" + PADDING[k] + " ");
+                            }
+                        } catch (Exception e) {
+                            e.printStackTrace();
+                            result = false;
+                            failedCnt++;
+                            failedList.append(ALGORITHM + "/" + MODE[j] + "/"
+                                    + PADDING[k] + " ");
+                        }
+
+                    }
+                }
+            }
+
+            if (result) {
+                out.println("STATUS:Passed. Test " + testCount
+                        + " cases, All Passed");
+                return true;
+            }
+            out.println("STATUS:Failed. " + failedCnt + " Failed: "
+                    + failedList);
+            return false;
+
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            out.println("STATUS:Failed. Unexpected Exception: " + ex);
+            return false;
+        }
+    }
+
+    protected boolean runTest(String algo, String mo, String pad)
+            throws Exception {
+        boolean result = true;
+        try {
+            byte[] plainText = new byte[160000];
+            new Random().nextBytes(plainText);
+
+            String transformation = algo + "/" + mo + "/" + pad;
+            ci = Cipher.getInstance(transformation, SUNJCE);
+            KeyGenerator kg = KeyGenerator.getInstance(algo, SUNJCE);
+            if (keyStrength > Cipher.getMaxAllowedKeyLength(transformation)) {
+                // skip if this key length is larger than what's
+                // configured in the jce jurisdiction policy files
+                System.out.println(keyStrength
+                        + " is larger than what's configured "
+                        + "in the jce jurisdiction policy files");
+                return result;
+            }
+            kg.init(keyStrength);
+            key = kg.generateKey();
+
+            if (!mo.equalsIgnoreCase("GCM")) {
+                ci.init(Cipher.ENCRYPT_MODE, key, aps);
+            } else {
+                ci.init(Cipher.ENCRYPT_MODE, key);
+            }
+            byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
+            int offset = ci.update(plainText, 0, plainText.length, cipherText,
+                    0);
+            ci.doFinal(cipherText, offset);
+
+            if (!mo.equalsIgnoreCase("ECB")) {
+                iv = ci.getIV();
+                aps = new IvParameterSpec(iv);
+            } else {
+                aps = null;
+            }
+
+            if (!mo.equalsIgnoreCase("GCM")) {
+                ci.init(Cipher.DECRYPT_MODE, key, aps);
+            } else {
+                ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
+            }
+            byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
+            int len = ci.doFinal(cipherText, 0, cipherText.length,
+                    recoveredText);
+
+            byte[] tmp = new byte[len];
+            for (int i = 0; i < len; i++) {
+                tmp[i] = recoveredText[i];
+            }
+
+            result = Arrays.equals(plainText, tmp);
+        } catch (NoSuchAlgorithmException nsaEx) {
+            nsaEx.printStackTrace();
+            // CFB7 and OFB150 are negative test,SunJCE not support this
+            // algorithm
+            result = mo.equalsIgnoreCase("CFB7")
+                    || mo.equalsIgnoreCase("OFB150");
+
+        }
+        return result;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestAESCiphers/TestAESWithDefaultProvider.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012, 2015, 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 8044193
+ * @summary Test AES ciphers with different modes and padding schemes with
+ *  default provider
+ */
+
+public class TestAESWithDefaultProvider extends Dynamic {
+    public static void main(String argv[]) throws Exception {
+        new TestAESWithDefaultProvider().run(argv);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestAESCiphers/TestAESWithProviderChange.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,39 @@
+/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.security.Security;
+
+/*
+ * @test
+ * @bug 8044193
+ * @summary Test AES ciphers with different modes and padding schemes after
+ *  remove then add provider.
+ * @run main/othervm/policy=testAES.policy TestAESWithProviderChange
+ */
+
+public class TestAESWithProviderChange extends Dynamic {
+    public static void main(String argv[]) throws Exception {
+        Security.removeProvider(SUNJCE);
+        Security.addProvider(new com.sun.crypto.provider.SunJCE());
+        new TestAESWithProviderChange().run(argv);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestAESCiphers/TestAESWithRemoveAddProvider.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.security.*;
+import java.security.Provider;
+
+/*
+ * @test
+ * @bug 8044193
+ * @summary Test AES ciphers with different modes and padding schemes after
+ *  remove default provider then add it back.
+ * @run main/othervm/policy=testAES.policy TestAESWithRemoveAddProvider
+ */
+
+public class TestAESWithRemoveAddProvider extends Dynamic {
+    public static void main(String argv[]) throws Exception {
+        Provider pJCE = Security.getProvider(SUNJCE);
+        Security.removeProvider(SUNJCE);
+        Security.addProvider(pJCE);
+        new TestAESWithRemoveAddProvider().run(argv);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestAESCiphers/testAES.policy	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,6 @@
+grant 
+{
+    permission java.security.SecurityPermission "removeProvider.SunJCE";
+    permission java.security.SecurityPermission "insertProvider.SunJCE";
+    permission java.security.SecurityPermission "putProviderProperty.SunJCE";
+};
--- a/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java	Thu Aug 04 18:37:15 2016 +0300
+++ b/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java	Mon Aug 08 15:29:16 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8026943
+ * @bug 8026943 8027575
  * @summary Verify that same buffer can be used as input and output when
  * using Cipher objects.
  * @author Valerie Peng
@@ -44,7 +44,7 @@
     private static SecretKey KEY = new SecretKeySpec(new byte[16], "AES");
     private static byte[] IV = new byte[16];
 
-    private static int[] OFFSETS = { 1, 8, 17 };
+    private static int[] OFFSETS = { 1, 8, 9, 16, 17, 32, 33 };
 
     private static final String[] MODES = {
         "ECB", "CBC", "PCBC", "CTR", "CTS",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/Blowfish/TestCipherBlowfish.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.security.NoSuchAlgorithmException;
+
+/*
+ * @test
+ * @bug 8048601
+ * @library ../
+ * @summary Test Blowfish cipher with different MODES and padding
+ */
+
+public class TestCipherBlowfish extends TestCipher {
+
+    TestCipherBlowfish() throws NoSuchAlgorithmException {
+        super("Blowfish",
+                new String[]{"CBC", "CTR", "CTS", "ECB", "PCBC",
+                    //CFBx
+                    "CFB", "CFB8", "CFB16", "CFB24", "CFB32", "CFB40", "CFB48", "CFB56",
+                    "CFB64",
+                    //OFBx
+                    "OFB", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56",
+                    "OFB64"},
+                new String[]{"NoPaDDing", "PKCS5Padding"},
+                true);
+    }
+
+    public static void main(String[] args) throws Exception {
+        new TestCipherBlowfish().runAll();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/DES/TestCipherDES.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2015, 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 8048601
+ * @library ../
+ * @summary Test DES/DESede cipher with different MODES and padding
+ */
+
+public class TestCipherDES extends TestCipher {
+
+    TestCipherDES() {
+        super("DES",
+                new String[]{"CBC", "CTR", "CTS", "ECB", "PCBC",
+                    //CFBx
+                    "CFB", "CFB8", "CFB16", "CFB24", "CFB32", "CFB40", "CFB48", "CFB56",
+                    "CFB64",
+                    //OFBx
+                    "OFB", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56",
+                    "OFB64"},
+                new String[]{"NoPaDDing", "PKCS5Padding"});
+    }
+
+    public static void main(String[] args) throws Exception {
+        new TestCipherDES().runAll();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/DES/TestCipherDESede.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2015, 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 8048601
+ * @library ../
+ * @summary Test DES/DESede cipher with different MODES and padding
+ */
+
+public class TestCipherDESede extends TestCipher {
+
+    TestCipherDESede() {
+        super("DESede",
+                new String[]{"CBC", "CTR", "CTS", "ECB", "PCBC",
+                    //CFBx
+                    "CFB", "CFB8", "CFB16", "CFB24", "CFB32", "CFB40", "CFB48", "CFB56",
+                    "CFB64",
+                    //OFBx
+                    "OFB", "OFB8", "OFB16", "OFB24", "OFB32", "OFB40", "OFB48", "OFB56",
+                    "OFB64"},
+                new String[]{"NoPaDDing", "PKCS5Padding"});
+    }
+
+    public static void main(String[] args) throws Exception {
+        new TestCipherDESede().runAll();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/PBE/TestCipherPBE.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2015, 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 static java.lang.System.out;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidKeySpecException;
+import java.util.Arrays;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.ShortBufferException;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+/*
+ * @test
+ * @bug 8048601
+ * @summary Tests for PBE ciphers
+ */
+public class TestCipherPBE {
+
+    private static final String[] ALGORITHMS = {"PBEWithMD5AndDES",
+        "PBEWithMD5AndDES/CBC/PKCS5Padding", "PBEWithMD5AndTripleDES",
+        "PBEWithMD5AndTripleDES/CBC/PKCS5Padding"};
+
+    private static final String KEY_ALGO = "pbeWithMD5ANDdes";
+    private final byte[] SALT;
+    private final byte[] PLAIN_TEXT;
+
+    public TestCipherPBE() {
+        SALT = generateBytes(8);
+        PLAIN_TEXT = generateBytes(200);
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        new TestCipherPBE().runAll();
+    }
+
+    private void runAll() throws Exception {
+        for (String algorithm : ALGORITHMS) {
+            runTest(algorithm);
+        }
+    }
+
+    private void runTest(String algorithm)
+            throws InvalidKeySpecException, NoSuchAlgorithmException,
+            InvalidAlgorithmParameterException, ShortBufferException,
+            NoSuchPaddingException, IllegalBlockSizeException,
+            BadPaddingException, InvalidKeyException {
+
+        out.println("=> Testing: " + algorithm);
+
+        try {
+            // Initialization
+            AlgorithmParameterSpec algoParamSpec
+                    = new PBEParameterSpec(SALT, 6);
+
+            SecretKey secretKey
+                    = SecretKeyFactory.getInstance(KEY_ALGO).generateSecret(
+                    new PBEKeySpec(("Secret Key Value").toCharArray()));
+
+            Cipher ci = Cipher.getInstance(algorithm);
+            ci.init(Cipher.ENCRYPT_MODE, secretKey, algoParamSpec);
+
+            // Encryption
+            byte[] cipherText = ci.doFinal(PLAIN_TEXT);
+
+            // Decryption
+            ci.init(Cipher.DECRYPT_MODE, secretKey, algoParamSpec);
+            byte[] recoveredText = ci.doFinal(cipherText);
+
+            if (algorithm.contains("TripleDES")) {
+                throw new RuntimeException(
+                        "Expected InvalidKeyException exception uncaugh");
+            }
+
+            // Comparison
+            if (!Arrays.equals(PLAIN_TEXT, recoveredText)) {
+                throw new RuntimeException(
+                        "Test failed: plainText is not equal to recoveredText");
+            }
+            out.println("Test Passed.");
+        } catch (InvalidKeyException ex) {
+            if (algorithm.contains("TripleDES")) {
+                out.println("Expected InvalidKeyException raised");
+            } else {
+                throw new RuntimeException(ex);
+            }
+        }
+    }
+
+    public static byte[] generateBytes(int length) {
+        byte[] bytes = new byte[length];
+        for (int i = 0; i < length; i++) {
+            bytes[i] = (byte) (i & 0xff);
+        }
+        return bytes;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/com/sun/crypto/provider/Cipher/TestCipher.java	Mon Aug 08 15:29:16 2016 -0700
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * 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 static java.lang.System.out;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderExc