Mercurial > hg > release > icedtea8-forest-3.0 > jdk
changeset 11691:efcf09751f0a
Merge
author | asaha |
---|---|
date | Thu, 29 Oct 2015 17:12:06 -0700 |
parents | 55b3e2dc4c47 (current diff) 5bab7361c6a3 (diff) |
children | 02f8fe1d8f9f |
files | .hgtags src/share/classes/sun/security/provider/certpath/ReverseBuilder.java src/share/classes/sun/security/provider/certpath/ReverseState.java src/share/classes/sun/security/provider/certpath/SunCertPathBuilderParameters.java src/solaris/native/java/net/AbstractPlainDatagramSocketImpl.c src/windows/native/java/net/AbstractPlainDatagramSocketImpl.c test/sun/security/provider/certpath/ReverseBuilder/BuildPath.java test/sun/security/provider/certpath/ReverseBuilder/ReverseBuild.java test/sun/security/provider/certpath/ReverseBuilder/mgrM2leadMA test/sun/security/provider/certpath/ReverseBuilder/mgrM2mgrM test/sun/security/provider/certpath/ReverseBuilder/mgrM2prjM test/sun/security/provider/certpath/ReverseBuilder/mgrMcrl test/sun/security/provider/certpath/ReverseBuilder/prjM2divE test/sun/security/provider/certpath/ReverseBuilder/prjM2mgrM test/sun/security/provider/certpath/ReverseBuilder/prjMcrl |
diffstat | 141 files changed, 4074 insertions(+), 3244 deletions(-) [+] |
line wrap: on
line diff
--- a/.hgtags Wed Oct 21 20:59:47 2015 +0300 +++ b/.hgtags Thu Oct 29 17:12:06 2015 -0700 @@ -499,4 +499,14 @@ e8b5e10a19d66a77d04f12d4677e6fec66f79651 jdk8u71-b01 25d689a73bc037e1710f95f6d4acf0671d22047d jdk8u71-b02 ab54163c8610f6238a1d5f1f67cbd19ba13d08a0 jdk8u71-b03 +5ea62bb625b6b8f828098884d13eb2e3114a7c97 jdk8u71-b04 +1a9ced1852957b65e0c156602c3101aff17274fb jdk8u71-b05 +be9d91d310a02c2974d2bdabc31d8a6df8ad596e jdk8u71-b06 +be5faa9c77042f202106c18f4e8ea211137b4a3b jdk8u72-b00 +5ad1e9e8e8417f80c91d7e0f1f44cdf89b34ead3 jdk8u72-b01 +ab0c1040414d038ccbcfcc8ceb1ccf2f44ead8e4 jdk8u72-b02 +bdbb8a650d90d3481802a4f5297b522a16bd3f63 jdk8u72-b03 +b6645d81ccd773820aca99548640ace9c2f39225 jdk8u72-b04 +2bae9d627eb83f2ea23f4fa86e8eb46920cd1be6 jdk8u72-b05 +93148bc60f510af5160b6727533733c66284a84f jdk8u72-b06 7cfd2c51c501df909833aa0fb6e40c50c61621ed jdk8u75-b00
--- a/make/lib/CoreLibraries.gmk Wed Oct 21 20:59:47 2015 +0300 +++ b/make/lib/CoreLibraries.gmk Thu Oct 29 17:12:06 2015 -0700 @@ -205,6 +205,7 @@ -framework Foundation \ -framework Security -framework SystemConfiguration, \ LDFLAGS_SUFFIX_windows := -export:winFileHandleOpen -export:handleLseek \ + -export:getErrorString \ jvm.lib $(BUILD_LIBFDLIBM) $(WIN_VERIFY_LIB) \ shell32.lib delayimp.lib -DELAYLOAD:shell32.dll \ advapi32.lib version.lib, \
--- a/make/mapfiles/libawt/mapfile-mawt-vers Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libawt/mapfile-mawt-vers Thu Oct 29 17:12:06 2015 -0700 @@ -242,7 +242,7 @@ getDefaultConfig; Java_sun_font_FontConfigManager_getFontConfig; Java_sun_font_FontConfigManager_getFontConfigAASettings; - Java_sun_awt_X11FontManager_getFontPathNative; + Java_sun_awt_FcFontManager_getFontPathNative; Java_sun_font_SunFontManager_populateFontFileNameMap; # CDE private entry point
--- a/make/mapfiles/libawt/mapfile-vers-linux Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libawt/mapfile-vers-linux Thu Oct 29 17:12:06 2015 -0700 @@ -270,7 +270,7 @@ getDefaultConfig; Java_sun_font_FontConfigManager_getFontConfig; Java_sun_font_FontConfigManager_getFontConfigAASettings; - Java_sun_awt_X11FontManager_getFontPathNative; + Java_sun_awt_FcFontManager_getFontPathNative; Java_sun_font_SunFontManager_populateFontFileNameMap; # CDE private entry point
--- a/make/mapfiles/libawt_headless/mapfile-vers Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libawt_headless/mapfile-vers Thu Oct 29 17:12:06 2015 -0700 @@ -65,7 +65,7 @@ Java_sun_font_FontConfigManager_getFontConfig; Java_sun_font_FontConfigManager_getFontConfigAASettings; Java_sun_font_FontConfigManager_getFontConfigVersion; - Java_sun_awt_X11FontManager_getFontPathNative; + Java_sun_awt_FcFontManager_getFontPathNative; Java_sun_awt_FontDescriptor_initIDs; Java_sun_awt_PlatformFont_initIDs;
--- a/make/mapfiles/libawt_xawt/mapfile-vers Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libawt_xawt/mapfile-vers Thu Oct 29 17:12:06 2015 -0700 @@ -188,7 +188,7 @@ Java_sun_font_FontConfigManager_getFontConfig; Java_sun_font_FontConfigManager_getFontConfigAASettings; Java_sun_font_FontConfigManager_getFontConfigVersion; - Java_sun_awt_X11FontManager_getFontPathNative; + Java_sun_awt_FcFontManager_getFontPathNative; Java_sun_awt_X11GraphicsEnvironment_initDisplay; Java_sun_awt_X11GraphicsEnvironment_initGLX; Java_sun_awt_X11GraphicsEnvironment_initXRender;
--- a/make/mapfiles/libjava/mapfile-vers Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libjava/mapfile-vers Thu Oct 29 17:12:06 2015 -0700 @@ -284,6 +284,8 @@ # ZipFile.c needs this one throwFileNotFoundException; + # zip_util.c needs this + getErrorString; # Java_sun_misc_VM_getState; threads.c # Java_sun_misc_VM_threadsSuspended; threads.c
--- a/make/mapfiles/libnet/mapfile-vers Wed Oct 21 20:59:47 2015 +0300 +++ b/make/mapfiles/libnet/mapfile-vers Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 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 @@ -28,8 +28,7 @@ SUNWprivate_1.1 { global: JNI_OnLoad; - Java_java_net_AbstractPlainDatagramSocketImpl_init; - Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable; + Java_java_net_PlainDatagramSocketImpl_dataAvailable; Java_java_net_PlainSocketImpl_socketListen; Java_java_net_PlainDatagramSocketImpl_getTTL; Java_java_net_PlainDatagramSocketImpl_init;
--- a/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,3 +1,4 @@ + /* * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -27,9 +28,10 @@ import java.awt.*; import java.awt.image.*; -import sun.awt.image.ImageRepresentation; import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.text.Normalizer; import java.text.Normalizer.Form; @@ -54,7 +56,8 @@ "PDF", "URL", "PNG", - "JFIF" + "JFIF", + "XPICT" }; static { @@ -78,6 +81,7 @@ public static final int CF_URL = 7; public static final int CF_PNG = 8; public static final int CF_JPEG = 9; + public static final int CF_XPICT = 10; private CDataTransferer() {} @@ -122,26 +126,43 @@ @Override public Object translateBytes(byte[] bytes, DataFlavor flavor, - long format, Transferable transferable) throws IOException { + long format, Transferable transferable) throws IOException { + - if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass())) - { - String charset = getDefaultTextCharset(); - if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { - try { - charset = new String((byte[])transferable.getTransferData(javaTextEncodingFlavor), "UTF-8"); - } catch (UnsupportedFlavorException cannotHappen) { - } + if (format == CF_URL && URL.class.equals(flavor.getRepresentationClass())) { + String[] strings = dragQueryFile(bytes); + if(strings == null || strings.length == 0) { + return null; + } + return new URL(strings[0]); + } else if(isUriListFlavor(flavor)) { + // dragQueryFile works fine with files and url, + // it parses and extracts values from property list. + // maxosx always returns property list for + // CF_URL and CF_FILE + String[] strings = dragQueryFile(bytes); + if(strings == null) { + return null; + } + String separator = System.getProperty("line.separator"); + StringBuilder sb = new StringBuilder(); + if(strings.length > 0) { + sb.append(strings[0]); + for(int i = 1; i < strings.length; i++) { + sb.append(strings[i]); + sb.append(separator); } - - return new URL(new String(bytes, charset)); } + bytes = sb.toString().getBytes(); + // now we extracted uri from xml, now we should treat it as + // regular string that allows to translate data to target represantation + // class by base method + format = CF_STRING; + } else if (format == CF_STRING) { + bytes = Normalizer.normalize(new String(bytes, "UTF8"), Form.NFC).getBytes("UTF8"); + } - if (format == CF_STRING) { - bytes = Normalizer.normalize(new String(bytes, "UTF8"), Form.NFC).getBytes("UTF8"); - } - - return super.translateBytes(bytes, flavor, format, transferable); + return super.translateBytes(bytes, flavor, format, transferable); } @Override @@ -219,6 +240,7 @@ return nativeDragQueryFile(bytes); } + @Override protected Image platformImageBytesToImage(byte[] bytes, long format) throws IOException { return CImage.getCreator().createImageFromPlatformImageBytes(bytes); @@ -243,7 +265,7 @@ } try { DataFlavor df = new DataFlavor(nat); - if (df.getPrimaryType().equals("text") && df.getSubType().equals("uri-list")) { + if (isUriListFlavor(df)) { return true; } } catch (Exception e) { @@ -251,6 +273,13 @@ } return false; } + + private boolean isUriListFlavor(DataFlavor df) { + if (df.getPrimaryType().equals("text") && df.getSubType().equals("uri-list")) { + return true; + } + return false; + } }
--- a/src/macosx/classes/sun/nio/ch/KQueueSelectorImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/macosx/classes/sun/nio/ch/KQueueSelectorImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -84,10 +84,24 @@ long fds = IOUtil.makePipe(false); fd0 = (int)(fds >>> 32); fd1 = (int)fds; - kqueueWrapper = new KQueueArrayWrapper(); - kqueueWrapper.initInterrupt(fd0, fd1); - fdMap = new HashMap<>(); - totalChannels = 1; + try { + kqueueWrapper = new KQueueArrayWrapper(); + kqueueWrapper.initInterrupt(fd0, fd1); + fdMap = new HashMap<>(); + totalChannels = 1; + } catch (Throwable t) { + try { + FileDispatcherImpl.closeIntFD(fd0); + } catch (IOException ioe0) { + t.addSuppressed(ioe0); + } + try { + FileDispatcherImpl.closeIntFD(fd1); + } catch (IOException ioe1) { + t.addSuppressed(ioe1); + } + throw t; + } }
--- a/src/macosx/lib/flavormap.properties Wed Oct 21 20:59:47 2015 +0300 +++ b/src/macosx/lib/flavormap.properties Thu Oct 29 17:12:06 2015 -0700 @@ -80,4 +80,6 @@ RICH_TEXT=text/rtf HTML=text/html;charset=utf-8;eoln="\r\n";terminators=1 URL=application/x-java-url;class=java.net.URL +FILE_NAME=text/uri-list;eoln="\r\n";terminators=1 URL=text/uri-list;eoln="\r\n";terminators=1 +XPICT=image/x-pict;class=java.io.InputStream
--- a/src/macosx/native/sun/awt/CDataTransferer.m Wed Oct 21 20:59:47 2015 +0300 +++ b/src/macosx/native/sun/awt/CDataTransferer.m Thu Oct 29 17:12:06 2015 -0700 @@ -58,6 +58,8 @@ forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_PNG]]; [sStandardMappings setObject:(NSString*)kUTTypeJPEG forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_JPEG]]; + [sStandardMappings setObject:NSPICTPboardType + forKey:[NSNumber numberWithLong:sun_lwawt_macosx_CDataTransferer_CF_XPICT]]; } return sStandardMappings; }
--- a/src/macosx/native/sun/awt/LWCToolkit.m Wed Oct 21 20:59:47 2015 +0300 +++ b/src/macosx/native/sun/awt/LWCToolkit.m Thu Oct 29 17:12:06 2015 -0700 @@ -287,7 +287,7 @@ // Processing all events excluding NSApplicationDefined which need to be processed // on the main loop only (those events are intended for disposing resources) NSEvent *event; - if ((event = [NSApp nextEventMatchingMask:(NSAnyEventMask & ~NSApplicationDefined) + if ((event = [NSApp nextEventMatchingMask:(NSAnyEventMask & ~NSApplicationDefinedMask) untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES]) != nil) {
--- a/src/share/classes/com/sun/jndi/ldap/LdapClient.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/com/sun/jndi/ldap/LdapClient.java Thu Oct 29 17:12:06 2015 -0700 @@ -494,16 +494,14 @@ */ void processConnectionClosure() { // Notify listeners - synchronized (unsolicited) { - if (unsolicited.size() > 0) { - String msg; - if (conn != null) { - msg = conn.host + ":" + conn.port + " connection closed"; - } else { - msg = "Connection closed"; - } - notifyUnsolicited(new CommunicationException(msg)); + if (unsolicited.size() > 0) { + String msg; + if (conn != null) { + msg = conn.host + ":" + conn.port + " connection closed"; + } else { + msg = "Connection closed"; } + notifyUnsolicited(new CommunicationException(msg)); } // Remove from pool @@ -1499,13 +1497,8 @@ if (debug > 0) { System.err.println("LdapClient.removeUnsolicited" + ctx); } - synchronized (unsolicited) { - if (unsolicited.size() == 0) { - return; - } unsolicited.removeElement(ctx); } - } // NOTE: Cannot be synchronized because this is called asynchronously // by the reader thread in Connection. Instead, sync on 'unsolicited' Vector. @@ -1513,30 +1506,35 @@ if (debug > 0) { System.err.println("LdapClient.processUnsolicited"); } - synchronized (unsolicited) { - try { - // Parse the response - LdapResult res = new LdapResult(); + try { + // Parse the response + LdapResult res = new LdapResult(); + + ber.parseSeq(null); // init seq + ber.parseInt(); // msg id; should be 0; ignored + if (ber.parseByte() != LDAP_REP_EXTENSION) { + throw new IOException( + "Unsolicited Notification must be an Extended Response"); + } + ber.parseLength(); + parseExtResponse(ber, res); - ber.parseSeq(null); // init seq - ber.parseInt(); // msg id; should be 0; ignored - if (ber.parseByte() != LDAP_REP_EXTENSION) { - throw new IOException( - "Unsolicited Notification must be an Extended Response"); - } - ber.parseLength(); - parseExtResponse(ber, res); + if (DISCONNECT_OID.equals(res.extensionId)) { + // force closing of connection + forceClose(pooled); + } - if (DISCONNECT_OID.equals(res.extensionId)) { - // force closing of connection - forceClose(pooled); - } + LdapCtx first = null; + UnsolicitedNotification notice = null; + synchronized (unsolicited) { if (unsolicited.size() > 0) { + first = unsolicited.elementAt(0); + // Create an UnsolicitedNotification using the parsed data // Need a 'ctx' object because we want to use the context's // list of provider control factories. - UnsolicitedNotification notice = new UnsolicitedResponseImpl( + notice = new UnsolicitedResponseImpl( res.extensionId, res.extensionValue, res.referrals, @@ -1544,42 +1542,45 @@ res.errorMessage, res.matchedDN, (res.resControls != null) ? - unsolicited.elementAt(0).convertControls(res.resControls) : + first.convertControls(res.resControls) : null); - - // Fire UnsolicitedNotification events to listeners - notifyUnsolicited(notice); - - // If "disconnect" notification, - // notify unsolicited listeners via NamingException - if (DISCONNECT_OID.equals(res.extensionId)) { - notifyUnsolicited( - new CommunicationException("Connection closed")); - } } - } catch (IOException e) { - if (unsolicited.size() == 0) - return; // no one registered; ignore + } + + if (notice != null) { + // Fire UnsolicitedNotification events to listeners + notifyUnsolicited(notice); - NamingException ne = new CommunicationException( - "Problem parsing unsolicited notification"); - ne.setRootCause(e); + // If "disconnect" notification, + // notify unsolicited listeners via NamingException + if (DISCONNECT_OID.equals(res.extensionId)) { + notifyUnsolicited( + new CommunicationException("Connection closed")); + } + } + } catch (IOException e) { + NamingException ne = new CommunicationException( + "Problem parsing unsolicited notification"); + ne.setRootCause(e); - notifyUnsolicited(ne); + notifyUnsolicited(ne); - } catch (NamingException e) { - notifyUnsolicited(e); - } + } catch (NamingException e) { + notifyUnsolicited(e); } } private void notifyUnsolicited(Object e) { - for (int i = 0; i < unsolicited.size(); i++) { - unsolicited.elementAt(i).fireUnsolicited(e); + Vector<LdapCtx> unsolicitedCopy; + synchronized (unsolicited) { + unsolicitedCopy = new Vector<>(unsolicited); + if (e instanceof NamingException) { + unsolicited.setSize(0); // no more listeners after exception + } } - if (e instanceof NamingException) { - unsolicited.setSize(0); // no more listeners after exception + for (int i = 0; i < unsolicitedCopy.size(); i++) { + unsolicitedCopy.elementAt(i).fireUnsolicited(e); } }
--- a/src/share/classes/java/awt/EventQueue.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/awt/EventQueue.java Thu Oct 29 17:12:06 2015 -0700 @@ -896,11 +896,13 @@ } } - // Wake up EDT waiting in getNextEvent(), so it can - // pick up a new EventQueue. Post the waking event before - // topQueue.nextQueue is assigned, otherwise the event would - // go newEventQueue - topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); + if (topQueue.dispatchThread != null) { + // Wake up EDT waiting in getNextEvent(), so it can + // pick up a new EventQueue. Post the waking event before + // topQueue.nextQueue is assigned, otherwise the event would + // go newEventQueue + topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); + } newEventQueue.previousQueue = topQueue; topQueue.nextQueue = newEventQueue;
--- a/src/share/classes/java/lang/Character.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/Character.java Thu Oct 29 17:12:06 2015 -0700 @@ -6647,7 +6647,7 @@ * <td>{@code FORM FEED}</td></tr> * <tr><td>{@code '\r'}</td> <td>{@code U+000D}</td> * <td>{@code CARRIAGE RETURN}</td></tr> - * <tr><td>{@code ' '}</td> <td>{@code U+0020}</td> + * <tr><td>{@code ' '}</td> <td>{@code U+0020}</td> * <td>{@code SPACE}</td></tr> * </table> *
--- a/src/share/classes/java/lang/invoke/LambdaFormEditor.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/invoke/LambdaFormEditor.java Thu Oct 29 17:12:06 2015 -0700 @@ -436,7 +436,7 @@ } private MethodType bindArgumentType(BoundMethodHandle mh, int pos, BasicType bt) { - assert(mh.form == lambdaForm); + assert(mh.form.uncustomize() == lambdaForm); assert(mh.form.names[1+pos].type == bt); assert(BasicType.basicType(mh.type().parameterType(pos)) == bt); return mh.type().dropParameterTypes(pos, pos+1);
--- a/src/share/classes/java/lang/invoke/MemberName.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/invoke/MemberName.java Thu Oct 29 17:12:06 2015 -0700 @@ -93,7 +93,7 @@ /** Return the simple name of this member. * For a type, it is the same as {@link Class#getSimpleName}. * For a method or field, it is the simple name of the member. - * For a constructor, it is always {@code "<init>"}. + * For a constructor, it is always {@code "<init>"}. */ public String getName() { if (name == null) { @@ -727,7 +727,7 @@ } /** Create a method or constructor name from the given components: * Declaring class, name, type, reference kind. - * It will be a constructor if and only if the name is {@code "<init>"}. + * It will be a constructor if and only if the name is {@code "<init>"}. * The declaring class may be supplied as null if this is to be a bare name and type. * The last argument is optional, a boolean which requests REF_invokeSpecial. * The resulting name will in an unresolved state.
--- a/src/share/classes/java/lang/invoke/MethodHandleInfo.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/invoke/MethodHandleInfo.java Thu Oct 29 17:12:06 2015 -0700 @@ -155,7 +155,7 @@ /** * Returns the name of the cracked method handle's underlying member. - * This is {@code "<init>"} if the underlying member was a constructor, + * This is {@code "<init>"} if the underlying member was a constructor, * else it is a simple method name or field name. * @return the simple name of the underlying member */
--- a/src/share/classes/java/lang/invoke/Stable.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/invoke/Stable.java Thu Oct 29 17:12:06 2015 -0700 @@ -51,7 +51,7 @@ * If the field is an array type, then both the field value and * all the components of the field value (if the field value is non-null) * are indicated to be stable. - * If the field type is an array type with rank {@code N > 1}, + * If the field type is an array type with rank {@code N > 1}, * then each component of the field value (if the field value is non-null), * is regarded as a stable array of rank {@code N-1}. * <p>
--- a/src/share/classes/java/lang/invoke/SwitchPoint.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/invoke/SwitchPoint.java Thu Oct 29 17:12:06 2015 -0700 @@ -55,20 +55,20 @@ * At that point {@code guardWithTest} may ignore {@code T} and return {@code F}. * <p> * Here is an example of a switch point in action: - * <blockquote><pre>{@code -MethodHandle MH_strcat = MethodHandles.lookup() - .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class)); -SwitchPoint spt = new SwitchPoint(); -assert(!spt.hasBeenInvalidated()); -// the following steps may be repeated to re-use the same switch point: -MethodHandle worker1 = MH_strcat; -MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0); -MethodHandle worker = spt.guardWithTest(worker1, worker2); -assertEquals("method", (String) worker.invokeExact("met", "hod")); -SwitchPoint.invalidateAll(new SwitchPoint[]{ spt }); -assert(spt.hasBeenInvalidated()); -assertEquals("hodmet", (String) worker.invokeExact("met", "hod")); - * }</pre></blockquote> + * <pre>{@code + * MethodHandle MH_strcat = MethodHandles.lookup() + * .findVirtual(String.class, "concat", MethodType.methodType(String.class, String.class)); + * SwitchPoint spt = new SwitchPoint(); + * assert(!spt.hasBeenInvalidated()); + * // the following steps may be repeated to re-use the same switch point: + * MethodHandle worker1 = MH_strcat; + * MethodHandle worker2 = MethodHandles.permuteArguments(MH_strcat, MH_strcat.type(), 1, 0); + * MethodHandle worker = spt.guardWithTest(worker1, worker2); + * assertEquals("method", (String) worker.invokeExact("met", "hod")); + * SwitchPoint.invalidateAll(new SwitchPoint[]{ spt }); + * assert(spt.hasBeenInvalidated()); + * assertEquals("hodmet", (String) worker.invokeExact("met", "hod")); + * }</pre> * <p style="font-size:smaller;"> * <em>Discussion:</em> * Switch points are useful without subclassing. They may also be subclassed. @@ -82,31 +82,31 @@ * <em>Implementation Note:</em> * A switch point behaves as if implemented on top of {@link MutableCallSite}, * approximately as follows: - * <blockquote><pre>{@code -public class SwitchPoint { - private static final MethodHandle - K_true = MethodHandles.constant(boolean.class, true), - K_false = MethodHandles.constant(boolean.class, false); - private final MutableCallSite mcs; - private final MethodHandle mcsInvoker; - public SwitchPoint() { - this.mcs = new MutableCallSite(K_true); - this.mcsInvoker = mcs.dynamicInvoker(); - } - public MethodHandle guardWithTest( - MethodHandle target, MethodHandle fallback) { - // Note: mcsInvoker is of type ()boolean. - // Target and fallback may take any arguments, but must have the same type. - return MethodHandles.guardWithTest(this.mcsInvoker, target, fallback); - } - public static void invalidateAll(SwitchPoint[] spts) { - List<MutableCallSite> mcss = new ArrayList<>(); - for (SwitchPoint spt : spts) mcss.add(spt.mcs); - for (MutableCallSite mcs : mcss) mcs.setTarget(K_false); - MutableCallSite.syncAll(mcss.toArray(new MutableCallSite[0])); - } -} - * }</pre></blockquote> + * <pre>{@code + * public class SwitchPoint { + * private static final MethodHandle + * K_true = MethodHandles.constant(boolean.class, true), + * K_false = MethodHandles.constant(boolean.class, false); + * private final MutableCallSite mcs; + * private final MethodHandle mcsInvoker; + * public SwitchPoint() { + * this.mcs = new MutableCallSite(K_true); + * this.mcsInvoker = mcs.dynamicInvoker(); + * } + * public MethodHandle guardWithTest( + * MethodHandle target, MethodHandle fallback) { + * // Note: mcsInvoker is of type ()boolean. + * // Target and fallback may take any arguments, but must have the same type. + * return MethodHandles.guardWithTest(this.mcsInvoker, target, fallback); + * } + * public static void invalidateAll(SwitchPoint[] spts) { + * List<MutableCallSite> mcss = new ArrayList<>(); + * for (SwitchPoint spt : spts) mcss.add(spt.mcs); + * for (MutableCallSite mcs : mcss) mcs.setTarget(K_false); + * MutableCallSite.syncAll(mcss.toArray(new MutableCallSite[0])); + * } + * } + * }</pre> * @author Remi Forax, JSR 292 EG */ public class SwitchPoint {
--- a/src/share/classes/java/lang/ref/Reference.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/ref/Reference.java Thu Oct 29 17:12:06 2015 -0700 @@ -26,6 +26,8 @@ package java.lang.ref; import sun.misc.Cleaner; +import sun.misc.JavaLangRefAccess; +import sun.misc.SharedSecrets; /** * Abstract base class for reference objects. This class defines the @@ -111,7 +113,7 @@ * therefore critical that any code holding this lock complete as quickly * as possible, allocate no new objects, and avoid calling user code. */ - static private class Lock { }; + static private class Lock { } private static Lock lock = new Lock(); @@ -126,53 +128,96 @@ */ private static class ReferenceHandler extends Thread { + private static void ensureClassInitialized(Class<?> clazz) { + try { + Class.forName(clazz.getName(), true, clazz.getClassLoader()); + } catch (ClassNotFoundException e) { + throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); + } + } + + static { + // pre-load and initialize InterruptedException and Cleaner classes + // so that we don't get into trouble later in the run loop if there's + // memory shortage while loading/initializing them lazily. + ensureClassInitialized(InterruptedException.class); + ensureClassInitialized(Cleaner.class); + } + ReferenceHandler(ThreadGroup g, String name) { super(g, name); } public void run() { - for (;;) { - Reference<Object> r; - synchronized (lock) { - if (pending != null) { - r = pending; - pending = r.discovered; - r.discovered = null; - } else { - // The waiting on the lock may cause an OOME because it may try to allocate - // exception objects, so also catch OOME here to avoid silent exit of the - // reference handler thread. - // - // Explicitly define the order of the two exceptions we catch here - // when waiting for the lock. - // - // We do not want to try to potentially load the InterruptedException class - // (which would be done if this was its first use, and InterruptedException - // were checked first) in this situation. - // - // This may lead to the VM not ever trying to load the InterruptedException - // class again. - try { - try { - lock.wait(); - } catch (OutOfMemoryError x) { } - } catch (InterruptedException x) { } - continue; - } - } - - // Fast path for cleaners - if (r instanceof Cleaner) { - ((Cleaner)r).clean(); - continue; - } - - ReferenceQueue<Object> q = r.queue; - if (q != ReferenceQueue.NULL) q.enqueue(r); + while (true) { + tryHandlePending(true); } } } + /** + * Try handle pending {@link Reference} if there is one.<p> + * Return {@code true} as a hint that there might be another + * {@link Reference} pending or {@code false} when there are no more pending + * {@link Reference}s at the moment and the program can do some other + * useful work instead of looping. + * + * @param waitForNotify if {@code true} and there was no pending + * {@link Reference}, wait until notified from VM + * or interrupted; if {@code false}, return immediately + * when there is no pending {@link Reference}. + * @return {@code true} if there was a {@link Reference} pending and it + * was processed, or we waited for notification and either got it + * or thread was interrupted before being notified; + * {@code false} otherwise. + */ + static boolean tryHandlePending(boolean waitForNotify) { + Reference<Object> r; + Cleaner c; + try { + synchronized (lock) { + if (pending != null) { + r = pending; + // 'instanceof' might throw OutOfMemoryError sometimes + // so do this before un-linking 'r' from the 'pending' chain... + c = r instanceof Cleaner ? (Cleaner) r : null; + // unlink 'r' from 'pending' chain + pending = r.discovered; + r.discovered = null; + } else { + // The waiting on the lock may cause an OutOfMemoryError + // because it may try to allocate exception objects. + if (waitForNotify) { + lock.wait(); + } + // retry if waited + return waitForNotify; + } + } + } catch (OutOfMemoryError x) { + // Give other threads CPU time so they hopefully drop some live references + // and GC reclaims some space. + // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above + // persistently throws OOME for some time... + Thread.yield(); + // retry + return true; + } catch (InterruptedException x) { + // retry + return true; + } + + // Fast path for cleaners + if (c != null) { + c.clean(); + return true; + } + + ReferenceQueue<? super Object> q = r.queue; + if (q != ReferenceQueue.NULL) q.enqueue(r); + return true; + } + static { ThreadGroup tg = Thread.currentThread().getThreadGroup(); for (ThreadGroup tgn = tg; @@ -185,9 +230,16 @@ handler.setPriority(Thread.MAX_PRIORITY); handler.setDaemon(true); handler.start(); + + // provide access in SharedSecrets + SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { + @Override + public boolean tryHandlePendingReference() { + return tryHandlePending(false); + } + }); } - /* -- Referent accessor and setters -- */ /**
--- a/src/share/classes/java/lang/reflect/Constructor.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/reflect/Constructor.java Thu Oct 29 17:12:06 2015 -0700 @@ -218,6 +218,7 @@ /** * {@inheritDoc} + * @since 1.8 */ public int getParameterCount() { return parameterTypes.length; }
--- a/src/share/classes/java/lang/reflect/Executable.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/reflect/Executable.java Thu Oct 29 17:12:06 2015 -0700 @@ -245,7 +245,6 @@ * declared or implicitly declared or neither) for the executable * represented by this object. * - * @since 1.8 * @return The number of formal parameters for the executable this * object represents */ @@ -343,7 +342,6 @@ * have unique names, or names that are legal identifiers in the * Java programming language (JLS 3.8). * - * @since 1.8 * @throws MalformedParametersException if the class file contains * a MethodParameters attribute that is improperly formatted. * @return an array of {@code Parameter} objects representing all @@ -575,7 +573,6 @@ /** * {@inheritDoc} * @throws NullPointerException {@inheritDoc} - * @since 1.8 */ @Override public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { @@ -623,8 +620,6 @@ * * @return an object representing the return type of the method * or constructor represented by this {@code Executable} - * - * @since 1.8 */ public abstract AnnotatedType getAnnotatedReturnType(); @@ -633,8 +628,6 @@ * Returns an AnnotatedType object that represents the use of a type to * specify the return type of the method/constructor represented by this * Executable. - * - * @since 1.8 */ AnnotatedType getAnnotatedReturnType0(Type returnType) { return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(), @@ -664,8 +657,6 @@ * * @return an object representing the receiver type of the method or * constructor represented by this {@code Executable} - * - * @since 1.8 */ public AnnotatedType getAnnotatedReceiverType() { if (Modifier.isStatic(this.getModifiers())) @@ -692,8 +683,6 @@ * @return an array of objects representing the types of the * formal parameters of the method or constructor represented by this * {@code Executable} - * - * @since 1.8 */ public AnnotatedType[] getAnnotatedParameterTypes() { return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(), @@ -718,8 +707,6 @@ * @return an array of objects representing the declared * exceptions of the method or constructor represented by this {@code * Executable} - * - * @since 1.8 */ public AnnotatedType[] getAnnotatedExceptionTypes() { return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
--- a/src/share/classes/java/lang/reflect/Method.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/lang/reflect/Method.java Thu Oct 29 17:12:06 2015 -0700 @@ -266,6 +266,7 @@ /** * {@inheritDoc} + * @since 1.8 */ public int getParameterCount() { return parameterTypes.length; }
--- a/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/net/AbstractPlainDatagramSocketImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -68,7 +68,6 @@ return null; } }); - init(); } /** @@ -364,6 +363,5 @@ return connectDisabled; } - native int dataAvailable(); - private static native void init(); + abstract int dataAvailable(); }
--- a/src/share/classes/java/nio/Bits.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/nio/Bits.java Thu Oct 29 17:12:06 2015 -0700 @@ -26,6 +26,11 @@ package java.nio; import java.security.AccessController; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.LongAdder; + +import sun.misc.JavaLangRefAccess; +import sun.misc.SharedSecrets; import sun.misc.Unsafe; import sun.misc.VM; @@ -621,55 +626,103 @@ // direct buffer memory. This value may be changed during VM // initialization if it is launched with "-XX:MaxDirectMemorySize=<size>". private static volatile long maxMemory = VM.maxDirectMemory(); - private static volatile long reservedMemory; - private static volatile long totalCapacity; - private static volatile long count; - private static boolean memoryLimitSet = false; + private static final AtomicLong reservedMemory = new AtomicLong(); + private static final AtomicLong totalCapacity = new AtomicLong(); + private static final AtomicLong count = new AtomicLong(); + private static volatile boolean memoryLimitSet = false; + // max. number of sleeps during try-reserving with exponentially + // increasing delay before throwing OutOfMemoryError: + // 1, 2, 4, 8, 16, 32, 64, 128, 256 (total 511 ms ~ 0.5 s) + // which means that OOME will be thrown after 0.5 s of trying + private static final int MAX_SLEEPS = 9; // These methods should be called whenever direct memory is allocated or // freed. They allow the user to control the amount of direct memory // which a process may access. All sizes are specified in bytes. static void reserveMemory(long size, int cap) { - synchronized (Bits.class) { - if (!memoryLimitSet && VM.isBooted()) { - maxMemory = VM.maxDirectMemory(); - memoryLimitSet = true; - } - // -XX:MaxDirectMemorySize limits the total capacity rather than the - // actual memory usage, which will differ when buffers are page - // aligned. - if (cap <= maxMemory - totalCapacity) { - reservedMemory += size; - totalCapacity += cap; - count++; + + if (!memoryLimitSet && VM.isBooted()) { + maxMemory = VM.maxDirectMemory(); + memoryLimitSet = true; + } + + // optimist! + if (tryReserveMemory(size, cap)) { + return; + } + + final JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess(); + + // retry while helping enqueue pending Reference objects + // which includes executing pending Cleaner(s) which includes + // Cleaner(s) that free direct buffer memory + while (jlra.tryHandlePendingReference()) { + if (tryReserveMemory(size, cap)) { return; } } + // trigger VM's Reference processing System.gc(); + + // a retry loop with exponential back-off delays + // (this gives VM some time to do it's job) + boolean interrupted = false; try { - Thread.sleep(100); - } catch (InterruptedException x) { - // Restore interrupt status - Thread.currentThread().interrupt(); + long sleepTime = 1; + int sleeps = 0; + while (true) { + if (tryReserveMemory(size, cap)) { + return; + } + if (sleeps >= MAX_SLEEPS) { + break; + } + if (!jlra.tryHandlePendingReference()) { + try { + Thread.sleep(sleepTime); + sleepTime <<= 1; + sleeps++; + } catch (InterruptedException e) { + interrupted = true; + } + } + } + + // no luck + throw new OutOfMemoryError("Direct buffer memory"); + + } finally { + if (interrupted) { + // don't swallow interrupts + Thread.currentThread().interrupt(); + } } - synchronized (Bits.class) { - if (totalCapacity + cap > maxMemory) - throw new OutOfMemoryError("Direct buffer memory"); - reservedMemory += size; - totalCapacity += cap; - count++; + } + + private static boolean tryReserveMemory(long size, int cap) { + + // -XX:MaxDirectMemorySize limits the total capacity rather than the + // actual memory usage, which will differ when buffers are page + // aligned. + long totalCap; + while (cap <= maxMemory - (totalCap = totalCapacity.get())) { + if (totalCapacity.compareAndSet(totalCap, totalCap + cap)) { + reservedMemory.addAndGet(size); + count.incrementAndGet(); + return true; + } } + return false; } - static synchronized void unreserveMemory(long size, int cap) { - if (reservedMemory > 0) { - reservedMemory -= size; - totalCapacity -= cap; - count--; - assert (reservedMemory > -1); - } + + static void unreserveMemory(long size, int cap) { + long cnt = count.decrementAndGet(); + long reservedMem = reservedMemory.addAndGet(-size); + long totalCap = totalCapacity.addAndGet(-cap); + assert cnt >= 0 && reservedMem >= 0 && totalCap >= 0; } // -- Monitoring of direct buffer usage -- @@ -687,15 +740,15 @@ } @Override public long getCount() { - return Bits.count; + return Bits.count.get(); } @Override public long getTotalCapacity() { - return Bits.totalCapacity; + return Bits.totalCapacity.get(); } @Override public long getMemoryUsed() { - return Bits.reservedMemory; + return Bits.reservedMemory.get(); } }; }
--- a/src/share/classes/java/text/SimpleDateFormat.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/text/SimpleDateFormat.java Thu Oct 29 17:12:06 2015 -0700 @@ -1722,7 +1722,7 @@ } return (start + zoneNames[nameIndex].length()); } - return 0; + return -start; } /**
--- a/src/share/classes/java/time/Instant.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/time/Instant.java Thu Oct 29 17:12:06 2015 -0700 @@ -1229,8 +1229,14 @@ * @throws ArithmeticException if numeric overflow occurs */ public long toEpochMilli() { - long millis = Math.multiplyExact(seconds, 1000); - return millis + nanos / 1000_000; + if (seconds < 0 && nanos > 0) { + long millis = Math.multiplyExact(seconds+1, 1000); + long adjustment = nanos / 1000_000 - 1000; + return Math.addExact(millis, adjustment); + } else { + long millis = Math.multiplyExact(seconds, 1000); + return Math.addExact(millis, nanos / 1000_000); + } } //-----------------------------------------------------------------------
--- a/src/share/classes/java/time/chrono/ChronoLocalDate.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/time/chrono/ChronoLocalDate.java Thu Oct 29 17:12:06 2015 -0700 @@ -715,7 +715,7 @@ * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the time-line position. - * This is equivalent to using {@code date1.toEpochDay() > date2.toEpochDay()}. + * This is equivalent to using {@code date1.toEpochDay() > date2.toEpochDay()}. * <p> * This default implementation performs the comparison based on the epoch-day. * @@ -733,7 +733,7 @@ * only compares the underlying date and not the chronology. * This allows dates in different calendar systems to be compared based * on the time-line position. - * This is equivalent to using {@code date1.toEpochDay() < date2.toEpochDay()}. + * This is equivalent to using {@code date1.toEpochDay() < date2.toEpochDay()}. * <p> * This default implementation performs the comparison based on the epoch-day. *
--- a/src/share/classes/java/util/zip/Deflater.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/util/zip/Deflater.java Thu Oct 29 17:12:06 2015 -0700 @@ -318,7 +318,9 @@ * should be called in order to provide more input */ public boolean needsInput() { - return len <= 0; + synchronized (zsRef) { + return len <= 0; + } } /**
--- a/src/share/classes/java/util/zip/ZStreamRef.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/util/zip/ZStreamRef.java Thu Oct 29 17:12:06 2015 -0700 @@ -31,7 +31,7 @@ class ZStreamRef { - private long address; + private volatile long address; ZStreamRef (long address) { this.address = address; }
--- a/src/share/classes/java/util/zip/ZipFile.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/java/util/zip/ZipFile.java Thu Oct 29 17:12:06 2015 -0700 @@ -58,7 +58,7 @@ */ public class ZipFile implements ZipConstants, Closeable { - private long jzfile; // address of jzfile data + private long jzfile; // address of jzfile data private final String name; // zip file name private final int total; // total number of entries private final boolean locsig; // if zip file starts with LOCSIG (usually true) @@ -685,7 +685,7 @@ * (possibly compressed) zip file entry. */ private class ZipFileInputStream extends InputStream { - private volatile boolean closeRequested = false; + private volatile boolean zfisCloseRequested = false; protected long jzentry; // address of jzentry data private long pos; // current position within entry data protected long rem; // number of remaining bytes within entry @@ -712,6 +712,7 @@ len = (int) rem; } + // Check if ZipFile open ensureOpenOrZipException(); len = ZipFile.read(ZipFile.this.jzfile, jzentry, pos, b, off, len); @@ -755,9 +756,9 @@ } public void close() { - if (closeRequested) + if (zfisCloseRequested) return; - closeRequested = true; + zfisCloseRequested = true; rem = 0; synchronized (ZipFile.this) {
--- a/src/share/classes/javax/swing/event/ListSelectionEvent.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/javax/swing/event/ListSelectionEvent.java Thu Oct 29 17:12:06 2015 -0700 @@ -78,7 +78,7 @@ /** * Returns the index of the first row whose selection may have changed. - * {@code getFirstIndex() <= getLastIndex()} + * {@code getFirstIndex() <= getLastIndex()} * * @return the first row whose selection value may have changed, * where zero is the first row @@ -87,7 +87,7 @@ /** * Returns the index of the last row whose selection may have changed. - * {@code getLastIndex() >= getFirstIndex()} + * {@code getLastIndex() >= getFirstIndex()} * * @return the last row whose selection value may have changed, * where zero is the first row
--- a/src/share/classes/sun/applet/AppletPanel.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/applet/AppletPanel.java Thu Oct 29 17:12:06 2015 -0700 @@ -682,12 +682,7 @@ if (toFocus != null) { if (parent instanceof EmbeddedFrame) { - // JDK-8056915: Try to request focus to the embedder first and - // activate the embedded frame through it - if (!((EmbeddedFrame) parent).requestFocusToEmbedder()) { - // Otherwise activate the embedded frame directly - ((EmbeddedFrame) parent).synthesizeWindowActivation(true); - } + ((EmbeddedFrame) parent).synthesizeWindowActivation(true); } // EmbeddedFrame might have focus before the applet was added. // Thus after its activation the most recent focus owner will be
--- a/src/share/classes/sun/awt/EmbeddedFrame.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/awt/EmbeddedFrame.java Thu Oct 29 17:12:06 2015 -0700 @@ -361,15 +361,6 @@ public void synthesizeWindowActivation(boolean doActivate) {} /** - * Requests the focus to the embedder. - * - * @return {@code true} if focus request was successful, and {@code false} otherwise. - */ - public boolean requestFocusToEmbedder() { - return false; - } - - /** * Moves this embedded frame to a new location. The top-left corner of * the new location is specified by the <code>x</code> and <code>y</code> * parameters relative to the native parent component.
--- a/src/share/classes/sun/font/CompositeFont.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/font/CompositeFont.java Thu Oct 29 17:12:06 2015 -0700 @@ -71,6 +71,13 @@ } else { numSlots = componentNames.length; } + /* We will limit the number of slots to 254. + * We store the slot for a glyph id in a byte and we may use one slot + * for an EUDC font, and we may also create a composite + * using this composite as a backup for a physical font. + * So we want to leave space for the two additional slots. + */ + numSlots = (numSlots <= 254) ? numSlots : 254; /* Only the first "numMetricsSlots" slots are used for font metrics. * the rest are considered "fallback" slots".
--- a/src/share/classes/sun/font/FileFontStrike.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/font/FileFontStrike.java Thu Oct 29 17:12:06 2015 -0700 @@ -420,14 +420,13 @@ /* The following method is called from CompositeStrike as a special case. */ - private static final int SLOTZEROMAX = 0xffffff; int getSlot0GlyphImagePtrs(int[] glyphCodes, long[] images, int len) { int convertedCnt = 0; for (int i=0; i<len; i++) { int glyphCode = glyphCodes[i]; - if (glyphCode >= SLOTZEROMAX) { + if (glyphCode >>> 24 != 0) { return convertedCnt; } else { convertedCnt++;
--- a/src/share/classes/sun/invoke/util/BytecodeName.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/invoke/util/BytecodeName.java Thu Oct 29 17:12:06 2015 -0700 @@ -295,7 +295,7 @@ * (The safe name might possibly be mangled to hide further dangerous characters.) * For example, the qualified class name {@code java/lang/String} * will be parsed into the array {@code {"java", '/', "lang", '/', "String"}}. - * The name {@code <init>} will be parsed into { '<', "init", '>'}} + * The name {@code <init>} will be parsed into {@code {'<', "init", '>'}}. * The name {@code foo/bar$:baz} will be parsed into * {@code {"foo", '/', "bar", '$', ':', "baz"}}. * The name {@code ::\=:foo:\=bar\!baz} will be parsed into
--- a/src/share/classes/sun/management/ThreadImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/management/ThreadImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -165,6 +165,10 @@ "Invalid maxDepth parameter: " + maxDepth); } + // ids has been verified to be non-null + // an empty array of ids should return an empty array of ThreadInfos + if (ids.length == 0) return new ThreadInfo[0]; + Util.checkMonitorAccess(); ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls @@ -436,6 +440,10 @@ boolean lockedMonitors, boolean lockedSynchronizers) { verifyThreadIds(ids); + // ids has been verified to be non-null + // an empty array of ids should return an empty array of ThreadInfos + if (ids.length == 0) return new ThreadInfo[0]; + verifyDumpThreads(lockedMonitors, lockedSynchronizers); return dumpThreads0(ids, lockedMonitors, lockedSynchronizers); }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/share/classes/sun/misc/JavaLangRefAccess.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.misc; + +public interface JavaLangRefAccess { + + /** + * Help ReferenceHandler thread process next pending + * {@link java.lang.ref.Reference} + * + * @return {@code true} if there was a pending reference and it + * was enqueue-ed or {@code false} if there was no + * pending reference + */ + boolean tryHandlePendingReference(); +}
--- a/src/share/classes/sun/misc/SharedSecrets.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/misc/SharedSecrets.java Thu Oct 29 17:12:06 2015 -0700 @@ -45,6 +45,7 @@ private static final Unsafe unsafe = Unsafe.getUnsafe(); private static JavaUtilJarAccess javaUtilJarAccess; private static JavaLangAccess javaLangAccess; + private static JavaLangRefAccess javaLangRefAccess; private static JavaIOAccess javaIOAccess; private static JavaNetAccess javaNetAccess; private static JavaNetHttpCookieAccess javaNetHttpCookieAccess; @@ -76,6 +77,14 @@ return javaLangAccess; } + public static void setJavaLangRefAccess(JavaLangRefAccess jlra) { + javaLangRefAccess = jlra; + } + + public static JavaLangRefAccess getJavaLangRefAccess() { + return javaLangRefAccess; + } + public static void setJavaNetAccess(JavaNetAccess jna) { javaNetAccess = jna; }
--- a/src/share/classes/sun/net/util/IPAddressUtil.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/net/util/IPAddressUtil.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -44,6 +44,7 @@ long tmpValue = 0; int currByte = 0; + boolean newOctet = true; int len = src.length(); if (len == 0 || len > 15) { @@ -77,11 +78,12 @@ for (int i = 0; i < len; i++) { char c = src.charAt(i); if (c == '.') { - if (tmpValue < 0 || tmpValue > 0xff || currByte == 3) { + if (newOctet || tmpValue < 0 || tmpValue > 0xff || currByte == 3) { return null; } res[currByte++] = (byte) (tmpValue & 0xff); tmpValue = 0; + newOctet = true; } else { int digit = Character.digit(c, 10); if (digit < 0) { @@ -89,9 +91,10 @@ } tmpValue *= 10; tmpValue += digit; + newOctet = false; } } - if (tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) { + if (newOctet || tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) { return null; } switch (currByte) {
--- a/src/share/classes/sun/nio/ch/FileChannelImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/nio/ch/FileChannelImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -328,6 +328,7 @@ int rv = -1; long p = -1; int ti = -1; + long rp = -1; try { begin(); ti = threads.add(); @@ -363,8 +364,8 @@ if (p > newSize) p = newSize; do { - rv = (int)position0(fd, p); - } while ((rv == IOStatus.INTERRUPTED) && isOpen()); + rp = position0(fd, p); + } while ((rp == IOStatus.INTERRUPTED) && isOpen()); return this; } finally { threads.remove(ti);
--- a/src/share/classes/sun/security/provider/KeyStoreDelegator.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/security/provider/KeyStoreDelegator.java Thu Oct 29 17:12:06 2015 -0700 @@ -216,57 +216,55 @@ } else { // First try the primary keystore then try the secondary keystore - try (InputStream bufferedStream = new BufferedInputStream(stream)) { - bufferedStream.mark(Integer.MAX_VALUE); + InputStream bufferedStream = new BufferedInputStream(stream); + bufferedStream.mark(Integer.MAX_VALUE); + try { + keystore = primaryKeyStore.newInstance(); + type = primaryType; + keystore.engineLoad(bufferedStream, password); + + } catch (Exception e) { + + // incorrect password + if (e instanceof IOException && + e.getCause() instanceof UnrecoverableKeyException) { + throw (IOException)e; + } try { - keystore = primaryKeyStore.newInstance(); - type = primaryType; + keystore = secondaryKeyStore.newInstance(); + type = secondaryType; + bufferedStream.reset(); keystore.engineLoad(bufferedStream, password); - } catch (Exception e) { - - // incorrect password - if (e instanceof IOException && - e.getCause() instanceof UnrecoverableKeyException) { - throw (IOException)e; + if (debug != null) { + debug.println("WARNING: switching from " + + primaryType + " to " + secondaryType + + " keystore file format has altered the " + + "keystore security level"); } - try { - keystore = secondaryKeyStore.newInstance(); - type = secondaryType; - bufferedStream.reset(); - keystore.engineLoad(bufferedStream, password); + } catch (InstantiationException | + IllegalAccessException e2) { + // can safely ignore - if (debug != null) { - debug.println("WARNING: switching from " + - primaryType + " to " + secondaryType + - " keystore file format has altered the " + - "keystore security level"); - } - - } catch (InstantiationException | - IllegalAccessException e2) { - // can safely ignore + } catch (IOException | + NoSuchAlgorithmException | + CertificateException e3) { - } catch (IOException | - NoSuchAlgorithmException | - CertificateException e3) { - - // incorrect password - if (e3 instanceof IOException && - e3.getCause() instanceof - UnrecoverableKeyException) { - throw (IOException)e3; - } - // rethrow the outer exception - if (e instanceof IOException) { - throw (IOException)e; - } else if (e instanceof CertificateException) { - throw (CertificateException)e; - } else if (e instanceof NoSuchAlgorithmException) { - throw (NoSuchAlgorithmException)e; - } + // incorrect password + if (e3 instanceof IOException && + e3.getCause() instanceof + UnrecoverableKeyException) { + throw (IOException)e3; + } + // rethrow the outer exception + if (e instanceof IOException) { + throw (IOException)e; + } else if (e instanceof CertificateException) { + throw (CertificateException)e; + } else if (e instanceof NoSuchAlgorithmException) { + throw (NoSuchAlgorithmException)e; } } }
--- a/src/share/classes/sun/security/provider/certpath/Builder.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/security/provider/certpath/Builder.java Thu Oct 29 17:12:06 2015 -0700 @@ -102,8 +102,8 @@ /** * Verifies whether the input certificate completes the path. - * When building forward, a trust anchor will complete the path. - * When building reverse, the target certificate will complete the path. + * When building in the forward direction, a trust anchor will + * complete the path. * * @param cert the certificate to test * @return a boolean value indicating whether the cert completes the path.
--- a/src/share/classes/sun/security/provider/certpath/PKIX.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/security/provider/certpath/PKIX.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,7 +25,6 @@ package sun.security.provider.certpath; import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; import java.security.PublicKey; import java.security.cert.*; import java.security.interfaces.DSAPublicKey; @@ -194,7 +193,6 @@ static class BuilderParams extends ValidatorParams { private PKIXBuilderParameters params; - private boolean buildForward = true; private List<CertStore> stores; private X500Principal targetSubject; @@ -213,10 +211,6 @@ + "targetCertConstraints parameter must be an " + "X509CertSelector"); } - if (params instanceof SunCertPathBuilderParameters) { - buildForward = - ((SunCertPathBuilderParameters)params).getBuildForward(); - } this.params = params; this.targetSubject = getTargetSubject( certStores(), (X509CertSelector)targetCertConstraints()); @@ -230,7 +224,6 @@ return stores; } int maxPathLength() { return params.getMaxPathLength(); } - boolean buildForward() { return buildForward; } PKIXBuilderParameters params() { return params; } X500Principal targetSubject() { return targetSubject; }
--- a/src/share/classes/sun/security/provider/certpath/ReverseBuilder.java Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,551 +0,0 @@ -/* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.Principal; -import java.security.cert.CertificateException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.PKIXBuilderParameters; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXReason; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.security.cert.X509CertSelector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.LinkedList; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.PKIX.BuilderParams; -import sun.security.util.Debug; -import sun.security.x509.Extension; -import static sun.security.x509.PKIXExtensions.*; -import sun.security.x509.X500Name; -import sun.security.x509.X509CertImpl; -import sun.security.x509.PolicyMappingsExtension; - -/** - * This class represents a reverse builder, which is able to retrieve - * matching certificates from CertStores and verify a particular certificate - * against a ReverseState. - * - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ - -class ReverseBuilder extends Builder { - - private Debug debug = Debug.getInstance("certpath"); - - private final Set<String> initPolicies; - - /** - * Initialize the builder with the input parameters. - * - * @param params the parameter set used to build a certification path - */ - ReverseBuilder(BuilderParams buildParams) { - super(buildParams); - - Set<String> initialPolicies = buildParams.initialPolicies(); - initPolicies = new HashSet<String>(); - if (initialPolicies.isEmpty()) { - // if no initialPolicies are specified by user, set - // initPolicies to be anyPolicy by default - initPolicies.add(PolicyChecker.ANY_POLICY); - } else { - initPolicies.addAll(initialPolicies); - } - } - - /** - * Retrieves all certs from the specified CertStores that satisfy the - * requirements specified in the parameters and the current - * PKIX state (name constraints, policy constraints, etc). - * - * @param currentState the current state. - * Must be an instance of <code>ReverseState</code> - * @param certStores list of CertStores - */ - @Override - Collection<X509Certificate> getMatchingCerts - (State currState, List<CertStore> certStores) - throws CertStoreException, CertificateException, IOException - { - ReverseState currentState = (ReverseState) currState; - - if (debug != null) - debug.println("In ReverseBuilder.getMatchingCerts."); - - /* - * The last certificate could be an EE or a CA certificate - * (we may be building a partial certification path or - * establishing trust in a CA). - * - * Try the EE certs before the CA certs. It will be more - * common to build a path to an end entity. - */ - Collection<X509Certificate> certs = - getMatchingEECerts(currentState, certStores); - certs.addAll(getMatchingCACerts(currentState, certStores)); - - return certs; - } - - /* - * Retrieves all end-entity certificates which satisfy constraints - * and requirements specified in the parameters and PKIX state. - */ - private Collection<X509Certificate> getMatchingEECerts - (ReverseState currentState, List<CertStore> certStores) - throws CertStoreException, CertificateException, IOException { - - /* - * Compose a CertSelector to filter out - * certs which do not satisfy requirements. - * - * First, retrieve clone of current target cert constraints, and - * then add more selection criteria based on current validation state. - */ - X509CertSelector sel = (X509CertSelector) targetCertConstraints.clone(); - - /* - * Match on issuer (subject of previous cert) - */ - sel.setIssuer(currentState.subjectDN); - - /* - * Match on certificate validity date. - */ - sel.setCertificateValid(buildParams.date()); - - /* - * Policy processing optimizations - */ - if (currentState.explicitPolicy == 0) - sel.setPolicy(getMatchingPolicies()); - - /* - * If previous cert has a subject key identifier extension, - * use it to match on authority key identifier extension. - */ - /*if (currentState.subjKeyId != null) { - AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension( - (KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID), - null, null); - sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue()); - }*/ - - /* - * Require EE certs - */ - sel.setBasicConstraints(-2); - - /* Retrieve matching certs from CertStores */ - HashSet<X509Certificate> eeCerts = new HashSet<>(); - addMatchingCerts(sel, certStores, eeCerts, true); - - if (debug != null) { - debug.println("ReverseBuilder.getMatchingEECerts got " - + eeCerts.size() + " certs."); - } - return eeCerts; - } - - /* - * Retrieves all CA certificates which satisfy constraints - * and requirements specified in the parameters and PKIX state. - */ - private Collection<X509Certificate> getMatchingCACerts - (ReverseState currentState, List<CertStore> certStores) - throws CertificateException, CertStoreException, IOException { - - /* - * Compose a CertSelector to filter out - * certs which do not satisfy requirements. - */ - X509CertSelector sel = new X509CertSelector(); - - /* - * Match on issuer (subject of previous cert) - */ - sel.setIssuer(currentState.subjectDN); - - /* - * Match on certificate validity date. - */ - sel.setCertificateValid(buildParams.date()); - - /* - * Match on target subject name (checks that current cert's - * name constraints permit it to certify target). - * (4 is the integer type for DIRECTORY name). - */ - byte[] subject = targetCertConstraints.getSubjectAsBytes(); - if (subject != null) { - sel.addPathToName(4, subject); - } else { - X509Certificate cert = targetCertConstraints.getCertificate(); - if (cert != null) { - sel.addPathToName(4, - cert.getSubjectX500Principal().getEncoded()); - } - } - - /* - * Policy processing optimizations - */ - if (currentState.explicitPolicy == 0) - sel.setPolicy(getMatchingPolicies()); - - /* - * If previous cert has a subject key identifier extension, - * use it to match on authority key identifier extension. - */ - /*if (currentState.subjKeyId != null) { - AuthorityKeyIdentifierExtension authKeyId = new AuthorityKeyIdentifierExtension( - (KeyIdentifier) currentState.subjKeyId.get(SubjectKeyIdentifierExtension.KEY_ID), - null, null); - sel.setAuthorityKeyIdentifier(authKeyId.getExtensionValue()); - }*/ - - /* - * Require CA certs - */ - sel.setBasicConstraints(0); - - /* Retrieve matching certs from CertStores */ - ArrayList<X509Certificate> reverseCerts = new ArrayList<>(); - addMatchingCerts(sel, certStores, reverseCerts, true); - - /* Sort remaining certs using name constraints */ - Collections.sort(reverseCerts, new PKIXCertComparator()); - - if (debug != null) - debug.println("ReverseBuilder.getMatchingCACerts got " + - reverseCerts.size() + " certs."); - return reverseCerts; - } - - /* - * This inner class compares 2 PKIX certificates according to which - * should be tried first when building a path to the target. For - * now, the algorithm is to look at name constraints in each cert and those - * which constrain the path closer to the target should be - * ranked higher. Later, we may want to consider other components, - * such as key identifiers. - */ - class PKIXCertComparator implements Comparator<X509Certificate> { - - private Debug debug = Debug.getInstance("certpath"); - - @Override - public int compare(X509Certificate cert1, X509Certificate cert2) { - - /* - * if either cert certifies the target, always - * put at head of list. - */ - X500Principal targetSubject = buildParams.targetSubject(); - if (cert1.getSubjectX500Principal().equals(targetSubject)) { - return -1; - } - if (cert2.getSubjectX500Principal().equals(targetSubject)) { - return 1; - } - - int targetDist1; - int targetDist2; - try { - X500Name targetSubjectName = X500Name.asX500Name(targetSubject); - targetDist1 = Builder.targetDistance( - null, cert1, targetSubjectName); - targetDist2 = Builder.targetDistance( - null, cert2, targetSubjectName); - } catch (IOException e) { - if (debug != null) { - debug.println("IOException in call to Builder.targetDistance"); - e.printStackTrace(); - } - throw new ClassCastException - ("Invalid target subject distinguished name"); - } - - if (targetDist1 == targetDist2) - return 0; - - if (targetDist1 == -1) - return 1; - - if (targetDist1 < targetDist2) - return -1; - - return 1; - } - } - - /** - * Verifies a matching certificate. - * - * This method executes any of the validation steps in the PKIX path validation - * algorithm which were not satisfied via filtering out non-compliant - * certificates with certificate matching rules. - * - * If the last certificate is being verified (the one whose subject - * matches the target subject, then the steps in Section 6.1.4 of the - * Certification Path Validation algorithm are NOT executed, - * regardless of whether or not the last cert is an end-entity - * cert or not. This allows callers to certify CA certs as - * well as EE certs. - * - * @param cert the certificate to be verified - * @param currentState the current state against which the cert is verified - * @param certPathList the certPathList generated thus far - */ - @Override - void verifyCert(X509Certificate cert, State currState, - List<X509Certificate> certPathList) - throws GeneralSecurityException - { - if (debug != null) { - debug.println("ReverseBuilder.verifyCert(SN: " - + Debug.toHexString(cert.getSerialNumber()) - + "\n Subject: " + cert.getSubjectX500Principal() + ")"); - } - - ReverseState currentState = (ReverseState) currState; - - /* we don't perform any validation of the trusted cert */ - if (currentState.isInitial()) { - return; - } - - // Don't bother to verify untrusted certificate more. - currentState.untrustedChecker.check(cert, - Collections.<String>emptySet()); - - /* - * check for looping - abort a loop if - * ((we encounter the same certificate twice) AND - * ((policyMappingInhibited = true) OR (no policy mapping - * extensions can be found between the occurrences of the same - * certificate))) - * in order to facilitate the check to see if there are - * any policy mapping extensions found between the occurrences - * of the same certificate, we reverse the certpathlist first - */ - if ((certPathList != null) && (!certPathList.isEmpty())) { - List<X509Certificate> reverseCertList = new ArrayList<>(); - for (X509Certificate c : certPathList) { - reverseCertList.add(0, c); - } - - boolean policyMappingFound = false; - for (X509Certificate cpListCert : reverseCertList) { - X509CertImpl cpListCertImpl = X509CertImpl.toImpl(cpListCert); - PolicyMappingsExtension policyMappingsExt = - cpListCertImpl.getPolicyMappingsExtension(); - if (policyMappingsExt != null) { - policyMappingFound = true; - } - if (debug != null) - debug.println("policyMappingFound = " + policyMappingFound); - if (cert.equals(cpListCert)) { - if ((buildParams.policyMappingInhibited()) || - (!policyMappingFound)){ - if (debug != null) - debug.println("loop detected!!"); - throw new CertPathValidatorException("loop detected"); - } - } - } - } - - /* check if target cert */ - boolean finalCert = cert.getSubjectX500Principal().equals(buildParams.targetSubject()); - - /* check if CA cert */ - boolean caCert = (cert.getBasicConstraints() != -1 ? true : false); - - /* if there are more certs to follow, verify certain constraints */ - if (!finalCert) { - - /* check if CA cert */ - if (!caCert) - throw new CertPathValidatorException("cert is NOT a CA cert"); - - /* If the certificate was not self-issued, verify that - * remainingCerts is greater than zero - */ - if ((currentState.remainingCACerts <= 0) && !X509CertImpl.isSelfIssued(cert)) { - throw new CertPathValidatorException - ("pathLenConstraint violated, path too long", null, - null, -1, PKIXReason.PATH_TOO_LONG); - } - - /* - * Check keyUsage extension (only if CA cert and not final cert) - */ - KeyChecker.verifyCAKeyUsage(cert); - - } else { - - /* - * If final cert, check that it satisfies specified target - * constraints - */ - if (targetCertConstraints.match(cert) == false) { - throw new CertPathValidatorException("target certificate " + - "constraints check failed"); - } - } - - /* - * Check revocation. - */ - if (buildParams.revocationEnabled() && currentState.revChecker != null) { - currentState.revChecker.check(cert, Collections.<String>emptySet()); - } - - /* Check name constraints if this is not a self-issued cert */ - if (finalCert || !X509CertImpl.isSelfIssued(cert)){ - if (currentState.nc != null) { - try { - if (!currentState.nc.verify(cert)){ - throw new CertPathValidatorException - ("name constraints check failed", null, null, -1, - PKIXReason.INVALID_NAME); - } - } catch (IOException ioe) { - throw new CertPathValidatorException(ioe); - } - } - } - - /* - * Check policy - */ - X509CertImpl certImpl = X509CertImpl.toImpl(cert); - currentState.rootNode = PolicyChecker.processPolicies - (currentState.certIndex, initPolicies, - currentState.explicitPolicy, currentState.policyMapping, - currentState.inhibitAnyPolicy, - buildParams.policyQualifiersRejected(), currentState.rootNode, - certImpl, finalCert); - - /* - * Check CRITICAL private extensions - */ - Set<String> unresolvedCritExts = cert.getCriticalExtensionOIDs(); - if (unresolvedCritExts == null) { - unresolvedCritExts = Collections.<String>emptySet(); - } - - /* - * Check that the signature algorithm is not disabled. - */ - currentState.algorithmChecker.check(cert, unresolvedCritExts); - - for (PKIXCertPathChecker checker : currentState.userCheckers) { - checker.check(cert, unresolvedCritExts); - } - - /* - * Look at the remaining extensions and remove any ones we have - * already checked. If there are any left, throw an exception! - */ - if (!unresolvedCritExts.isEmpty()) { - unresolvedCritExts.remove(BasicConstraints_Id.toString()); - unresolvedCritExts.remove(NameConstraints_Id.toString()); - unresolvedCritExts.remove(CertificatePolicies_Id.toString()); - unresolvedCritExts.remove(PolicyMappings_Id.toString()); - unresolvedCritExts.remove(PolicyConstraints_Id.toString()); - unresolvedCritExts.remove(InhibitAnyPolicy_Id.toString()); - unresolvedCritExts.remove(SubjectAlternativeName_Id.toString()); - unresolvedCritExts.remove(KeyUsage_Id.toString()); - unresolvedCritExts.remove(ExtendedKeyUsage_Id.toString()); - - if (!unresolvedCritExts.isEmpty()) - throw new CertPathValidatorException - ("Unrecognized critical extension(s)", null, null, -1, - PKIXReason.UNRECOGNIZED_CRIT_EXT); - } - - /* - * Check signature. - */ - if (buildParams.sigProvider() != null) { - cert.verify(currentState.pubKey, buildParams.sigProvider()); - } else { - cert.verify(currentState.pubKey); - } - } - - /** - * Verifies whether the input certificate completes the path. - * This checks whether the cert is the target certificate. - * - * @param cert the certificate to test - * @return a boolean value indicating whether the cert completes the path. - */ - @Override - boolean isPathCompleted(X509Certificate cert) { - return cert.getSubjectX500Principal().equals(buildParams.targetSubject()); - } - - /** Adds the certificate to the certPathList - * - * @param cert the certificate to be added - * @param certPathList the certification path list - */ - @Override - void addCertToPath(X509Certificate cert, - LinkedList<X509Certificate> certPathList) { - certPathList.addLast(cert); - } - - /** Removes final certificate from the certPathList - * - * @param certPathList the certification path list - */ - @Override - void removeFinalCertFromPath(LinkedList<X509Certificate> certPathList) { - certPathList.removeLast(); - } -}
--- a/src/share/classes/sun/security/provider/certpath/ReverseState.java Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,406 +0,0 @@ -/* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.io.IOException; -import java.security.PublicKey; -import java.security.cert.CertificateException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXRevocationChecker; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.PKIX.BuilderParams; -import sun.security.util.Debug; -import sun.security.x509.NameConstraintsExtension; -import sun.security.x509.SubjectKeyIdentifierExtension; -import sun.security.x509.X509CertImpl; - -/** - * A specification of a reverse PKIX validation state - * which is initialized by each build and updated each time a - * certificate is added to the current path. - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ - -class ReverseState implements State { - - private static final Debug debug = Debug.getInstance("certpath"); - - /* The subject DN of the last cert in the path */ - X500Principal subjectDN; - - /* The subject public key of the last cert */ - PublicKey pubKey; - - /* The subject key identifier extension (if any) of the last cert */ - SubjectKeyIdentifierExtension subjKeyId; - - /* The PKIX constrained/excluded subtrees state variable */ - NameConstraintsExtension nc; - - /* The PKIX explicit policy, policy mapping, and inhibit_any-policy - state variables */ - int explicitPolicy; - int policyMapping; - int inhibitAnyPolicy; - int certIndex; - PolicyNodeImpl rootNode; - - /* The number of remaining CA certs which may follow in the path. - * -1: previous cert was an EE cert - * 0: only EE certs may follow. - * >0 and <Integer.MAX_VALUE:no more than this number of CA certs may follow - * Integer.MAX_VALUE: unlimited - */ - int remainingCACerts; - - /* The list of user-defined checkers retrieved from the PKIXParameters - * instance */ - ArrayList<PKIXCertPathChecker> userCheckers; - - /* Flag indicating if state is initial (path is just starting) */ - private boolean init = true; - - /* the checker used for revocation status */ - RevocationChecker revChecker; - - /* the algorithm checker */ - AlgorithmChecker algorithmChecker; - - /* the untrusted certificates checker */ - UntrustedChecker untrustedChecker; - - /* the trust anchor used to validate the path */ - TrustAnchor trustAnchor; - - /* Flag indicating if current cert can vouch for the CRL for - * the next cert - */ - boolean crlSign = true; - - /** - * Returns a boolean flag indicating if the state is initial - * (just starting) - * - * @return boolean flag indicating if the state is initial (just starting) - */ - @Override - public boolean isInitial() { - return init; - } - - /** - * Display state for debugging purposes - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("State ["); - sb.append("\n subjectDN of last cert: ").append(subjectDN); - sb.append("\n subjectKeyIdentifier: ").append - (String.valueOf(subjKeyId)); - sb.append("\n nameConstraints: ").append(String.valueOf(nc)); - sb.append("\n certIndex: ").append(certIndex); - sb.append("\n explicitPolicy: ").append(explicitPolicy); - sb.append("\n policyMapping: ").append(policyMapping); - sb.append("\n inhibitAnyPolicy: ").append(inhibitAnyPolicy); - sb.append("\n rootNode: ").append(rootNode); - sb.append("\n remainingCACerts: ").append(remainingCACerts); - sb.append("\n crlSign: ").append(crlSign); - sb.append("\n init: ").append(init); - sb.append("\n]\n"); - return sb.toString(); - } - - /** - * Initialize the state. - * - * @param buildParams builder parameters - */ - public void initState(BuilderParams buildParams) - throws CertPathValidatorException - { - /* - * Initialize number of remainingCACerts. - * Note that -1 maxPathLen implies unlimited. - * 0 implies only an EE cert is acceptable. - */ - int maxPathLen = buildParams.maxPathLength(); - remainingCACerts = (maxPathLen == -1) ? Integer.MAX_VALUE - : maxPathLen; - - /* Initialize explicit policy state variable */ - if (buildParams.explicitPolicyRequired()) { - explicitPolicy = 0; - } else { - // unconstrained if maxPathLen is -1, - // otherwise, we want to initialize this to the value of the - // longest possible path + 1 (i.e. maxpathlen + finalcert + 1) - explicitPolicy = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize policy mapping state variable */ - if (buildParams.policyMappingInhibited()) { - policyMapping = 0; - } else { - policyMapping = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize inhibit any policy state variable */ - if (buildParams.anyPolicyInhibited()) { - inhibitAnyPolicy = 0; - } else { - inhibitAnyPolicy = (maxPathLen == -1) ? maxPathLen : maxPathLen + 2; - } - - /* Initialize certIndex */ - certIndex = 1; - - /* Initialize policy tree */ - Set<String> initExpPolSet = new HashSet<>(1); - initExpPolSet.add(PolicyChecker.ANY_POLICY); - - rootNode = new PolicyNodeImpl(null, PolicyChecker.ANY_POLICY, null, - false, initExpPolSet, false); - - /* - * Initialize each user-defined checker - * Shallow copy the checkers - */ - userCheckers = new ArrayList<>(buildParams.certPathCheckers()); - /* initialize each checker (just in case) */ - for (PKIXCertPathChecker checker : userCheckers) { - checker.init(false); - } - - /* Start by trusting the cert to sign CRLs */ - crlSign = true; - - init = true; - } - - /** - * Update the state with the specified trust anchor. - * - * @param anchor the most-trusted CA - * @param buildParams builder parameters - */ - public void updateState(TrustAnchor anchor, BuilderParams buildParams) - throws CertificateException, IOException, CertPathValidatorException - { - trustAnchor = anchor; - X509Certificate trustedCert = anchor.getTrustedCert(); - if (trustedCert != null) { - updateState(trustedCert); - } else { - X500Principal caName = anchor.getCA(); - updateState(anchor.getCAPublicKey(), caName); - } - - // The user specified AlgorithmChecker and RevocationChecker may not be - // able to set the trust anchor until now. - boolean revCheckerAdded = false; - for (PKIXCertPathChecker checker : userCheckers) { - if (checker instanceof AlgorithmChecker) { - ((AlgorithmChecker)checker).trySetTrustAnchor(anchor); - } else if (checker instanceof PKIXRevocationChecker) { - if (revCheckerAdded) { - throw new CertPathValidatorException( - "Only one PKIXRevocationChecker can be specified"); - } - // if it's our own, initialize it - if (checker instanceof RevocationChecker) { - ((RevocationChecker)checker).init(anchor, buildParams); - } - ((PKIXRevocationChecker)checker).init(false); - revCheckerAdded = true; - } - } - - // only create a RevocationChecker if revocation is enabled and - // a PKIXRevocationChecker has not already been added - if (buildParams.revocationEnabled() && !revCheckerAdded) { - revChecker = new RevocationChecker(anchor, buildParams); - revChecker.init(false); - } - - init = false; - } - - /** - * Update the state. This method is used when the most-trusted CA is - * a trusted public-key and caName, instead of a trusted cert. - * - * @param pubKey the public key of the trusted CA - * @param subjectDN the subject distinguished name of the trusted CA - */ - private void updateState(PublicKey pubKey, X500Principal subjectDN) { - - /* update subject DN */ - this.subjectDN = subjectDN; - - /* update subject public key */ - this.pubKey = pubKey; - } - - /** - * Update the state with the next certificate added to the path. - * - * @param cert the certificate which is used to update the state - */ - public void updateState(X509Certificate cert) - throws CertificateException, IOException, CertPathValidatorException { - - if (cert == null) { - return; - } - - /* update subject DN */ - subjectDN = cert.getSubjectX500Principal(); - - /* check for key needing to inherit alg parameters */ - X509CertImpl icert = X509CertImpl.toImpl(cert); - PublicKey newKey = cert.getPublicKey(); - if (PKIX.isDSAPublicKeyWithoutParams(newKey)) { - newKey = BasicChecker.makeInheritedParamsKey(newKey, pubKey); - } - - /* update subject public key */ - pubKey = newKey; - - /* - * if this is a trusted cert (init == true), then we - * don't update any of the remaining fields - */ - if (init) { - init = false; - return; - } - - /* update subject key identifier */ - subjKeyId = icert.getSubjectKeyIdentifierExtension(); - - /* update crlSign */ - crlSign = RevocationChecker.certCanSignCrl(cert); - - /* update current name constraints */ - if (nc != null) { - nc.merge(icert.getNameConstraintsExtension()); - } else { - nc = icert.getNameConstraintsExtension(); - if (nc != null) { - // Make sure we do a clone here, because we're probably - // going to modify this object later and we don't want to - // be sharing it with a Certificate object! - nc = (NameConstraintsExtension) nc.clone(); - } - } - - /* update policy state variables */ - explicitPolicy = - PolicyChecker.mergeExplicitPolicy(explicitPolicy, icert, false); - policyMapping = - PolicyChecker.mergePolicyMapping(policyMapping, icert); - inhibitAnyPolicy = - PolicyChecker.mergeInhibitAnyPolicy(inhibitAnyPolicy, icert); - certIndex++; - - /* - * Update remaining CA certs - */ - remainingCACerts = - ConstraintsChecker.mergeBasicConstraints(cert, remainingCACerts); - - init = false; - } - - /** - * Returns a boolean flag indicating if a key lacking necessary key - * algorithm parameters has been encountered. - * - * @return boolean flag indicating if key lacking parameters encountered. - */ - @Override - public boolean keyParamsNeeded() { - /* when building in reverse, we immediately get parameters needed - * or else throw an exception - */ - return false; - } - - /* - * Clone current state. The state is cloned as each cert is - * added to the path. This is necessary if backtracking occurs, - * and a prior state needs to be restored. - * - * Note that this is a SMART clone. Not all fields are fully copied, - * because some of them (e.g., subjKeyId) will - * not have their contents modified by subsequent calls to updateState. - */ - @Override - @SuppressWarnings("unchecked") // Safe casts assuming clone() works correctly - public Object clone() { - try { - ReverseState clonedState = (ReverseState) super.clone(); - - /* clone checkers, if cloneable */ - clonedState.userCheckers = - (ArrayList<PKIXCertPathChecker>)userCheckers.clone(); - ListIterator<PKIXCertPathChecker> li = - clonedState.userCheckers.listIterator(); - while (li.hasNext()) { - PKIXCertPathChecker checker = li.next(); - if (checker instanceof Cloneable) { - li.set((PKIXCertPathChecker)checker.clone()); - } - } - - /* make copy of name constraints */ - if (nc != null) { - clonedState.nc = (NameConstraintsExtension) nc.clone(); - } - - /* make copy of policy tree */ - if (rootNode != null) { - clonedState.rootNode = rootNode.copyTree(); - } - - return clonedState; - } catch (CloneNotSupportedException e) { - throw new InternalError(e.toString(), e); - } - } -}
--- a/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java Thu Oct 29 17:12:06 2015 -0700 @@ -35,8 +35,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.LinkedList; import java.util.Set; @@ -47,8 +45,7 @@ import sun.security.util.Debug; /** - * This class is able to build certification paths in either the forward - * or reverse directions. + * This class builds certification paths in the forward direction. * * <p> If successful, it returns a certification path which has successfully * satisfied all the constraints and requirements specified in the @@ -102,10 +99,8 @@ /** * Attempts to build a certification path using the Sun build * algorithm from a trusted anchor(s) to a target subject, which must both - * be specified in the input parameter set. By default, this method will - * attempt to build in the forward direction. In order to build in the - * reverse direction, the caller needs to pass in an instance of - * SunCertPathBuilderParameters with the buildForward flag set to false. + * be specified in the input parameter set. This method will + * attempt to build in the forward direction: from the target to the CA. * * <p>The certification path that is constructed is validated * according to the PKIX specification. @@ -162,11 +157,7 @@ policyTreeResult = null; LinkedList<X509Certificate> certPathList = new LinkedList<>(); try { - if (buildParams.buildForward()) { - buildForward(adjList, certPathList, searchAllCertStores); - } else { - buildReverse(adjList, certPathList); - } + buildForward(adjList, certPathList, searchAllCertStores); } catch (GeneralSecurityException | IOException e) { if (debug != null) { debug.println("SunCertPathBuilder.engineBuild() exception in " @@ -210,81 +201,6 @@ } /* - * Private build reverse method. - */ - private void buildReverse(List<List<Vertex>> adjacencyList, - LinkedList<X509Certificate> certPathList) - throws GeneralSecurityException, IOException - { - if (debug != null) { - debug.println("SunCertPathBuilder.buildReverse()..."); - debug.println("SunCertPathBuilder.buildReverse() InitialPolicies: " - + buildParams.initialPolicies()); - } - - ReverseState currentState = new ReverseState(); - /* Initialize adjacency list */ - adjacencyList.clear(); - adjacencyList.add(new LinkedList<Vertex>()); - - /* - * Perform a search using each trust anchor, until a valid - * path is found - */ - Iterator<TrustAnchor> iter = buildParams.trustAnchors().iterator(); - while (iter.hasNext()) { - TrustAnchor anchor = iter.next(); - - /* check if anchor satisfies target constraints */ - if (anchorIsTarget(anchor, buildParams.targetCertConstraints())) { - this.trustAnchor = anchor; - this.pathCompleted = true; - this.finalPublicKey = anchor.getTrustedCert().getPublicKey(); - break; - } - - // skip anchor if it contains a DSA key with no DSA params - X509Certificate trustedCert = anchor.getTrustedCert(); - PublicKey pubKey = trustedCert != null ? trustedCert.getPublicKey() - : anchor.getCAPublicKey(); - - if (PKIX.isDSAPublicKeyWithoutParams(pubKey)) { - continue; - } - - /* Initialize current state */ - currentState.initState(buildParams); - currentState.updateState(anchor, buildParams); - - currentState.algorithmChecker = new AlgorithmChecker(anchor); - currentState.untrustedChecker = new UntrustedChecker(); - try { - depthFirstSearchReverse(null, currentState, - new ReverseBuilder(buildParams), - adjacencyList, certPathList); - } catch (GeneralSecurityException | IOException e) { - // continue on error if more anchors to try - if (iter.hasNext()) - continue; - else - throw e; - } - - // break out of loop if search is successful - if (pathCompleted) { - break; - } - } - - if (debug != null) { - debug.println("SunCertPathBuilder.buildReverse() returned from " - + "depthFirstSearchReverse()"); - debug.println("SunCertPathBuilder.buildReverse() " - + "certPathList.size: " + certPathList.size()); - } - } - - /* * Private build forward method. */ private void buildForward(List<List<Vertex>> adjacencyList, @@ -632,147 +548,6 @@ } /* - * This method performs a depth first search for a certification - * path while building reverse which meets the requirements set in - * the parameters object. - * It uses an adjacency list to store all certificates which were - * tried (i.e. at one time added to the path - they may not end up in - * the final path if backtracking occurs). This information can - * be used later to debug or demo the build. - * - * See "Data Structure and Algorithms, by Aho, Hopcroft, and Ullman" - * for an explanation of the DFS algorithm. - * - * @param dN the distinguished name being currently searched for certs - * @param currentState the current PKIX validation state - */ - private void depthFirstSearchReverse(X500Principal dN, - ReverseState currentState, - ReverseBuilder builder, - List<List<Vertex>> adjList, - LinkedList<X509Certificate> cpList) - throws GeneralSecurityException, IOException - { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse(" + dN - + ", " + currentState.toString() + ")"); - - /* - * Find all the certificates issued by dN which - * satisfy the PKIX certification path constraints. - */ - Collection<X509Certificate> certs = - builder.getMatchingCerts(currentState, buildParams.certStores()); - List<Vertex> vertices = addVertices(certs, adjList); - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse(): " - + "certs.size=" + vertices.size()); - - /* - * For each cert in the collection, verify anything - * that hasn't been checked yet (signature, revocation, etc) - * and check for loops. Call depthFirstSearchReverse() - * recursively for each good cert. - */ - for (Vertex vertex : vertices) { - /** - * Restore state to currentState each time through the loop. - * This is important because some of the user-defined - * checkers modify the state, which MUST be restored if - * the cert eventually fails to lead to the target and - * the next matching cert is tried. - */ - ReverseState nextState = (ReverseState) currentState.clone(); - X509Certificate cert = vertex.getCertificate(); - try { - builder.verifyCert(cert, nextState, cpList); - } catch (GeneralSecurityException gse) { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": validation failed: " + gse); - vertex.setThrowable(gse); - continue; - } - - /* - * Certificate is good, add it to the path (if it isn't a - * self-signed cert) and update state - */ - if (!currentState.isInitial()) - builder.addCertToPath(cert, cpList); - // save trust anchor - this.trustAnchor = currentState.trustAnchor; - - /* - * Check if path is completed, return ASAP if so. - */ - if (builder.isPathCompleted(cert)) { - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": path completed!"); - pathCompleted = true; - - PolicyNodeImpl rootNode = nextState.rootNode; - - if (rootNode == null) - policyTreeResult = null; - else { - policyTreeResult = rootNode.copyTree(); - ((PolicyNodeImpl)policyTreeResult).setImmutable(); - } - - /* - * Extract and save the final target public key - */ - finalPublicKey = cert.getPublicKey(); - if (PKIX.isDSAPublicKeyWithoutParams(finalPublicKey)) { - finalPublicKey = - BasicChecker.makeInheritedParamsKey - (finalPublicKey, currentState.pubKey); - } - - return; - } - - /* Update the PKIX state */ - nextState.updateState(cert); - - /* - * Append an entry for cert in adjacency list and - * set index for current vertex. - */ - adjList.add(new LinkedList<Vertex>()); - vertex.setIndex(adjList.size() - 1); - - /* recursively search for matching certs at next dN */ - depthFirstSearchReverse(cert.getSubjectX500Principal(), nextState, - builder, adjList, cpList); - - /* - * If path has been completed, return ASAP! - */ - if (pathCompleted) { - return; - } else { - /* - * If we get here, it means we have searched all possible - * certs issued by the dN w/o finding any matching certs. This - * means we have to backtrack to the previous cert in the path - * and try some other paths. - */ - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse()" - + ": backtracking"); - if (!currentState.isInitial()) - builder.removeFinalCertFromPath(cpList); - } - } - if (debug != null) - debug.println("SunCertPathBuilder.depthFirstSearchReverse() all " - + "certs in this adjacency list checked"); - } - - /* * Adds a collection of matching certificates to the * adjacency list. */
--- a/src/share/classes/sun/security/provider/certpath/SunCertPathBuilderParameters.java Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package sun.security.provider.certpath; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.*; -import java.util.Set; - -/** - * This class specifies the set of parameters used as input for the Sun - * certification path build algorithm. It is identical to PKIXBuilderParameters - * with the addition of a <code>buildForward</code> parameter which allows - * the caller to specify whether or not the path should be constructed in - * the forward direction. - * - * The default for the <code>buildForward</code> parameter is - * true, which means that the build algorithm should construct paths - * from the target subject back to the trusted anchor. - * - * @since 1.4 - * @author Sean Mullan - * @author Yassir Elley - */ -public class SunCertPathBuilderParameters extends PKIXBuilderParameters { - - private boolean buildForward = true; - - /** - * Creates an instance of <code>SunCertPathBuilderParameters</code> with the - * specified parameter values. - * - * @param trustAnchors a <code>Set</code> of <code>TrustAnchor</code>s - * @param targetConstraints a <code>CertSelector</code> specifying the - * constraints on the target certificate - * @throws InvalidAlgorithmParameterException if the specified - * <code>Set</code> is empty <code>(trustAnchors.isEmpty() == true)</code> - * @throws NullPointerException if the specified <code>Set</code> is - * <code>null</code> - * @throws ClassCastException if any of the elements in the <code>Set</code> - * are not of type <code>java.security.cert.TrustAnchor</code> - */ - public SunCertPathBuilderParameters(Set<TrustAnchor> trustAnchors, - CertSelector targetConstraints) throws InvalidAlgorithmParameterException - { - super(trustAnchors, targetConstraints); - setBuildForward(true); - } - - /** - * Creates an instance of <code>SunCertPathBuilderParameters</code> that - * uses the specified <code>KeyStore</code> to populate the set - * of most-trusted CA certificates. - * - * @param keystore A keystore from which the set of most-trusted - * CA certificates will be populated. - * @param targetConstraints a <code>CertSelector</code> specifying the - * constraints on the target certificate - * @throws KeyStoreException if the keystore has not been initialized. - * @throws InvalidAlgorithmParameterException if the keystore does - * not contain at least one trusted certificate entry - * @throws NullPointerException if the keystore is <code>null</code> - */ - public SunCertPathBuilderParameters(KeyStore keystore, - CertSelector targetConstraints) - throws KeyStoreException, InvalidAlgorithmParameterException - { - super(keystore, targetConstraints); - setBuildForward(true); - } - - /** - * Returns the value of the buildForward flag. - * - * @return the value of the buildForward flag - */ - public boolean getBuildForward() { - return this.buildForward; - } - - /** - * Sets the value of the buildForward flag. If true, paths - * are built from the target subject to the trusted anchor. - * If false, paths are built from the trusted anchor to the - * target subject. The default value if not specified is true. - * - * @param buildForward the value of the buildForward flag - */ - public void setBuildForward(boolean buildForward) { - this.buildForward = buildForward; - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters. - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[\n"); - sb.append(super.toString()); - sb.append(" Build Forward Flag: " + String.valueOf(buildForward) + "\n"); - sb.append("]\n"); - return sb.toString(); - } -}
--- a/src/share/classes/sun/util/resources/en/TimeZoneNames_en_GB.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/util/resources/en/TimeZoneNames_en_GB.java Thu Oct 29 17:12:06 2015 -0700 @@ -47,7 +47,8 @@ protected final Object[][] getContents() { return new Object[][] { {"Europe/London", new String[] {"Greenwich Mean Time", "GMT", - "British Summer Time", "BST"}}, + "British Summer Time", "BST", + "British Time", "BT"}}, }; } }
--- a/src/share/classes/sun/util/resources/hi/TimeZoneNames_hi.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/classes/sun/util/resources/hi/TimeZoneNames_hi.java Thu Oct 29 17:12:06 2015 -0700 @@ -40,7 +40,8 @@ {"Asia/Calcutta", new String[] { "\u092d\u093e\u0930\u0924\u0940\u092f \u0938\u092e\u092f", "IST", - "\u092d\u093e\u0930\u0924\u0940\u092f \u0938\u092e\u092f", "IST" + "\u092d\u093e\u0930\u0924\u0940\u092f \u0938\u092e\u092f", "IST", + "\u092d\u093e\u0930\u0924\u0940\u092f \u0938\u092e\u092f", "IT" } }, };
--- a/src/share/native/common/jni_util.h Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/common/jni_util.h Thu Oct 29 17:12:06 2015 -0700 @@ -391,6 +391,7 @@ void buildJniFunctionName(const char *sym, const char *cname, char *jniEntryName); +extern int getErrorString(int err, char *buf, size_t len); #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */
--- a/src/share/native/java/util/zip/Deflater.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/java/util/zip/Deflater.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, 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 @@ -49,13 +49,21 @@ Java_java_util_zip_Deflater_initIDs(JNIEnv *env, jclass cls) { levelID = (*env)->GetFieldID(env, cls, "level", "I"); + CHECK_NULL(levelID); strategyID = (*env)->GetFieldID(env, cls, "strategy", "I"); + CHECK_NULL(strategyID); setParamsID = (*env)->GetFieldID(env, cls, "setParams", "Z"); + CHECK_NULL(setParamsID); finishID = (*env)->GetFieldID(env, cls, "finish", "Z"); + CHECK_NULL(finishID); finishedID = (*env)->GetFieldID(env, cls, "finished", "Z"); + CHECK_NULL(finishedID); bufID = (*env)->GetFieldID(env, cls, "buf", "[B"); + CHECK_NULL(bufID); offID = (*env)->GetFieldID(env, cls, "off", "I"); + CHECK_NULL(offID); lenID = (*env)->GetFieldID(env, cls, "len", "I"); + CHECK_NULL(lenID); } JNIEXPORT jlong JNICALL @@ -137,14 +145,14 @@ in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0); if (in_buf == NULL) { // Throw OOME only when length is not zero - if (this_len != 0) + if (this_len != 0 && (*env)->ExceptionOccurred(env) == NULL) JNU_ThrowOutOfMemoryError(env, 0); return 0; } out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0); if (out_buf == NULL) { (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0); - if (len != 0) + if (len != 0 && (*env)->ExceptionOccurred(env) == NULL) JNU_ThrowOutOfMemoryError(env, 0); return 0; } @@ -163,7 +171,7 @@ this_off += this_len - strm->avail_in; (*env)->SetIntField(env, this, offID, this_off); (*env)->SetIntField(env, this, lenID, strm->avail_in); - return len - strm->avail_out; + return (jint) (len - strm->avail_out); case Z_BUF_ERROR: (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE); return 0;
--- a/src/share/native/java/util/zip/Inflater.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/java/util/zip/Inflater.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -50,10 +50,15 @@ Java_java_util_zip_Inflater_initIDs(JNIEnv *env, jclass cls) { needDictID = (*env)->GetFieldID(env, cls, "needDict", "Z"); + CHECK_NULL(needDictID); finishedID = (*env)->GetFieldID(env, cls, "finished", "Z"); + CHECK_NULL(finishedID); bufID = (*env)->GetFieldID(env, cls, "buf", "[B"); + CHECK_NULL(bufID); offID = (*env)->GetFieldID(env, cls, "off", "I"); + CHECK_NULL(offID); lenID = (*env)->GetFieldID(env, cls, "len", "I"); + CHECK_NULL(lenID); } JNIEXPORT jlong JNICALL @@ -127,14 +132,14 @@ in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0); if (in_buf == NULL) { - if (this_len != 0) + if (this_len != 0 && (*env)->ExceptionOccurred(env) == NULL) JNU_ThrowOutOfMemoryError(env, 0); return 0; } out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0); if (out_buf == NULL) { (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0); - if (len != 0) + if (len != 0 && (*env)->ExceptionOccurred(env) == NULL) JNU_ThrowOutOfMemoryError(env, 0); return 0; } @@ -154,7 +159,7 @@ this_off += this_len - strm->avail_in; (*env)->SetIntField(env, this, offID, this_off); (*env)->SetIntField(env, this, lenID, strm->avail_in); - return len - strm->avail_out; + return (jint) (len - strm->avail_out); case Z_NEED_DICT: (*env)->SetBooleanField(env, this, needDictID, JNI_TRUE); /* Might have consumed some input here! */
--- a/src/share/native/java/util/zip/ZipFile.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/java/util/zip/ZipFile.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -71,11 +71,13 @@ if (msg != NULL) { s = JNU_NewStringPlatform(env, msg); } - x = JNU_NewObjectByName(env, + if (s != NULL) { + x = JNU_NewObjectByName(env, "java/util/zip/ZipException", "(Ljava/lang/String;)V", s); - if (x != NULL) { - (*env)->Throw(env, x); + if (x != NULL) { + (*env)->Throw(env, x); + } } } @@ -363,8 +365,10 @@ /* If some names were found then build array of java strings */ if (count > 0) { - jclass cls = (*env)->FindClass(env, "java/lang/String"); + jclass cls = JNU_ClassString(env); + CHECK_NULL_RETURN(cls, NULL); result = (*env)->NewObjectArray(env, count, cls, 0); + CHECK_NULL_RETURN(result, NULL); if (result != 0) { for (i = 0; i < count; i++) { jstring str = (*env)->NewStringUTF(env, zip->metanames[i]);
--- a/src/share/native/java/util/zip/zip_util.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/java/util/zip/zip_util.c Thu Oct 29 17:12:06 2015 -0700 @@ -1314,12 +1314,23 @@ jint ZIP_Read(jzfile *zip, jzentry *entry, jlong pos, void *buf, jint len) { - jlong entry_size = (entry->csize != 0) ? entry->csize : entry->size; + jlong entry_size; jlong start; + if (zip == 0) { + return -1; + } + /* Clear previous zip error */ zip->msg = NULL; + if (entry == 0) { + zip->msg = "ZIP_Read: jzentry is NULL"; + return -1; + } + + entry_size = (entry->csize != 0) ? entry->csize : entry->size; + /* Check specified position */ if (pos < 0 || pos > entry_size - 1) { zip->msg = "ZIP_Read: specified offset out of range"; @@ -1449,6 +1460,12 @@ ZIP_ReadEntry(jzfile *zip, jzentry *entry, unsigned char *buf, char *entryname) { char *msg; + char tmpbuf[1024]; + + if (entry == 0) { + jio_fprintf(stderr, "jzentry was invalid"); + return JNI_FALSE; + } strcpy(entryname, entry->name); if (entry->csize == 0) { @@ -1467,8 +1484,11 @@ msg = zip->msg; ZIP_Unlock(zip); if (n == -1) { - jio_fprintf(stderr, "%s: %s\n", zip->name, - msg != 0 ? msg : strerror(errno)); + if (msg == 0) { + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + msg = tmpbuf; + } + jio_fprintf(stderr, "%s: %s\n", zip->name, msg); return JNI_FALSE; } buf += n; @@ -1481,8 +1501,11 @@ if ((msg == NULL) || (*msg == 0)) { msg = zip->msg; } - jio_fprintf(stderr, "%s: %s\n", zip->name, - msg != 0 ? msg : strerror(errno)); + if (msg == 0) { + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + msg = tmpbuf; + } + jio_fprintf(stderr, "%s: %s\n", zip->name, msg); return JNI_FALSE; } }
--- a/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/share/native/sun/security/pkcs11/wrapper/p11_convert.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. */ /* Copyright (c) 2002 Graz University of Technology. All rights reserved. @@ -474,6 +474,7 @@ jfieldID fieldID; jclass jSsl3RandomDataClass; jobject jRandomInfo, jRIClientRandom, jRIServerRandom, jVersion; + memset(&ckParam, 0, sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS)); /* get RandomInfo */ jSsl3MasterKeyDeriveParamsClass = (*env)->FindClass(env, CLASS_SSL3_MASTER_KEY_DERIVE_PARAMS); @@ -527,6 +528,7 @@ CK_TLS_PRF_PARAMS ckParam; jfieldID fieldID; jobject jSeed, jLabel, jOutput; + memset(&ckParam, 0, sizeof(CK_TLS_PRF_PARAMS)); // TBD: what if jParam == NULL?! @@ -592,6 +594,7 @@ jobject jRandomInfo, jRIClientRandom, jRIServerRandom; jobject jReturnedKeyMaterial, jRMIvClient, jRMIvServer; CK_ULONG ckTemp; + memset(&ckParam, 0, sizeof(CK_SSL3_KEY_MAT_PARAMS)); /* get ulMacSizeInBits */ jSsl3KeyMatParamsClass = (*env)->FindClass(env, CLASS_SSL3_KEY_MAT_PARAMS); @@ -1355,6 +1358,7 @@ jlong jHashAlg, jMgf, jSource; jobject jSourceData; CK_BYTE_PTR ckpByte; + memset(&ckParam, 0, sizeof(CK_RSA_PKCS_OAEP_PARAMS)); /* get hashAlg */ jRsaPkcsOaepParamsClass = (*env)->FindClass(env, CLASS_RSA_PKCS_OAEP_PARAMS); @@ -1404,6 +1408,7 @@ jlong jIteration; jobject jInitVector, jPassword, jSalt; CK_ULONG ckTemp; + memset(&ckParam, 0, sizeof(CK_PBE_PARAMS)); /* get pInitVector */ jPbeParamsClass = (*env)->FindClass(env, CLASS_PBE_PARAMS); @@ -1522,6 +1527,7 @@ jfieldID fieldID; jlong jSaltSource, jIteration, jPrf; jobject jSaltSourceData, jPrfData; + memset(&ckParam, 0, sizeof(CK_PKCS5_PBKD2_PARAMS)); /* get saltSource */ jPkcs5Pbkd2ParamsClass = (*env)->FindClass(env, CLASS_PKCS5_PBKD2_PARAMS); @@ -1734,6 +1740,7 @@ jfieldID fieldID; jlong jKdf; jobject jOtherInfo, jPublicData; + memset(&ckParam, 0, sizeof(CK_X9_42_DH1_DERIVE_PARAMS)); /* get kdf */ jX942Dh1DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH1_DERIVE_PARAMS); @@ -1779,6 +1786,7 @@ jfieldID fieldID; jlong jKdf, jPrivateDataLen, jPrivateData; jobject jOtherInfo, jPublicData, jPublicData2; + memset(&ckParam, 0, sizeof(CK_X9_42_DH2_DERIVE_PARAMS)); /* get kdf */ jX942Dh2DeriveParamsClass = (*env)->FindClass(env, CLASS_X9_42_DH2_DERIVE_PARAMS);
--- a/src/solaris/classes/java/net/PlainDatagramSocketImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/java/net/PlainDatagramSocketImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007,2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -119,6 +119,8 @@ protected native void disconnect0(int family); + native int dataAvailable(); + /** * Perform class load-time initializations. */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/solaris/classes/sun/awt/FcFontManager.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.awt; + +import sun.font.FcFontConfiguration; +import sun.font.FontConfigManager; +import sun.font.SunFontManager; + +/** + * A {@link sun.font.FontManager} that uses fontconfig to find system fonts. + */ +public class FcFontManager extends SunFontManager { + + private FontConfigManager fcManager = null; + + public synchronized FontConfigManager getFontConfigManager() { + + if (fcManager == null) { + fcManager = new FontConfigManager(); + } + + return fcManager; + } + + @Override + protected FontConfiguration createFontConfiguration() { + FcFontConfiguration fcFontConfig = new FcFontConfiguration(this); + if (fcFontConfig.init()) { + return fcFontConfig; + } else { + throw new InternalError("failed to initialize fontconfig"); + } + } + + @Override + public FontConfiguration createFontConfiguration(boolean preferLocaleFonts, + boolean preferPropFonts) { + FcFontConfiguration fcFontConfig = + new FcFontConfiguration(this, preferLocaleFonts, preferPropFonts); + if (fcFontConfig.init()) { + return fcFontConfig; + } else { + throw new InternalError("failed to initialize fontconfig"); + } + } + + @Override + protected String[] getDefaultPlatformFont() { + final String[] info = new String[2]; + getFontConfigManager().initFontConfigFonts(false); + FontConfigManager.FcCompFont[] fontConfigFonts = + getFontConfigManager().getFontConfigFonts(); + for (int i=0; i<fontConfigFonts.length; i++) { + if ("sans".equals(fontConfigFonts[i].fcFamily) && + 0 == fontConfigFonts[i].style) { + info[0] = fontConfigFonts[i].firstFont.familyName; + info[1] = fontConfigFonts[i].firstFont.fontFile; + break; + } + } + /* Absolute last ditch attempt in the face of fontconfig problems. + * If we didn't match, pick the first, or just make something + * up so we don't NPE. + */ + if (info[0] == null) { + if (fontConfigFonts.length > 0 && + fontConfigFonts[0].firstFont.fontFile != null) { + info[0] = fontConfigFonts[0].firstFont.familyName; + info[1] = fontConfigFonts[0].firstFont.fontFile; + } else { + info[0] = "Dialog"; + info[1] = "/dialog.ttf"; + } + } + return info; + } + + protected native String getFontPathNative(boolean noType1Fonts, + boolean isX11GE); + + protected synchronized String getFontPath(boolean noType1Fonts) { + return getFontPathNative(noType1Fonts, false); + } + +}
--- a/src/solaris/classes/sun/awt/X11FontManager.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/awt/X11FontManager.java Thu Oct 29 17:12:06 2015 -0700 @@ -54,7 +54,7 @@ /** * The X11 implementation of {@link FontManager}. */ -public final class X11FontManager extends SunFontManager { +public final class X11FontManager extends FcFontManager { // constants identifying XLFD and font ID fields private static final int FOUNDRY_FIELD = 1; @@ -154,8 +154,6 @@ */ private static String[] fontdirs = null; - private FontConfigManager fcManager = null; - public static X11FontManager getInstance() { return (X11FontManager) SunFontManager.getInstance(); } @@ -784,51 +782,9 @@ preferLocaleFonts, preferPropFonts); } - public synchronized native String getFontPathNative(boolean noType1Fonts); - protected synchronized String getFontPath(boolean noType1Fonts) { isHeadless(); // make sure GE is inited, as its the X11 lock. - return getFontPathNative(noType1Fonts); - } - - @Override - protected String[] getDefaultPlatformFont() { - final String[] info = new String[2]; - getFontConfigManager().initFontConfigFonts(false); - FontConfigManager.FcCompFont[] fontConfigFonts = - getFontConfigManager().getFontConfigFonts(); - for (int i=0; i<fontConfigFonts.length; i++) { - if ("sans".equals(fontConfigFonts[i].fcFamily) && - 0 == fontConfigFonts[i].style) { - info[0] = fontConfigFonts[i].firstFont.familyName; - info[1] = fontConfigFonts[i].firstFont.fontFile; - break; - } - } - /* Absolute last ditch attempt in the face of fontconfig problems. - * If we didn't match, pick the first, or just make something - * up so we don't NPE. - */ - if (info[0] == null) { - if (fontConfigFonts.length > 0 && - fontConfigFonts[0].firstFont.fontFile != null) { - info[0] = fontConfigFonts[0].firstFont.familyName; - info[1] = fontConfigFonts[0].firstFont.fontFile; - } else { - info[0] = "Dialog"; - info[1] = "/dialog.ttf"; - } - } - return info; - } - - public synchronized FontConfigManager getFontConfigManager() { - - if (fcManager == null) { - fcManager = new FontConfigManager(); - } - - return fcManager; + return getFontPathNative(noType1Fonts, true); } @Override
--- a/src/solaris/classes/sun/font/FcFontConfiguration.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/font/FcFontConfiguration.java Thu Oct 29 17:12:06 2015 -0700 @@ -39,10 +39,10 @@ import java.util.HashSet; import java.util.Properties; import java.util.Scanner; +import sun.awt.FcFontManager; import sun.awt.FontConfiguration; import sun.awt.FontDescriptor; import sun.awt.SunToolkit; -import sun.awt.X11FontManager; import sun.font.CompositeFontDescriptor; import sun.font.FontManager; import sun.font.FontConfigManager.FontConfigInfo; @@ -92,7 +92,7 @@ setFontConfiguration(); readFcInfo(); - X11FontManager fm = (X11FontManager) fontManager; + FcFontManager fm = (FcFontManager) fontManager; FontConfigManager fcm = fm.getFontConfigManager(); if (fcCompFonts == null) { fcCompFonts = fcm.loadFontConfig(); @@ -194,7 +194,7 @@ @Override public String[] getPlatformFontNames() { HashSet<String> nameSet = new HashSet<String>(); - X11FontManager fm = (X11FontManager) fontManager; + FcFontManager fm = (FcFontManager) fontManager; FontConfigManager fcm = fm.getFontConfigManager(); FcCompFont[] fcCompFonts = fcm.loadFontConfig(); for (int i=0; i<fcCompFonts.length; i++) { @@ -235,7 +235,7 @@ @Override public CompositeFontDescriptor[] get2DCompositeFontInfo() { - X11FontManager fm = (X11FontManager) fontManager; + FcFontManager fm = (FcFontManager) fontManager; FontConfigManager fcm = fm.getFontConfigManager(); FcCompFont[] fcCompFonts = fcm.loadFontConfig(); @@ -368,7 +368,7 @@ private void writeFcInfo() { Properties props = new Properties(); props.setProperty("version", fileVersion); - X11FontManager fm = (X11FontManager) fontManager; + FcFontManager fm = (FcFontManager) fontManager; FontConfigManager fcm = fm.getFontConfigManager(); FontConfigInfo fcInfo = fcm.getFontConfigInfo(); props.setProperty("fcversion", Integer.toString(fcInfo.fcVersion)); @@ -427,7 +427,7 @@ return; } Properties props = new Properties(); - X11FontManager fm = (X11FontManager) fontManager; + FcFontManager fm = (FcFontManager) fontManager; FontConfigManager fcm = fm.getFontConfigManager(); try { FileInputStream fis = new FileInputStream(fcFile);
--- a/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/ch/DevPollSelectorImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -68,9 +68,23 @@ long pipeFds = IOUtil.makePipe(false); fd0 = (int) (pipeFds >>> 32); fd1 = (int) pipeFds; - pollWrapper = new DevPollArrayWrapper(); - pollWrapper.initInterrupt(fd0, fd1); - fdToKey = new HashMap<Integer,SelectionKeyImpl>(); + try { + pollWrapper = new DevPollArrayWrapper(); + pollWrapper.initInterrupt(fd0, fd1); + fdToKey = new HashMap<>(); + } catch (Throwable t) { + try { + FileDispatcherImpl.closeIntFD(fd0); + } catch (IOException ioe0) { + t.addSuppressed(ioe0); + } + try { + FileDispatcherImpl.closeIntFD(fd1); + } catch (IOException ioe1) { + t.addSuppressed(ioe1); + } + throw t; + } } protected int doSelect(long timeout)
--- a/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/ch/EPollSelectorImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -65,9 +65,23 @@ long pipeFds = IOUtil.makePipe(false); fd0 = (int) (pipeFds >>> 32); fd1 = (int) pipeFds; - pollWrapper = new EPollArrayWrapper(); - pollWrapper.initInterrupt(fd0, fd1); - fdToKey = new HashMap<>(); + try { + pollWrapper = new EPollArrayWrapper(); + pollWrapper.initInterrupt(fd0, fd1); + fdToKey = new HashMap<>(); + } catch (Throwable t) { + try { + FileDispatcherImpl.closeIntFD(fd0); + } catch (IOException ioe0) { + t.addSuppressed(ioe0); + } + try { + FileDispatcherImpl.closeIntFD(fd1); + } catch (IOException ioe1) { + t.addSuppressed(ioe1); + } + throw t; + } } protected int doSelect(long timeout) throws IOException {
--- a/src/solaris/classes/sun/nio/ch/PollSelectorImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/ch/PollSelectorImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -57,9 +57,23 @@ long pipeFds = IOUtil.makePipe(false); fd0 = (int) (pipeFds >>> 32); fd1 = (int) pipeFds; - pollWrapper = new PollArrayWrapper(INIT_CAP); - pollWrapper.initInterrupt(fd0, fd1); - channelArray = new SelectionKeyImpl[INIT_CAP]; + try { + pollWrapper = new PollArrayWrapper(INIT_CAP); + pollWrapper.initInterrupt(fd0, fd1); + channelArray = new SelectionKeyImpl[INIT_CAP]; + } catch (Throwable t) { + try { + FileDispatcherImpl.closeIntFD(fd0); + } catch (IOException ioe0) { + t.addSuppressed(ioe0); + } + try { + FileDispatcherImpl.closeIntFD(fd1); + } catch (IOException ioe1) { + t.addSuppressed(ioe1); + } + throw t; + } } protected int doSelect(long timeout)
--- a/src/solaris/classes/sun/nio/fs/GnomeFileTypeDetector.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/fs/GnomeFileTypeDetector.java Thu Oct 29 17:12:06 2015 -0700 @@ -86,7 +86,7 @@ // GIO private static native boolean initializeGio(); - private static native byte[] probeUsingGio(long pathAddress); + private static synchronized native byte[] probeUsingGio(long pathAddress); // GNOME VFS private static native boolean initializeGnomeVfs();
--- a/src/solaris/classes/sun/nio/fs/MimeTypesFileTypeDetector.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/fs/MimeTypesFileTypeDetector.java Thu Oct 29 17:12:06 2015 -0700 @@ -171,7 +171,7 @@ final String EXTEQUAL = "exts="; String extRegex = "\\b" + EXTEQUAL + - "(\"[\\p{Graph}|\\p{Blank}]+?\"|\\p{Graph}+\\b)"; + "(\"[\\p{Graph}\\p{Blank}]+?\"|\\p{Graph}+\\b)"; Pattern extPattern = Pattern.compile(extRegex); Matcher extMatcher = extPattern.matcher(entry); @@ -181,7 +181,7 @@ if (exts.charAt(0) == '"') { exts = exts.substring(1, exts.length() - 1); } - String[] extList = exts.split("[\\p{Blank}|\\p{Punct}]+"); + String[] extList = exts.split("[\\p{Blank}\\p{Punct}]+"); for (String ext : extList) { putIfAbsent(ext, type); }
--- a/src/solaris/classes/sun/nio/fs/UnixFileStore.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/classes/sun/nio/fs/UnixFileStore.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -186,7 +186,8 @@ return false; UnixFileStore other = (UnixFileStore)ob; return (this.dev == other.dev) && - Arrays.equals(this.entry.dir(), other.entry.dir()); + Arrays.equals(this.entry.dir(), other.entry.dir()) && + this.entry.name().equals(other.entry.name()); } @Override
--- a/src/solaris/native/common/jni_util_md.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/common/jni_util_md.c Thu Oct 29 17:12:06 2015 -0700 @@ -37,6 +37,13 @@ return NULL; } +#if defined(LINUX) && (defined(_GNU_SOURCE) || \ + (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE < 200112L \ + && defined(_XOPEN_SOURCE) && _XOPEN_SOURCE < 600)) +extern int __xpg_strerror_r(int, char *, size_t); +#define strerror_r(a, b, c) __xpg_strerror_r((a), (b), (c)) +#endif + void* getProcessHandle() { static void *procHandle = NULL; if (procHandle != NULL) { @@ -59,3 +66,9 @@ } } +int +getErrorString(int err, char *buf, size_t len) +{ + if (err == 0 || len < 1) return 0; + return strerror_r(err, buf, len); +}
--- a/src/solaris/native/java/io/io_util_md.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/java/io/io_util_md.c Thu Oct 29 17:12:06 2015 -0700 @@ -216,13 +216,6 @@ getLastErrorString(char *buf, size_t len) { if (errno == 0 || len < 1) return 0; - - const char *err = strerror(errno); - size_t n = strlen(err); - if (n >= len) - n = len - 1; - - strncpy(buf, err, n); - buf[n] = '\0'; - return n; + getErrorString(errno, buf, len); + return strlen(buf); }
--- a/src/solaris/native/java/lang/UNIXProcess_md.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/java/lang/UNIXProcess_md.c Thu Oct 29 17:12:06 2015 -0700 @@ -292,12 +292,13 @@ static const char * const format = "error=%d, %s"; const char *detail = defaultDetail; char *errmsg; + char tmpbuf[1024]; jstring s; if (errnum != 0) { - const char *s = strerror(errnum); - if (strcmp(s, "Unknown error") != 0) - detail = s; + int ret = getErrorString(errnum, tmpbuf, sizeof(tmpbuf)); + if (ret != EINVAL) + detail = tmpbuf; } /* ASCII Decimal representation uses 2.4 times as many bits as binary. */ errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum));
--- a/src/solaris/native/java/net/AbstractPlainDatagramSocketImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include <sys/types.h> -#include <sys/socket.h> - -#ifdef __solaris__ -#include <unistd.h> -#include <stropts.h> - -#ifndef BSD_COMP -#define BSD_COMP -#endif - -#endif - -#include <sys/ioctl.h> - -#include "jvm.h" -#include "jni_util.h" -#include "net_util.h" - -#include "java_net_AbstractPlainDatagramSocketImpl.h" - -static jfieldID IO_fd_fdID; - -static jfieldID apdsi_fdID; - - -/* - * Class: java_net_AbstractPlainDatagramSocketImpl - * Method: init - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) { - - apdsi_fdID = (*env)->GetFieldID(env, cls, "fd", - "Ljava/io/FileDescriptor;"); - CHECK_NULL(apdsi_fdID); - - IO_fd_fdID = NET_GetFileDescriptorID(env); -} - -/* - * Class: java_net_AbstractPlainDatagramSocketImpl - * Method: dataAvailable - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable -(JNIEnv *env, jobject this) { - int fd, retval; - - jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID); - - if (IS_NULL(fdObj)) { - JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", - "Socket closed"); - return -1; - } - fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID); - - if (ioctl(fd, FIONREAD, &retval) < 0) { - return -1; - } - return retval; -}
--- a/src/solaris/native/java/net/PlainDatagramSocketImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/java/net/PlainDatagramSocketImpl.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -32,6 +32,12 @@ #ifdef __solaris__ #include <fcntl.h> +#include <unistd.h> +#include <stropts.h> + +#ifndef BSD_COMP +#define BSD_COMP +#endif #endif #ifdef __linux__ #include <unistd.h> @@ -52,6 +58,8 @@ #endif #endif // __linux__ +#include <sys/ioctl.h> + #ifndef IPTOS_TOS_MASK #define IPTOS_TOS_MASK 0x1e #endif @@ -946,6 +954,7 @@ jobject this) { jobject fdObj = (*env)->GetObjectField(env, this, pdsi_fdID); int arg, fd, t = 1; + char tmpbuf[1024]; #ifdef AF_INET6 int domain = ipv6_available() ? AF_INET6 : AF_INET; #else @@ -981,14 +990,14 @@ arg = 65507; if (JVM_SetSockOpt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&arg, sizeof(arg)) < 0) { - JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", - strerror(errno)); + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf); return; } if (JVM_SetSockOpt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&arg, sizeof(arg)) < 0) { - JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", - strerror(errno)); + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf); return; } #endif /* __APPLE__ */ @@ -996,15 +1005,16 @@ setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char*) &t, sizeof(int)); #if defined(__linux__) - arg = 0; - int level = (domain == AF_INET6) ? IPPROTO_IPV6 : IPPROTO_IP; - if ((setsockopt(fd, level, IP_MULTICAST_ALL, (char*)&arg, sizeof(arg)) < 0) && - (errno != ENOPROTOOPT)) { - JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", - strerror(errno)); - close(fd); - return; - } + arg = 0; + int level = (domain == AF_INET6) ? IPPROTO_IPV6 : IPPROTO_IP; + if ((setsockopt(fd, level, IP_MULTICAST_ALL, (char*)&arg, sizeof(arg)) < 0) && + (errno != ENOPROTOOPT)) + { + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf); + close(fd); + return; + } #endif #if defined (__linux__) && defined (AF_INET6) @@ -2265,3 +2275,28 @@ { mcast_join_leave(env, this, iaObj, niObj, JNI_FALSE); } + +/* + * Class: java_net_PlainDatagramSocketImpl + * Method: dataAvailable + * Signature: ()I + */ +JNIEXPORT jint JNICALL +Java_java_net_PlainDatagramSocketImpl_dataAvailable(JNIEnv *env, jobject this) +{ + int fd, retval; + + jobject fdObj = (*env)->GetObjectField(env, this, pdsi_fdID); + + if (IS_NULL(fdObj)) { + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", + "Socket closed"); + return -1; + } + fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID); + + if (ioctl(fd, FIONREAD, &retval) < 0) { + return -1; + } + return retval; +}
--- a/src/solaris/native/java/util/TimeZone_md.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/java/util/TimeZone_md.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, 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 @@ -35,14 +35,20 @@ #include <string.h> #include <dirent.h> #include <unistd.h> -#ifdef __solaris__ +#if defined(__solaris__) #include <libscf.h> #endif #include "jvm.h" +#include "TimeZone_md.h" #define SKIP_SPACE(p) while (*p == ' ' || *p == '\t') p++; +#if defined(_ALLBSD_SOURCE) +#define dirent64 dirent +#define readdir64_r readdir_r +#endif + #if !defined(__solaris__) || defined(__sparcv9) || defined(amd64) #define fileopen fopen #define filegets fgets @@ -50,19 +56,20 @@ #endif #if defined(__linux__) || defined(_ALLBSD_SOURCE) - - static const char *ETC_TIMEZONE_FILE = "/etc/timezone"; static const char *ZONEINFO_DIR = "/usr/share/zoneinfo"; static const char *DEFAULT_ZONEINFO_FILE = "/etc/localtime"; #else -#ifdef _AIX -static const char *ETC_ENVIRONMENT_FILE = "/etc/environment"; -#endif static const char *SYS_INIT_FILE = "/etc/default/init"; static const char *ZONEINFO_DIR = "/usr/share/lib/zoneinfo"; static const char *DEFAULT_ZONEINFO_FILE = "/usr/share/lib/zoneinfo/localtime"; -#endif /*__linux__*/ +#endif /* defined(__linux__) || defined(_ALLBSD_SOURCE) */ + +#if defined(_AIX) +static const char *ETC_ENVIRONMENT_FILE = "/etc/environment"; +#endif + +#if defined(__linux__) || defined(MACOSX) || defined(__solaris__) /* * Returns a pointer to the zone ID portion of the given zoneinfo file @@ -108,8 +115,8 @@ { DIR *dirp = NULL; struct stat statbuf; - struct dirent *dp = NULL; - struct dirent *entry = NULL; + struct dirent64 *dp = NULL; + struct dirent64 *entry = NULL; char *pathname = NULL; int fd = -1; char *dbuf = NULL; @@ -120,19 +127,13 @@ return NULL; } - entry = (struct dirent *) malloc((size_t) pathconf(dir, _PC_NAME_MAX)); + entry = (struct dirent64 *) malloc((size_t) pathconf(dir, _PC_NAME_MAX)); if (entry == NULL) { (void) closedir(dirp); return NULL; } -#if defined(_AIX) || defined(__linux__) || defined(MACOSX) || (defined(__solaris__) \ - && (defined(_POSIX_PTHREAD_SEMANTICS) || defined(_LP64))) - while (readdir_r(dirp, entry, &dp) == 0 && dp != NULL) { -#else - while ((dp = readdir_r(dirp, entry)) != NULL) { -#endif - + while (readdir64_r(dirp, entry, &dp) == 0 && dp != NULL) { /* * Skip '.' and '..' (and possibly other .* files) */ @@ -145,7 +146,7 @@ */ if ((strcmp(dp->d_name, "ROC") == 0) || (strcmp(dp->d_name, "posixrules") == 0) -#ifdef __solaris__ +#if defined(__solaris__) /* * Skip the "src" and "tab" directories on Solaris. */ @@ -230,7 +231,7 @@ char *buf; size_t size; -#ifdef __linux__ +#if defined(__linux__) /* * Try reading the /etc/timezone file for Debian distros. There's * no spec of the file format available. This parsing assumes that @@ -254,7 +255,7 @@ return tz; } } -#endif /* __linux__ */ +#endif /* defined(__linux__) */ /* * Next, try /etc/localtime to find the zone ID. @@ -318,8 +319,9 @@ free((void *) buf); return tz; } -#else -#ifdef __solaris__ + +#elif defined(__solaris__) + #if !defined(__sparcv9) && !defined(amd64) /* @@ -444,8 +446,7 @@ } /*NOTREACHED*/ } -#endif /* not __sparcv9 */ - +#endif /* !defined(__sparcv9) && !defined(amd64) */ /* * Performs Solaris dependent mapping. Returns a zone ID if @@ -546,7 +547,7 @@ } /* - * Retruns a zone ID of Solaris when the TZ value is "localtime". + * Returns a zone ID of Solaris when the TZ value is "localtime". * First, it tries scf. If scf fails, it looks for the same file as * /usr/share/lib/zoneinfo/localtime under /usr/share/lib/zoneinfo/. */ @@ -615,10 +616,11 @@ free((void *) buf); return tz; } -#endif /*__solaris__*/ -#endif /*__linux__*/ + +#endif /* defined(__solaris__) */ -#ifdef _AIX +#elif defined(_AIX) + static char * getPlatformTimeZoneID() { @@ -644,175 +646,33 @@ return tz; } -static char *mapPlatformToJavaTimezone(const char *java_home_dir, const char *tz); -#endif -/* - * findJavaTZ_md() maps platform time zone ID to Java time zone ID - * using <java_home>/lib/tzmappings. If the TZ value is not found, it - * trys some libc implementation dependent mappings. If it still - * can't map to a Java time zone ID, it falls back to the GMT+/-hh:mm - * form. - */ -/*ARGSUSED1*/ -char * -findJavaTZ_md(const char *java_home_dir) -{ - char *tz; - char *javatz = NULL; - char *freetz = NULL; - - tz = getenv("TZ"); - -#if defined(__linux__) || defined(_ALLBSD_SOURCE) - if (tz == NULL) { -#else -#if defined (__solaris__) || defined(_AIX) - if (tz == NULL || *tz == '\0') { -#endif -#endif - tz = getPlatformTimeZoneID(); - freetz = tz; - } - - /* - * Remove any preceding ':' - */ - if (tz != NULL && *tz == ':') { - tz++; - } - -#ifdef __solaris__ - if (tz != NULL && strcmp(tz, "localtime") == 0) { - tz = getSolarisDefaultZoneID(); - freetz = tz; - } -#endif - - if (tz != NULL) { -#ifdef __linux__ - /* - * Ignore "posix/" prefix. - */ - if (strncmp(tz, "posix/", 6) == 0) { - tz += 6; - } -#endif - javatz = strdup(tz); - if (freetz != NULL) { - free((void *) freetz); - } - -#ifdef _AIX - freetz = mapPlatformToJavaTimezone(java_home_dir, javatz); - if (javatz != NULL) { - free((void *) javatz); - } - javatz = freetz; -#endif - } - - return javatz; -} - -/** - * Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00") - */ - -#ifdef MACOSX - -char * -getGMTOffsetID() -{ - time_t offset; - char sign, buf[32]; - struct tm *local_tm; - time_t clock; - time_t currenttime; - - clock = time(NULL); - tzset(); - local_tm = localtime(&clock); - if (local_tm->tm_gmtoff >= 0) { - offset = (time_t) local_tm->tm_gmtoff; - sign = "+"; - } else { - offset = (time_t) -local_tm->tm_gmtoff; - sign = "-"; - } - sprintf(buf, (const char *)"GMT%c%02d:%02d", - sign, (int)(offset/3600), (int)((offset%3600)/60)); - return strdup(buf); -} -#else - -char * -getGMTOffsetID() -{ - time_t offset; - char sign, buf[32]; -#ifdef __solaris__ - struct tm localtm; - time_t currenttime; - - currenttime = time(NULL); - if (localtime_r(¤ttime, &localtm) == NULL) { - return NULL; - } - - offset = localtm.tm_isdst ? altzone : timezone; -#else - offset = timezone; -#endif /*__linux__*/ - - if (offset == 0) { - return strdup("GMT"); - } - - /* Note that the time offset direction is opposite. */ - if (offset > 0) { - sign = '-'; - } else { - offset = -offset; - sign = '+'; - } - sprintf(buf, (const char *)"GMT%c%02d:%02d", - sign, (int)(offset/3600), (int)((offset%3600)/60)); - return strdup(buf); -} -#endif /* MACOSX */ - -#ifdef _AIX static char * mapPlatformToJavaTimezone(const char *java_home_dir, const char *tz) { FILE *tzmapf; - char mapfilename[PATH_MAX+1]; + char mapfilename[PATH_MAX + 1]; char line[256]; int linecount = 0; - char temp[100], *temp_tz; + char *tz_buf = NULL; + char *temp_tz = NULL; char *javatz = NULL; - char *str_tmp = NULL; - size_t temp_tz_len = 0; + size_t tz_len = 0; /* On AIX, the TZ environment variable may end with a comma - * followed by modifier fields. These are ignored here. - */ - strncpy(temp, tz, 100); - temp_tz = strtok_r(temp, ",", &str_tmp); + * followed by modifier fields. These are ignored here. */ + temp_tz = strchr(tz, ','); + tz_len = (temp_tz == NULL) ? strlen(tz) : temp_tz - tz; + tz_buf = (char *)malloc(tz_len + 1); + memcpy(tz_buf, tz, tz_len); + tz_buf[tz_len] = 0; - if(temp_tz == NULL) - goto tzerr; - - temp_tz_len = strlen(temp_tz); - - if (strlen(java_home_dir) >= (PATH_MAX - 15)) { - jio_fprintf(stderr, "java.home longer than maximum path length \n"); + /* Open tzmappings file, with buffer overrun check */ + if ((strlen(java_home_dir) + 15) > PATH_MAX) { + jio_fprintf(stderr, "Path %s/lib/tzmappings exceeds maximum path length\n", java_home_dir); goto tzerr; } - - strncpy(mapfilename, java_home_dir, PATH_MAX); + strcpy(mapfilename, java_home_dir); strcat(mapfilename, "/lib/tzmappings"); - if ((tzmapf = fopen(mapfilename, "r")) == NULL) { jio_fprintf(stderr, "can't open %s\n", mapfilename); goto tzerr; @@ -845,7 +705,7 @@ } *p++ = '\0'; - if ((result = strncmp(temp_tz, sol, temp_tz_len)) == 0) { + if ((result = strncmp(tz_buf, sol, tz_len)) == 0) { /* * If this is the current platform zone ID, * take the Java time zone ID (2nd field). @@ -871,11 +731,150 @@ (void) fclose(tzmapf); tzerr: + if (tz_buf != NULL ) { + free((void *) tz_buf); + } + if (javatz == NULL) { return getGMTOffsetID(); } return javatz; } + +#endif /* defined(_AIX) */ + +/* + * findJavaTZ_md() maps platform time zone ID to Java time zone ID + * using <java_home>/lib/tzmappings. If the TZ value is not found, it + * trys some libc implementation dependent mappings. If it still + * can't map to a Java time zone ID, it falls back to the GMT+/-hh:mm + * form. + */ +/*ARGSUSED1*/ +char * +findJavaTZ_md(const char *java_home_dir) +{ + char *tz; + char *javatz = NULL; + char *freetz = NULL; + + tz = getenv("TZ"); + + if (tz == NULL || *tz == '\0') { + tz = getPlatformTimeZoneID(); + freetz = tz; + } + + if (tz != NULL) { + /* Ignore preceding ':' */ + if (*tz == ':') { + tz++; + } +#if defined(__linux__) + /* Ignore "posix/" prefix on Linux. */ + if (strncmp(tz, "posix/", 6) == 0) { + tz += 6; + } #endif +#if defined(_AIX) + /* On AIX do the platform to Java mapping. */ + javatz = mapPlatformToJavaTimezone(java_home_dir, tz); + if (freetz != NULL) { + free((void *) freetz); + } +#else +#if defined(__solaris__) + /* Solaris might use localtime, so handle it here. */ + if (strcmp(tz, "localtime") == 0) { + javatz = getSolarisDefaultZoneID(); + if (freetz != NULL) { + free((void *) freetz); + } + } else +#endif + if (freetz == NULL) { + /* strdup if we are still working on getenv result. */ + javatz = strdup(tz); + } else if (freetz != tz) { + /* strdup and free the old buffer, if we moved the pointer. */ + javatz = strdup(tz); + free((void *) freetz); + } else { + /* we are good if we already work on a freshly allocated buffer. */ + javatz = tz; + } +#endif + } + + return javatz; +} + +/** + * Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00") + */ + +#if defined(MACOSX) + +char * +getGMTOffsetID() +{ + time_t offset; + char sign, buf[32]; + struct tm *local_tm; + time_t clock; + time_t currenttime; + + clock = time(NULL); + tzset(); + local_tm = localtime(&clock); + if (local_tm->tm_gmtoff >= 0) { + offset = (time_t) local_tm->tm_gmtoff; + sign = '+'; + } else { + offset = (time_t) -local_tm->tm_gmtoff; + sign = '-'; + } + sprintf(buf, (const char *)"GMT%c%02d:%02d", + sign, (int)(offset/3600), (int)((offset%3600)/60)); + return strdup(buf); +} + +#else + +char * +getGMTOffsetID() +{ + time_t offset; + char sign, buf[32]; +#if defined(__solaris__) + struct tm localtm; + time_t currenttime; + + currenttime = time(NULL); + if (localtime_r(¤ttime, &localtm) == NULL) { + return NULL; + } + + offset = localtm.tm_isdst ? altzone : timezone; +#else + offset = timezone; +#endif + + if (offset == 0) { + return strdup("GMT"); + } + + /* Note that the time offset direction is opposite. */ + if (offset > 0) { + sign = '-'; + } else { + offset = -offset; + sign = '+'; + } + sprintf(buf, (const char *)"GMT%c%02d:%02d", + sign, (int)(offset/3600), (int)((offset%3600)/60)); + return strdup(buf); +} +#endif /* MACOSX */
--- a/src/solaris/native/sun/awt/fontpath.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/sun/awt/fontpath.c Thu Oct 29 17:12:06 2015 -0700 @@ -497,7 +497,7 @@ * This also frees us from X11 APIs as JRE is required to function in * a "headless" mode where there is no Xserver. */ -static char *getPlatformFontPathChars(JNIEnv *env, jboolean noType1) { +static char *getPlatformFontPathChars(JNIEnv *env, jboolean noType1, jboolean isX11) { char **fcdirs = NULL, **x11dirs = NULL, **knowndirs = NULL, *path = NULL; @@ -519,6 +519,7 @@ * be initialised. */ #ifndef HEADLESS + if (isX11) { // The following only works in an x11 environment. #if defined(__linux__) /* There's no headless build on linux ... */ if (!AWTIsHeadless()) { /* .. so need to call a function to check */ @@ -538,6 +539,7 @@ #if defined(__linux__) } #endif + } #endif /* !HEADLESS */ path = mergePaths(fcdirs, x11dirs, knowndirs, noType1); if (fcdirs != NULL) { @@ -555,13 +557,13 @@ return path; } -JNIEXPORT jstring JNICALL Java_sun_awt_X11FontManager_getFontPathNative -(JNIEnv *env, jobject thiz, jboolean noType1) { +JNIEXPORT jstring JNICALL Java_sun_awt_FcFontManager_getFontPathNative +(JNIEnv *env, jobject thiz, jboolean noType1, jboolean isX11) { jstring ret; static char *ptr = NULL; /* retain result across calls */ if (ptr == NULL) { - ptr = getPlatformFontPathChars(env, noType1); + ptr = getPlatformFontPathChars(env, noType1, isX11); } ret = (*env)->NewStringUTF(env, ptr); return ret; @@ -1217,10 +1219,11 @@ minGlyphs = val; } } + FcCharSet *unionCharset = NULL; for (j=0; j<nfonts; j++) { FcPattern *fontPattern = fontset->fonts[j]; FcChar8 *fontformat; - FcCharSet *unionCharset = NULL, *charset; + FcCharSet *charset = NULL; fontformat = NULL; (*FcPatternGetString)(fontPattern, FC_FONTFORMAT, 0, &fontformat); @@ -1278,6 +1281,9 @@ if (!includeFallbacks) { break; } + if (fontCount == 254) { + break; // CompositeFont will only use up to 254 slots from here. + } } /* Once we get here 'fontCount' is the number of returned fonts
--- a/src/solaris/native/sun/management/LinuxOperatingSystem.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/sun/management/LinuxOperatingSystem.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -76,14 +76,17 @@ static int get_totalticks(int which, ticks *pticks) { FILE *fh; uint64_t userTicks, niceTicks, systemTicks, idleTicks; + uint64_t iowTicks = 0, irqTicks = 0, sirqTicks= 0; int n; if((fh = fopen("/proc/stat", "r")) == NULL) { return -1; } - n = fscanf(fh, "cpu " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64, - &userTicks, &niceTicks, &systemTicks, &idleTicks); + n = fscanf(fh, "cpu " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 " " + DEC_64 " " DEC_64, + &userTicks, &niceTicks, &systemTicks, &idleTicks, + &iowTicks, &irqTicks, &sirqTicks); // Move to next line next_line(fh); @@ -92,24 +95,30 @@ if (which != -1) { int i; for (i = 0; i < which; i++) { - if (fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64, &userTicks, &niceTicks, &systemTicks, &idleTicks) != 4) { + if (fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 " " + DEC_64 " " DEC_64 " " DEC_64, + &userTicks, &niceTicks, &systemTicks, &idleTicks, + &iowTicks, &irqTicks, &sirqTicks) < 4) { fclose(fh); return -2; } next_line(fh); } - n = fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 "\n", - &userTicks, &niceTicks, &systemTicks, &idleTicks); + n = fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 " " + DEC_64 " " DEC_64 " " DEC_64 "\n", + &userTicks, &niceTicks, &systemTicks, &idleTicks, + &iowTicks, &irqTicks, &sirqTicks); } fclose(fh); - if (n != 4) { + if (n < 4) { return -2; } pticks->used = userTicks + niceTicks; - pticks->usedKernel = systemTicks; - pticks->total = userTicks + niceTicks + systemTicks + idleTicks; + pticks->usedKernel = systemTicks + irqTicks + sirqTicks; + pticks->total = userTicks + niceTicks + systemTicks + idleTicks + + iowTicks + irqTicks + sirqTicks; return 0; }
--- a/src/solaris/native/sun/nio/fs/UnixNativeDispatcher.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/solaris/native/sun/nio/fs/UnixNativeDispatcher.c Thu Oct 29 17:12:06 2015 -0700 @@ -308,21 +308,15 @@ JNIEXPORT jbyteArray Java_sun_nio_fs_UnixNativeDispatcher_strerror(JNIEnv* env, jclass this, jint error) { - char* msg; + char tmpbuf[1024]; jsize len; jbyteArray bytes; -#ifdef _AIX - /* strerror() is not thread-safe on AIX so we have to use strerror_r() */ - char buffer[256]; - msg = (strerror_r((int)error, buffer, 256) == 0) ? buffer : "Error while calling strerror_r"; -#else - msg = strerror((int)error); -#endif - len = strlen(msg); + getErrorString((int)errno, tmpbuf, sizeof(tmpbuf)); + len = strlen(tmpbuf); bytes = (*env)->NewByteArray(env, len); if (bytes != NULL) { - (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)msg); + (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)tmpbuf); } return bytes; }
--- a/src/windows/classes/java/net/DefaultDatagramSocketImplFactory.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/java/net/DefaultDatagramSocketImplFactory.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -45,7 +45,7 @@ class DefaultDatagramSocketImplFactory { - static Class<?> prefixImplClass = null; + private final static Class<?> prefixImplClass; /* the windows version. */ private static float version; @@ -54,16 +54,19 @@ private static boolean preferIPv4Stack = false; /* If the version supports a dual stack TCP implementation */ - private static boolean useDualStackImpl = false; + private final static boolean useDualStackImpl; /* sun.net.useExclusiveBind */ private static String exclBindProp; /* True if exclusive binding is on for Windows */ - private static boolean exclusiveBind = true; - + private final static boolean exclusiveBind; static { + Class<?> prefixImplClassLocal = null; + boolean useDualStackImplLocal = false; + boolean exclusiveBindLocal = true; + // Determine Windows Version. java.security.AccessController.doPrivileged( new PrivilegedAction<Object>() { @@ -78,7 +81,7 @@ "java.net.preferIPv4Stack")); exclBindProp = System.getProperty( "sun.net.useExclusiveBind"); - } catch (NumberFormatException e ) { + } catch (NumberFormatException e) { assert false : e; } return null; // nothing to return @@ -87,14 +90,14 @@ // (version >= 6.0) implies Vista or greater. if (version >= 6.0 && !preferIPv4Stack) { - useDualStackImpl = true; + useDualStackImplLocal = true; } if (exclBindProp != null) { // sun.net.useExclusiveBind is true - exclusiveBind = exclBindProp.length() == 0 ? true + exclusiveBindLocal = exclBindProp.length() == 0 ? true : Boolean.parseBoolean(exclBindProp); } else if (version < 6.0) { - exclusiveBind = false; + exclusiveBindLocal = false; } // impl.prefix @@ -103,12 +106,16 @@ prefix = AccessController.doPrivileged( new sun.security.action.GetPropertyAction("impl.prefix", null)); if (prefix != null) - prefixImplClass = Class.forName("java.net."+prefix+"DatagramSocketImpl"); + prefixImplClassLocal = Class.forName("java.net."+prefix+"DatagramSocketImpl"); } catch (Exception e) { System.err.println("Can't find class: java.net." + prefix + "DatagramSocketImpl: check impl.prefix property"); } + + prefixImplClass = prefixImplClassLocal; + useDualStackImpl = useDualStackImplLocal; + exclusiveBind = exclusiveBindLocal; } /** @@ -126,12 +133,10 @@ throw new SocketException("can't instantiate DatagramSocketImpl"); } } else { - if (isMulticast) - exclusiveBind = false; if (useDualStackImpl && !isMulticast) return new DualStackPlainDatagramSocketImpl(exclusiveBind); else - return new TwoStacksPlainDatagramSocketImpl(exclusiveBind); + return new TwoStacksPlainDatagramSocketImpl(exclusiveBind && !isMulticast); } } }
--- a/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/java/net/DualStackPlainDatagramSocketImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -45,6 +45,10 @@ { static JavaIOFileDescriptorAccess fdAccess = SharedSecrets.getJavaIOFileDescriptorAccess(); + static { + initIDs(); + } + // true if this socket is exclusively bound private final boolean exclusiveBind; @@ -288,4 +292,6 @@ int optionValue) throws SocketException; private static native int socketGetIntOption(int fd, int cmd) throws SocketException; + + native int dataAvailable(); }
--- a/src/windows/classes/java/net/TwoStacksPlainDatagramSocketImpl.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/java/net/TwoStacksPlainDatagramSocketImpl.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -207,6 +207,8 @@ protected native void disconnect0(int family); + native int dataAvailable(); + /** * Perform class load-time initializations. */
--- a/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/awt/windows/WEmbeddedFrame.java Thu Oct 29 17:12:06 2015 -0700 @@ -248,14 +248,6 @@ } } - @SuppressWarnings("deprecation") - public boolean requestFocusToEmbedder() { - if (isEmbeddedInIE) { - return ((WEmbeddedFramePeer) getPeer()).requestFocusToEmbedder(); - } - return false; - } - public void registerAccelerator(AWTKeyStroke stroke) {} public void unregisterAccelerator(AWTKeyStroke stroke) {}
--- a/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/awt/windows/WEmbeddedFramePeer.java Thu Oct 29 17:12:06 2015 -0700 @@ -79,10 +79,4 @@ return !Win32GraphicsEnvironment.isDWMCompositionEnabled(); } - /** - * Sets the focus to plugin control window, the parent of embedded frame. - * Eventually, it will synthesizeWindowActivation to activate the embedded frame, - * if plugin control window gets the focus. - */ - public native boolean requestFocusToEmbedder(); }
--- a/src/windows/classes/sun/nio/fs/WindowsConstants.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/nio/fs/WindowsConstants.java Thu Oct 29 17:12:06 2015 -0700 @@ -98,6 +98,7 @@ public static final int ERROR_DISK_FULL = 112; public static final int ERROR_INSUFFICIENT_BUFFER = 122; public static final int ERROR_INVALID_LEVEL = 124; + public static final int ERROR_DIR_NOT_ROOT = 144; public static final int ERROR_DIR_NOT_EMPTY = 145; public static final int ERROR_ALREADY_EXISTS = 183; public static final int ERROR_MORE_DATA = 234;
--- a/src/windows/classes/sun/nio/fs/WindowsFileStore.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/nio/fs/WindowsFileStore.java Thu Oct 29 17:12:06 2015 -0700 @@ -86,14 +86,28 @@ WindowsFileAttributes.get(file, true); target = file.getPathForWin32Calls(); } - String root = GetVolumePathName(target); - return new WindowsFileStore(root); + try { + return createFromPath(target); + } catch (WindowsException e) { + if (e.lastError() != ERROR_DIR_NOT_ROOT) + throw e; + target = WindowsLinkSupport.getFinalPath(file); + if (target == null) + throw new FileSystemException(file.getPathForExceptionMessage(), + null, "Couldn't resolve path"); + return createFromPath(target); + } } catch (WindowsException x) { x.rethrowAsIOException(file); return null; // keep compiler happy } } + private static WindowsFileStore createFromPath(String target) throws WindowsException { + String root = GetVolumePathName(target); + return new WindowsFileStore(root); + } + VolumeInformation volumeInformation() { return volInfo; }
--- a/src/windows/classes/sun/nio/fs/WindowsLinkSupport.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/nio/fs/WindowsLinkSupport.java Thu Oct 29 17:12:06 2015 -0700 @@ -66,7 +66,7 @@ * Returns the final path (all symbolic links resolved) or null if this * operation is not supported. */ - private static String getFinalPath(WindowsPath input) throws IOException { + static String getFinalPath(WindowsPath input) throws IOException { long h = 0; try { h = input.openForReadAttributeAccess(true);
--- a/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java Thu Oct 29 17:12:06 2015 -0700 @@ -37,6 +37,17 @@ private WindowsNativeDispatcher() { } /** + * HANDLE CreateEvent( + * LPSECURITY_ATTRIBUTES lpEventAttributes, + * BOOL bManualReset, + * BOOL bInitialState, + * PCTSTR lpName + * ); + */ + static native long CreateEvent(boolean bManualReset, boolean bInitialState) + throws WindowsException; + + /** * HANDLE CreateFile( * LPCTSTR lpFileName, * DWORD dwDesiredAccess, @@ -1041,6 +1052,25 @@ long pOverlapped) throws WindowsException; + + /** + * CancelIo( + * HANDLE hFile + * ) + */ + static native void CancelIo(long hFile) throws WindowsException; + + /** + * GetOverlappedResult( + * HANDLE hFile, + * LPOVERLAPPED lpOverlapped, + * LPDWORD lpNumberOfBytesTransferred, + * BOOL bWait + * ); + */ + static native int GetOverlappedResult(long hFile, long lpOverlapped) + throws WindowsException; + /** * BackupRead( * HANDLE hFile,
--- a/src/windows/classes/sun/nio/fs/WindowsWatchService.java Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/classes/sun/nio/fs/WindowsWatchService.java Thu Oct 29 17:12:06 2015 -0700 @@ -25,9 +25,16 @@ package sun.nio.fs; -import java.nio.file.*; import java.io.IOException; -import java.util.*; +import java.nio.file.NotDirectoryException; +import java.nio.file.Path; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + import com.sun.nio.file.ExtendedWatchEventModifier; import sun.misc.Unsafe; @@ -42,7 +49,6 @@ extends AbstractWatchService { private final static int WAKEUP_COMPLETION_KEY = 0; - private final Unsafe unsafe = Unsafe.getUnsafe(); // background thread to service I/O completion port private final Poller poller; @@ -82,7 +88,7 @@ /** * Windows implementation of WatchKey. */ - private class WindowsWatchKey extends AbstractWatchKey { + private static class WindowsWatchKey extends AbstractWatchKey { // file key (used to detect existing registrations) private final FileKey fileKey; @@ -169,15 +175,9 @@ return completionKey; } - // close directory and release buffer - void releaseResources() { - CloseHandle(handle); - buffer.cleaner().clean(); - } - - // Invalidate key by closing directory and releasing buffer + // Invalidate the key, assumes that resources have been released void invalidate() { - releaseResources(); + ((WindowsWatchService)watcher()).poller.releaseResources(this); handle = INVALID_HANDLE_VALUE; buffer = null; countAddress = 0; @@ -193,7 +193,7 @@ public void cancel() { if (isValid()) { // delegate to poller - poller.cancel(this); + ((WindowsWatchService)watcher()).poller.cancel(this); } } } @@ -241,18 +241,25 @@ /** * Background thread to service I/O completion port. */ - private class Poller extends AbstractPoller { + private static class Poller extends AbstractPoller { + private final static Unsafe UNSAFE = Unsafe.getUnsafe(); + /* * typedef struct _OVERLAPPED { - * DWORD Internal; - * DWORD InternalHigh; - * DWORD Offset; - * DWORD OffsetHigh; - * HANDLE hEvent; + * ULONG_PTR Internal; + * ULONG_PTR InternalHigh; + * union { + * struct { DWORD Offset; DWORD OffsetHigh; }; + * PVOID Pointer; + * }; + * HANDLE hEvent; * } OVERLAPPED; */ private static final short SIZEOF_DWORD = 4; private static final short SIZEOF_OVERLAPPED = 32; // 20 on 32-bit + private static final short OFFSETOF_HEVENT = + (UNSAFE.addressSize() == 4) ? (short) 16 : 24; + /* * typedef struct _FILE_NOTIFY_INFORMATION { @@ -276,10 +283,10 @@ private final long port; // maps completion key to WatchKey - private final Map<Integer,WindowsWatchKey> ck2key; + private final Map<Integer, WindowsWatchKey> ck2key; // maps file key to WatchKey - private final Map<FileKey,WindowsWatchKey> fk2key; + private final Map<FileKey, WindowsWatchKey> fk2key; // unique completion key for each directory // native completion key capacity is 64 bits on Win64. @@ -393,8 +400,13 @@ long overlappedAddress = bufferAddress + size - SIZEOF_OVERLAPPED; long countAddress = overlappedAddress - SIZEOF_DWORD; + // zero the overlapped structure + UNSAFE.setMemory(overlappedAddress, SIZEOF_OVERLAPPED, (byte)0); + // start async read of changes to directory try { + createAndAttachEvent(overlappedAddress); + ReadDirectoryChangesW(handle, bufferAddress, CHANGES_BUFFER_SIZE, @@ -403,6 +415,7 @@ countAddress, overlappedAddress); } catch (WindowsException x) { + closeAttachedEvent(overlappedAddress); buffer.release(); return new IOException(x.getMessage()); } @@ -421,7 +434,7 @@ // 2. release existing key's resources (handle/buffer) // 3. re-initialize key with new handle/buffer ck2key.remove(existing.completionKey()); - existing.releaseResources(); + releaseResources(existing); watchKey = existing.init(handle, events, watchSubtree, buffer, countAddress, overlappedAddress, completionKey); } @@ -436,6 +449,42 @@ } } + /** + * Cancels the outstanding I/O operation on the directory + * associated with the given key and releases the associated + * resources. + */ + private void releaseResources(WindowsWatchKey key) { + try { + CancelIo(key.handle()); + GetOverlappedResult(key.handle(), key.overlappedAddress()); + } catch (WindowsException expected) { + // expected as I/O operation has been cancelled + } + CloseHandle(key.handle()); + closeAttachedEvent(key.overlappedAddress()); + key.buffer().cleaner().clean(); + } + + /** + * Creates an unnamed event and set it as the hEvent field + * in the given OVERLAPPED structure + */ + private void createAndAttachEvent(long ov) throws WindowsException { + long hEvent = CreateEvent(false, false); + UNSAFE.putAddress(ov + OFFSETOF_HEVENT, hEvent); + } + + /** + * Closes the event attached to the given OVERLAPPED structure. A + * no-op if there isn't an event attached. + */ + private void closeAttachedEvent(long ov) { + long hEvent = UNSAFE.getAddress(ov + OFFSETOF_HEVENT); + if (hEvent != 0 && hEvent != INVALID_HANDLE_VALUE) + CloseHandle(hEvent); + } + // cancel single key @Override void implCancelKey(WatchKey obj) { @@ -451,9 +500,8 @@ @Override void implCloseAll() { // cancel all keys - for (Map.Entry<Integer, WindowsWatchKey> entry: ck2key.entrySet()) { - entry.getValue().invalidate(); - } + ck2key.values().forEach(WindowsWatchKey::invalidate); + fk2key.clear(); ck2key.clear(); @@ -462,8 +510,7 @@ } // Translate file change action into watch event - private WatchEvent.Kind<?> translateActionToEvent(int action) - { + private WatchEvent.Kind<?> translateActionToEvent(int action) { switch (action) { case FILE_ACTION_MODIFIED : return StandardWatchEventKinds.ENTRY_MODIFY; @@ -487,18 +534,18 @@ int nextOffset; do { - int action = unsafe.getInt(address + OFFSETOF_ACTION); + int action = UNSAFE.getInt(address + OFFSETOF_ACTION); // map action to event WatchEvent.Kind<?> kind = translateActionToEvent(action); if (key.events().contains(kind)) { // copy the name - int nameLengthInBytes = unsafe.getInt(address + OFFSETOF_FILENAMELENGTH); + int nameLengthInBytes = UNSAFE.getInt(address + OFFSETOF_FILENAMELENGTH); if ((nameLengthInBytes % 2) != 0) { - throw new AssertionError("FileNameLength.FileNameLength is not a multiple of 2"); + throw new AssertionError("FileNameLength is not a multiple of 2"); } char[] nameAsArray = new char[nameLengthInBytes/2]; - unsafe.copyMemory(null, address + OFFSETOF_FILENAME, nameAsArray, + UNSAFE.copyMemory(null, address + OFFSETOF_FILENAME, nameAsArray, Unsafe.ARRAY_CHAR_BASE_OFFSET, nameLengthInBytes); // create FileName and queue event @@ -508,7 +555,7 @@ } // next event - nextOffset = unsafe.getInt(address + OFFSETOF_NEXTENTRYOFFSET); + nextOffset = UNSAFE.getInt(address + OFFSETOF_NEXTENTRYOFFSET); address += (long)nextOffset; } while (nextOffset != 0); }
--- a/src/windows/native/common/jni_util_md.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/common/jni_util_md.c Thu Oct 29 17:12:06 2015 -0700 @@ -142,6 +142,15 @@ return (void*)GetModuleHandle(NULL); } +int +getErrorString(int err, char *buf, size_t len) +{ + int ret = 0; + if (err == 0 || len < 1) return 0; + ret = strerror_s(buf, len, err); + return ret; +} + /* * Windows symbols can be simple like JNI_OnLoad or __stdcall format * like _JNI_OnLoad@8. We need to handle both.
--- a/src/windows/native/java/net/AbstractPlainDatagramSocketImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include <windows.h> -#include <winsock2.h> - -#include "jvm.h" -#include "jni_util.h" -#include "net_util.h" - -#include "java_net_AbstractPlainDatagramSocketImpl.h" - -static jfieldID IO_fd_fdID = NULL; -static jfieldID apdsi_fdID = NULL; - -static jfieldID apdsi_fd1ID = NULL; -static jclass two_stacks_clazz = NULL; - - -/* - * Class: java_net_AbstractPlainDatagramSocketImpl - * Method: init - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_java_net_AbstractPlainDatagramSocketImpl_init(JNIEnv *env, jclass cls) { - - apdsi_fdID = (*env)->GetFieldID(env, cls, "fd", - "Ljava/io/FileDescriptor;"); - CHECK_NULL(apdsi_fdID); - IO_fd_fdID = NET_GetFileDescriptorID(env); - CHECK_NULL(IO_fd_fdID); - - two_stacks_clazz = (*env)->FindClass(env, "java/net/TwoStacksPlainDatagramSocketImpl"); - CHECK_NULL(two_stacks_clazz); - - /* Handle both TwoStacks and DualStack here */ - - if (JNU_Equals(env, cls, two_stacks_clazz)) { - /* fd1 present only in TwoStack.. */ - apdsi_fd1ID = (*env)->GetFieldID(env, cls, "fd1", - "Ljava/io/FileDescriptor;"); - CHECK_NULL(apdsi_fd1ID); - } - - JNU_CHECK_EXCEPTION(env); -} - -/* - * Class: java_net_AbstractPlainDatagramSocketImpl - * Method: dataAvailable - * Signature: ()I - */ -JNIEXPORT jint JNICALL Java_java_net_AbstractPlainDatagramSocketImpl_dataAvailable -(JNIEnv *env, jobject this) { - SOCKET fd; - SOCKET fd1; - int rv = -1, rv1 = -1; - jobject fdObj = (*env)->GetObjectField(env, this, apdsi_fdID); - - if (!IS_NULL(fdObj)) { - int retval = 0; - fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID); - rv = ioctlsocket(fd, FIONREAD, &retval); - if (retval > 0) { - return retval; - } - } - - if (!IS_NULL(apdsi_fd1ID)) { - /* TwoStacks */ - jobject fd1Obj = (*env)->GetObjectField(env, this, apdsi_fd1ID); - if (!IS_NULL(fd1Obj)) { - int retval = 0; - fd1 = (SOCKET)(*env)->GetIntField(env, fd1Obj, IO_fd_fdID); - rv1 = ioctlsocket(fd1, FIONREAD, &retval); - if (retval > 0) { - return retval; - } - } - } - - if (rv < 0 && rv1 < 0) { - JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", - "Socket closed"); - return -1; - } - - return 0; -} -
--- a/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/java/net/DualStackPlainDatagramSocketImpl.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -70,6 +70,25 @@ return got_icmp; } +static jfieldID IO_fd_fdID = NULL; +static jfieldID pdsi_fdID = NULL; + +/* + * Class: java_net_DualStackPlainDatagramSocketImpl + * Method: initIDs + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_initIDs + (JNIEnv *env, jclass clazz) +{ + pdsi_fdID = (*env)->GetFieldID(env, clazz, "fd", + "Ljava/io/FileDescriptor;"); + CHECK_NULL(pdsi_fdID); + IO_fd_fdID = NET_GetFileDescriptorID(env); + CHECK_NULL(IO_fd_fdID); + JNU_CHECK_EXCEPTION(env); +} + /* * Class: java_net_DualStackPlainDatagramSocketImpl * Method: socketCreate @@ -498,3 +517,32 @@ return result; } + +/* + * Class: java_net_DualStackPlainDatagramSocketImpl + * Method: dataAvailable + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_java_net_DualStackPlainDatagramSocketImpl_dataAvailable +(JNIEnv *env, jobject this) { + SOCKET fd; + int rv = -1; + jobject fdObj = (*env)->GetObjectField(env, this, pdsi_fdID); + + if (!IS_NULL(fdObj)) { + int retval = 0; + fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID); + rv = ioctlsocket(fd, FIONREAD, &retval); + if (retval > 0) { + return retval; + } + } + + if (rv < 0) { + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", + "Socket closed"); + return -1; + } + + return 0; +}
--- a/src/windows/native/java/net/Inet4AddressImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/java/net/Inet4AddressImpl.c Thu Oct 29 17:12:06 2015 -0700 @@ -31,6 +31,8 @@ #include <malloc.h> #include <sys/types.h> #include <process.h> +#include <iphlpapi.h> +#include <icmpapi.h> #include "java_net_InetAddress.h" #include "java_net_Inet4AddressImpl.h" @@ -297,114 +299,65 @@ * Returns true is an ECHO_REPLY is received, otherwise, false. */ static jboolean -ping4(JNIEnv *env, jint fd, struct sockaddr_in* him, jint timeout, - struct sockaddr_in* netif, jint ttl) { - jint size; - jint n, len, hlen1, icmplen; - char sendbuf[1500]; - char recvbuf[1500]; - struct icmp *icmp; - struct ip *ip; - WSAEVENT hEvent; - struct sockaddr sa_recv; - jint tmout2; - u_short pid, seq; - int read_rv = 0; +ping4(JNIEnv *env, + unsigned long src_addr, + unsigned long dest_addr, + jint timeout) +{ + // See https://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx - /* Initialize the sequence number to a suitable random number and - shift right one place to allow sufficient room for increamenting. */ - seq = ((unsigned short)rand()) >> 1; + HANDLE hIcmpFile; + DWORD dwRetVal = 0; + char SendData[32] = {0}; + LPVOID ReplyBuffer = NULL; + DWORD ReplySize = 0; - /* icmp_id is a 16 bit data type, therefore down cast the pid */ - pid = (u_short) _getpid(); - size = 60*1024; - setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char *) &size, sizeof(size)); - /** - * A TTL was specified, let's set the socket option. - */ - if (ttl > 0) { - setsockopt(fd, IPPROTO_IP, IP_TTL, (const char *) &ttl, sizeof(ttl)); + hIcmpFile = IcmpCreateFile(); + if (hIcmpFile == INVALID_HANDLE_VALUE) { + NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle"); + return JNI_FALSE; } - /** - * A network interface was specified, let's bind to it. - */ - if (netif != NULL) { - if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) { - NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket"); - closesocket(fd); + ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); + ReplyBuffer = (VOID*) malloc(ReplySize); + if (ReplyBuffer == NULL) { + IcmpCloseHandle(hIcmpFile); + NET_ThrowNew(env, WSAGetLastError(), "Unable to allocate memory"); return JNI_FALSE; - } } - /** - * Let's make the socket non blocking - */ - hEvent = WSACreateEvent(); - WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE); + if (src_addr == 0) { + dwRetVal = IcmpSendEcho(hIcmpFile, // HANDLE IcmpHandle, + dest_addr, // IPAddr DestinationAddress, + SendData, // LPVOID RequestData, + sizeof(SendData), // WORD RequestSize, + NULL, // PIP_OPTION_INFORMATION RequestOptions, + ReplyBuffer,// LPVOID ReplyBuffer, + ReplySize, // DWORD ReplySize, + timeout); // DWORD Timeout + } else { + dwRetVal = IcmpSendEcho2Ex(hIcmpFile, // HANDLE IcmpHandle, + NULL, // HANDLE Event + NULL, // PIO_APC_ROUTINE ApcRoutine + NULL, // ApcContext + src_addr, // IPAddr SourceAddress, + dest_addr, // IPAddr DestinationAddress, + SendData, // LPVOID RequestData, + sizeof(SendData), // WORD RequestSize, + NULL, // PIP_OPTION_INFORMATION RequestOptions, + ReplyBuffer,// LPVOID ReplyBuffer, + ReplySize, // DWORD ReplySize, + timeout); // DWORD Timeout + } - /** - * send 1 ICMP REQUEST every second until either we get a valid reply - * or the timeout expired. - */ - do { - /** - * construct the ICMP header - */ - memset(sendbuf, 0, 1500); - icmp = (struct icmp *) sendbuf; - icmp->icmp_type = ICMP_ECHO; - icmp->icmp_code = 0; - icmp->icmp_id = htons(pid); - icmp->icmp_seq = htons(seq); - /** - * checksum has to be set to zero before we can calculate the - * real checksum! - */ - icmp->icmp_cksum = 0; - icmp->icmp_cksum = in_cksum((u_short *)icmp, 64); - /** - * Ping! - */ - n = sendto(fd, sendbuf, 64, 0, (struct sockaddr *)him, - sizeof(struct sockaddr)); - if (n < 0 && WSAGetLastError() != WSAEWOULDBLOCK) { - NET_ThrowNew(env, WSAGetLastError(), "Can't send ICMP packet"); - closesocket(fd); - WSACloseEvent(hEvent); + free(ReplyBuffer); + IcmpCloseHandle(hIcmpFile); + + if (dwRetVal != 0) { + return JNI_TRUE; + } else { return JNI_FALSE; - } - - /* - * wait for 1 second at most - */ - tmout2 = timeout > 1000 ? 1000 : timeout; - do { - tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2); - if (tmout2 >= 0) { - len = sizeof(sa_recv); - n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, &sa_recv, &len); - ip = (struct ip*) recvbuf; - hlen1 = (ip->ip_hl) << 2; - icmp = (struct icmp *) (recvbuf + hlen1); - icmplen = n - hlen1; - /** - * Is that a proper ICMP reply? - */ - if (icmplen >= 8 && icmp->icmp_type == ICMP_ECHOREPLY && - (ntohs(icmp->icmp_seq) == seq) && (ntohs(icmp->icmp_id) == pid)) { - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_TRUE; - } - } - } while (tmout2 > 0); - timeout -= 1000; - seq++; - } while (timeout > 0); - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_FALSE; + } } /* @@ -418,15 +371,9 @@ jint timeout, jbyteArray ifArray, jint ttl) { - jint addr; + jint src_addr = 0; + jint dest_addr = 0; jbyte caddr[4]; - jint fd; - struct sockaddr_in him; - struct sockaddr_in* netif = NULL; - struct sockaddr_in inf; - int len = 0; - WSAEVENT hEvent; - int connect_rv = -1; int sz; /** @@ -436,143 +383,27 @@ if (sz != 4) { return JNI_FALSE; } - memset((char *) &him, 0, sizeof(him)); memset((char *) caddr, 0, sizeof(caddr)); (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr); - addr = ((caddr[0]<<24) & 0xff000000); - addr |= ((caddr[1] <<16) & 0xff0000); - addr |= ((caddr[2] <<8) & 0xff00); - addr |= (caddr[3] & 0xff); - addr = htonl(addr); - /** - * Socket address - */ - him.sin_addr.s_addr = addr; - him.sin_family = AF_INET; - len = sizeof(him); + dest_addr = ((caddr[0]<<24) & 0xff000000); + dest_addr |= ((caddr[1] <<16) & 0xff0000); + dest_addr |= ((caddr[2] <<8) & 0xff00); + dest_addr |= (caddr[3] & 0xff); + dest_addr = htonl(dest_addr); /** * If a network interface was specified, let's convert its address * as well. */ if (!(IS_NULL(ifArray))) { - memset((char *) caddr, 0, sizeof(caddr)); - (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr); - addr = ((caddr[0]<<24) & 0xff000000); - addr |= ((caddr[1] <<16) & 0xff0000); - addr |= ((caddr[2] <<8) & 0xff00); - addr |= (caddr[3] & 0xff); - addr = htonl(addr); - inf.sin_addr.s_addr = addr; - inf.sin_family = AF_INET; - inf.sin_port = 0; - netif = &inf; - } - -#if 0 - /* - * Windows implementation of ICMP & RAW sockets is too unreliable for now. - * Therefore it's best not to try it at all and rely only on TCP - * We may revisit and enable this code in the future. - */ - - /* - * Let's try to create a RAW socket to send ICMP packets - * This usually requires "root" privileges, so it's likely to fail. - */ - fd = NET_Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - if (fd != -1) { - /* - * It didn't fail, so we can use ICMP_ECHO requests. - */ - return ping4(env, fd, &him, timeout, netif, ttl); - } -#endif - - /* - * Can't create a raw socket, so let's try a TCP socket - */ - fd = NET_Socket(AF_INET, SOCK_STREAM, 0); - if (fd == JVM_IO_ERR) { - /* 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, WSAGetLastError(), "Can't create socket"); - return JNI_FALSE; - } - if (ttl > 0) { - setsockopt(fd, IPPROTO_IP, IP_TTL, (const char *)&ttl, sizeof(ttl)); - } - /* - * A network interface was specified, so let's bind to it. - */ - if (netif != NULL) { - if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) { - NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket"); - closesocket(fd); - return JNI_FALSE; - } + memset((char *) caddr, 0, sizeof(caddr)); + (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr); + src_addr = ((caddr[0]<<24) & 0xff000000); + src_addr |= ((caddr[1] <<16) & 0xff0000); + src_addr |= ((caddr[2] <<8) & 0xff00); + src_addr |= (caddr[3] & 0xff); + src_addr = htonl(src_addr); } - /* - * Make the socket non blocking so we can use select/poll. - */ - hEvent = WSACreateEvent(); - WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE); - - /* no need to use NET_Connect as non-blocking */ - him.sin_port = htons(7); /* Echo */ - connect_rv = connect(fd, (struct sockaddr *)&him, 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); - - /* has connection been established */ - - if (timeout >= 0) { - 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; + return ping4(env, src_addr, dest_addr, timeout); }
--- a/src/windows/native/java/net/Inet6AddressImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/java/net/Inet6AddressImpl.c Thu Oct 29 17:12:06 2015 -0700 @@ -31,6 +31,8 @@ #include <malloc.h> #include <sys/types.h> #include <process.h> +#include <iphlpapi.h> +#include <icmpapi.h> #include "java_net_InetAddress.h" #include "java_net_Inet4AddressImpl.h" @@ -366,139 +368,61 @@ * Returns true is an ECHO_REPLY is received, otherwise, false. */ static jboolean -ping6(JNIEnv *env, jint fd, struct SOCKADDR_IN6* him, jint timeout, - struct SOCKADDR_IN6* netif, jint ttl) { - jint size; - jint n, len, i; - char sendbuf[1500]; - char auxbuf[1500]; - unsigned char recvbuf[1500]; - struct icmp6_hdr *icmp6; - struct SOCKADDR_IN6 sa_recv; - unsigned short pid, seq; - int read_rv = 0; - WSAEVENT hEvent; - struct ip6_pseudo_hdr *pseudo_ip6; - int timestamp; - int tmout2; +ping6(JNIEnv *env, + struct sockaddr_in6* src, + struct sockaddr_in6* dest, + jint timeout) +{ + HANDLE hIcmpFile; + DWORD dwRetVal = 0; + char SendData[32] = {0}; + LPVOID ReplyBuffer = NULL; + DWORD ReplySize = 0; + IP_OPTION_INFORMATION ipInfo = {255, 0, 0, 0, NULL}; + struct sockaddr_in6 sa6Source; - /* Initialize the sequence number to a suitable random number and - shift right one place to allow sufficient room for increamenting. */ - seq = ((unsigned short)rand()) >> 1; - - /* icmp_id is a 16 bit data type, therefore down cast the pid */ - pid = (unsigned short) _getpid(); - - size = 60*1024; - setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char *)&size, sizeof(size)); - /** - * 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)); + hIcmpFile = Icmp6CreateFile(); + if (hIcmpFile == INVALID_HANDLE_VALUE) { + NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle"); + return JNI_FALSE; } - /** - * 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); + ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData); + ReplyBuffer = (VOID*) malloc(ReplySize); + if (ReplyBuffer == NULL) { + IcmpCloseHandle(hIcmpFile); + NET_ThrowNew(env, WSAGetLastError(), "Unable to allocate memory"); return JNI_FALSE; - } } - /* - * Make the socket non blocking - */ - hEvent = WSACreateEvent(); - WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE); - - /** - * send 1 ICMP REQUEST every second until either we get a valid reply - * or the timeout expired. - */ - do { - /* let's tag the ECHO packet with our pid so we can identify it */ - timestamp = GetCurrentTime(); - memset(sendbuf, 0, 1500); - icmp6 = (struct icmp6_hdr *) sendbuf; - icmp6->icmp6_type = ICMP6_ECHO_REQUEST; - icmp6->icmp6_code = 0; - icmp6->icmp6_id = htons(pid); - icmp6->icmp6_seq = htons(seq); - icmp6->icmp6_cksum = 0; - memcpy((icmp6 + 1), ×tamp, sizeof(int)); - if (netif != NULL) { - memset(auxbuf, 0, 1500); - pseudo_ip6 = (struct ip6_pseudo_hdr*) auxbuf; - memcpy(&pseudo_ip6->ip6_src, &netif->sin6_addr, sizeof(struct in6_addr)); - memcpy(&pseudo_ip6->ip6_dst, &him->sin6_addr, sizeof(struct in6_addr)); - pseudo_ip6->ip6_plen= htonl( 64 ); - pseudo_ip6->ip6_nxt = htonl( IPPROTO_ICMPV6 ); - memcpy(auxbuf + sizeof(struct ip6_pseudo_hdr), icmp6, 64); - /** - * We shouldn't have to do that as computing the checksum is supposed - * to be done by the IPv6 stack. Unfortunately windows, here too, is - * uterly broken, or non compliant, so let's do it. - * Problem is to compute the checksum I need to know the source address - * which happens only if I know the interface to be used... - */ - icmp6->icmp6_cksum = in_cksum((u_short *)pseudo_ip6, sizeof(struct ip6_pseudo_hdr) + 64); - } + //define local source information + sa6Source.sin6_addr = in6addr_any; + sa6Source.sin6_family = AF_INET6; + sa6Source.sin6_flowinfo = 0; + sa6Source.sin6_port = 0; - /** - * Ping! - */ - n = sendto(fd, sendbuf, 64, 0, (struct sockaddr*) him, sizeof(struct sockaddr_in6)); - if (n < 0 && (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEADDRNOTAVAIL)) { - // Happens when using a "tunnel interface" for instance. - // Or trying to send a packet on a different scope. - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_FALSE; - } - if (n < 0 && WSAGetLastError() != WSAEWOULDBLOCK) { - NET_ThrowNew(env, WSAGetLastError(), "Can't send ICMP packet"); - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_FALSE; - } - - tmout2 = timeout > 1000 ? 1000 : timeout; - do { - tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2); + dwRetVal = Icmp6SendEcho2(hIcmpFile, // HANDLE IcmpHandle, + NULL, // HANDLE Event, + NULL, // PIO_APC_ROUTINE ApcRoutine, + NULL, // PVOID ApcContext, + &sa6Source, // struct sockaddr_in6 *SourceAddress, + dest, // struct sockaddr_in6 *DestinationAddress, + SendData, // LPVOID RequestData, + sizeof(SendData), // WORD RequestSize, + &ipInfo, // PIP_OPTION_INFORMATION RequestOptions, + ReplyBuffer, // LPVOID ReplyBuffer, + ReplySize, // DWORD ReplySize, + timeout); // DWORD Timeout - if (tmout2 >= 0) { - len = sizeof(sa_recv); - memset(recvbuf, 0, 1500); - /** - * For some unknown reason, besides plain stupidity, windows - * truncates the first 4 bytes of the icmpv6 header some we can't - * check for the ICMP_ECHOREPLY value. - * we'll check the other values, though - */ - n = recvfrom(fd, recvbuf + 4, sizeof(recvbuf) - 4, 0, (struct sockaddr*) &sa_recv, &len); - icmp6 = (struct icmp6_hdr *) (recvbuf); - memcpy(&i, (icmp6 + 1), sizeof(int)); - /** - * Is that the reply we were expecting? - */ - if (n >= 8 && ntohs(icmp6->icmp6_seq) == seq && - ntohs(icmp6->icmp6_id) == pid && i == timestamp) { - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_TRUE; - } - } - } while (tmout2 > 0); - timeout -= 1000; - seq++; - } while (timeout > 0); - closesocket(fd); - WSACloseEvent(hEvent); - return JNI_FALSE; + free(ReplyBuffer); + IcmpCloseHandle(hIcmpFile); + + + if (dwRetVal != 0) { + return JNI_TRUE; + } else { + return JNI_FALSE; + } } #endif /* AF_INET6 */ @@ -516,11 +440,10 @@ jint ttl, jint if_scope) { #ifdef AF_INET6 jbyte caddr[16]; - jint fd, sz; + jint sz; struct sockaddr_in6 him6; struct sockaddr_in6* netif = NULL; struct sockaddr_in6 inf6; - WSAEVENT hEvent; int len = 0; int connect_rv = -1; @@ -552,6 +475,7 @@ him6.sin6_scope_id = scope; } len = sizeof(struct sockaddr_in6); + /** * A network interface was specified, let's convert the address */ @@ -565,123 +489,7 @@ inf6.sin6_scope_id = if_scope; netif = &inf6; } - -#if 0 - /* - * Windows implementation of ICMP & RAW sockets is too unreliable for now. - * Therefore it's best not to try it at all and rely only on TCP - * We may revisit and enable this code in the future. - */ - - /* - * Right now, windows doesn't generate the ICMP checksum automatically - * so we have to compute it, but we can do it only if we know which - * interface will be used. Therefore, don't try to use ICMP if no - * interface was specified. - * When ICMPv6 support improves in windows, we may change this. - */ - if (!(IS_NULL(ifArray))) { - /* - * If we can create a RAW socket, then when can use the ICMP ECHO_REQUEST - * otherwise we'll try a tcp socket to the Echo port (7). - * Note that this is empiric, and not connecting could mean it's blocked - * or the echo servioe has been disabled. - */ - fd = NET_Socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); - - if (fd != -1) { /* Good to go, let's do a ping */ - return ping6(env, fd, &him6, timeout, netif, ttl); - } - } -#endif - - /* No good, let's fall back on TCP */ - fd = NET_Socket(AF_INET6, SOCK_STREAM, 0); - if (fd == JVM_IO_ERR) { - /* 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 ping6(env, netif, &him6, timeout); #endif /* AF_INET6 */ return JNI_FALSE; }
--- a/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -2239,8 +2239,11 @@ optlen = sizeof(optval.i); if (NET_GetSockOpt(fd, level, optname, (void *)&optval, &optlen) < 0) { - char errmsg[255]; - sprintf(errmsg, "error getting socket option: %s\n", strerror(errno)); + char tmpbuf[255]; + int size = 0; + char errmsg[255 + 31]; + getErrorString(errno, tmpbuf, sizeof(tmpbuf)); + sprintf(errmsg, "error getting socket option: %s", tmpbuf); JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", errmsg); return NULL; } @@ -2591,3 +2594,44 @@ { mcast_join_leave (env, this, iaObj, niObj, JNI_FALSE); } + +/* + * Class: java_net_TwoStacksPlainDatagramSocketImpl + * Method: dataAvailable + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_java_net_TwoStacksPlainDatagramSocketImpl_dataAvailable +(JNIEnv *env, jobject this) { + SOCKET fd; + SOCKET fd1; + int rv = -1, rv1 = -1; + jobject fdObj = (*env)->GetObjectField(env, this, pdsi_fdID); + jobject fd1Obj; + + if (!IS_NULL(fdObj)) { + int retval = 0; + fd = (SOCKET)(*env)->GetIntField(env, fdObj, IO_fd_fdID); + rv = ioctlsocket(fd, FIONREAD, &retval); + if (retval > 0) { + return retval; + } + } + + fd1Obj = (*env)->GetObjectField(env, this, pdsi_fd1ID); + if (!IS_NULL(fd1Obj)) { + int retval = 0; + fd1 = (SOCKET)(*env)->GetIntField(env, fd1Obj, IO_fd_fdID); + rv1 = ioctlsocket(fd1, FIONREAD, &retval); + if (retval > 0) { + return retval; + } + } + + if (rv < 0 && rv1 < 0) { + JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", + "Socket closed"); + return -1; + } + + return 0; +}
--- a/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp Thu Oct 29 17:12:06 2015 -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 @@ -114,8 +114,9 @@ // which may've been disposed by this time, and we have // no means of checking against it. if (oldhDC != NULL) { - MoveDCToPassiveList(oldhDC); + MoveDCToPassiveList(oldhDC, info->hWnd); info->hDC = NULL; + info->hWnd = NULL; } if (wsdo->window != NULL){ @@ -150,6 +151,7 @@ // Finally, set these new values in the info for this thread info->hDC = hDC; + info->hWnd = wsdo->window; } // cached brush and pen are not associated with any DC, and can be @@ -187,7 +189,7 @@ if (info->hDC != NULL) { // move the DC from the active dcs list to // the passive dc list to be released later - MoveDCToPassiveList(info->hDC); + MoveDCToPassiveList(info->hDC, info->hWnd); } if (info->clip != NULL) {
--- a/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.h Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.h Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2010, 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 @@ -196,6 +196,7 @@ */ typedef struct { HDC hDC; + HWND hWnd; GDIWinSDOps *wsdo; LONG wsdoTimeStamp; // wsdo creation time stamp. // Other threads may deallocate wsdo
--- a/src/windows/native/sun/nio/ch/Net.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/nio/ch/Net.c Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -157,7 +157,7 @@ if (loopback_available) { int rv = NET_EnableFastTcpLoopback((jint)s); if (rv) { - if (rv == WSAEOPNOTSUPP) { + if (rv == WSAEOPNOTSUPP || rv == WSAEINVAL) { loopback_available = 0; } else { NET_ThrowNew(env, rv, "fastLoopback");
--- a/src/windows/native/sun/nio/fs/WindowsNativeDispatcher.c Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/nio/fs/WindowsNativeDispatcher.c Thu Oct 29 17:12:06 2015 -0700 @@ -195,6 +195,17 @@ } } +JNIEXPORT jlong JNICALL +Java_sun_nio_fs_WindowsNativeDispatcher_CreateEvent(JNIEnv* env, jclass this, + jboolean bManualReset, jboolean bInitialState) +{ + HANDLE hEvent = CreateEventW(NULL, bManualReset, bInitialState, NULL); + if (hEvent == NULL) { + throwWindowsException(env, GetLastError()); + } + return ptr_to_jlong(hEvent); +} + JNIEXPORT jstring JNICALL Java_sun_nio_fs_WindowsNativeDispatcher_FormatMessage(JNIEnv* env, jclass this, jint errorCode) { WCHAR message[255]; @@ -1230,23 +1241,38 @@ } JNIEXPORT void JNICALL +Java_sun_nio_fs_WindowsNativeDispatcher_CancelIo(JNIEnv* env, jclass this, jlong hFile) { + if (CancelIo((HANDLE)jlong_to_ptr(hFile)) == 0) { + throwWindowsException(env, GetLastError()); + } +} + +JNIEXPORT jint JNICALL +Java_sun_nio_fs_WindowsNativeDispatcher_GetOverlappedResult(JNIEnv *env, jclass this, + jlong hFile, jlong lpOverlapped) +{ + BOOL res; + DWORD bytesTransferred = -1; + + res = GetOverlappedResult((HANDLE)jlong_to_ptr(hFile), + (LPOVERLAPPED)jlong_to_ptr(lpOverlapped), + &bytesTransferred, + TRUE); + if (res == 0) { + throwWindowsException(env, GetLastError()); + } + + return (jint)bytesTransferred; +} + +JNIEXPORT void JNICALL Java_sun_nio_fs_WindowsNativeDispatcher_ReadDirectoryChangesW(JNIEnv* env, jclass this, jlong hDirectory, jlong bufferAddress, jint bufferLength, jboolean watchSubTree, jint filter, jlong bytesReturnedAddress, jlong pOverlapped) { BOOL res; BOOL subtree = (watchSubTree == JNI_TRUE) ? TRUE : FALSE; - - /* Any unused members of [OVERLAPPED] structure should always be initialized to zero - before the structure is used in a function call. - Otherwise, the function may fail and return ERROR_INVALID_PARAMETER. - http://msdn.microsoft.com/en-us/library/windows/desktop/ms684342%28v=vs.85%29.aspx - - The [Offset] and [OffsetHigh] members of this structure are not used. - http://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx - - [hEvent] should be zero, other fields are the return values. */ - ZeroMemory((LPOVERLAPPED)jlong_to_ptr(pOverlapped), sizeof(OVERLAPPED)); + LPOVERLAPPED ov = (LPOVERLAPPED)jlong_to_ptr(pOverlapped); res = ReadDirectoryChangesW((HANDLE)jlong_to_ptr(hDirectory), (LPVOID)jlong_to_ptr(bufferAddress),
--- a/src/windows/native/sun/windows/awt_Component.cpp Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/windows/awt_Component.cpp Thu Oct 29 17:12:06 2015 -0700 @@ -1382,7 +1382,7 @@ case WM_AWT_RELEASEDC: { HDC hDC = (HDC)wParam; - MoveDCToPassiveList(hDC); + MoveDCToPassiveList(hDC, GetHWnd()); ReleaseDCList(GetHWnd(), passiveDCList); mr = mrConsume; break; @@ -7174,8 +7174,8 @@ } /** - * Given a DC, remove it from the DC list and return - * TRUE if it exists on the current list. Otherwise + * Given a DC and window handle, remove the DC from the DC list + * and return TRUE if it exists on the current list. Otherwise * return FALSE. * A DC may not exist on the list because it has already * been released elsewhere (for example, the window @@ -7183,14 +7183,14 @@ * thread may also want to release a DC when it notices that * its DC is obsolete for the current window). */ -DCItem *DCList::RemoveDC(HDC hDC) +DCItem *DCList::RemoveDC(HDC hDC, HWND hWnd) { listLock.Enter(); DCItem **prevPtrPtr = &head; DCItem *listPtr = head; while (listPtr) { DCItem *nextPtr = listPtr->next; - if (listPtr->hDC == hDC) { + if (listPtr->hDC == hDC && listPtr->hWnd == hWnd) { *prevPtrPtr = nextPtr; break; } @@ -7244,9 +7244,9 @@ listLock.Leave(); } -void MoveDCToPassiveList(HDC hDC) { +void MoveDCToPassiveList(HDC hDC, HWND hWnd) { DCItem *removedDC; - if ((removedDC = activeDCList.RemoveDC(hDC)) != NULL) { + if ((removedDC = activeDCList.RemoveDC(hDC, hWnd)) != NULL) { passiveDCList.AddDCItem(removedDC); } }
--- a/src/windows/native/sun/windows/awt_Component.h Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/windows/awt_Component.h Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -900,13 +900,13 @@ void AddDC(HDC hDC, HWND hWnd); void AddDCItem(DCItem *newItem); - DCItem *RemoveDC(HDC hDC); + DCItem *RemoveDC(HDC hDC, HWND hWnd); DCItem *RemoveAllDCs(HWND hWnd); void RealizePalettes(int screen); }; void ReleaseDCList(HWND hwnd, DCList &list); -void MoveDCToPassiveList(HDC hDC); +void MoveDCToPassiveList(HDC hDC, HWND hWnd); namespace TimeHelper{ jlong getMessageTimeUTC();
--- a/src/windows/native/sun/windows/awt_Frame.cpp Wed Oct 21 20:59:47 2015 +0300 +++ b/src/windows/native/sun/windows/awt_Frame.cpp Thu Oct 29 17:12:06 2015 -0700 @@ -1961,29 +1961,6 @@ CATCH_BAD_ALLOC; } -JNIEXPORT jboolean JNICALL -Java_sun_awt_windows_WEmbeddedFramePeer_requestFocusToEmbedder(JNIEnv *env, jobject self) -{ - jboolean result = JNI_FALSE; - - TRY; - - AwtFrame *frame = NULL; - - PDATA pData; - JNI_CHECK_PEER_GOTO(self, ret); - frame = (AwtFrame *)pData; - - // JDK-8056915: During initial applet activation, set focus to plugin control window - HWND hwndParent = ::GetParent(frame->GetHWnd()); - - result = SetFocusToPluginControl(hwndParent); - - CATCH_BAD_ALLOC_RET(JNI_FALSE); -ret: - return result; -} - } /* extern "C" */ static bool SetFocusToPluginControl(HWND hwndPlugin)
--- a/test/TEST.groups Wed Oct 21 20:59:47 2015 +0300 +++ b/test/TEST.groups Thu Oct 29 17:12:06 2015 -0700 @@ -327,6 +327,7 @@ java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java \ java/lang/invoke/lambda/LambdaAccessControlTest.java \ java/lang/invoke/lambda/LambdaAsm.java \ + java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java \ java/lang/System/MacEncoding/TestFileEncoding.java \ java/net/URLClassLoader/closetest/GetResourceAsStream.java \ java/util/Collections/EmptyIterator.java \ @@ -489,7 +490,6 @@ java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java \ java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java \ java/lang/System/MacEncoding/TestFileEncoding.java \ - java/lang/Class/getDeclaredField/FieldSetAccessibleTest.java \ java/nio/channels/AsynchronousSocketChannel/Leaky.java \ java/security/PermissionCollection/Concurrent.java \ java/security/Principal/Implies.java \
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/awt/Toolkit/AutoShutdown/EventQueuePush/EventQueuePushAutoshutdown.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,75 @@ +/* + * 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 8081485 + @summary tests that a program terminates automatically after EventQueue.push() + @author Anton Nashatyrev : area=toolkit +*/ + +import java.awt.*; + +public class EventQueuePushAutoshutdown implements Runnable { + private volatile int status = 2; + + public EventQueuePushAutoshutdown() throws Exception { + Runtime.getRuntime().addShutdownHook(new Thread(this)); + Thread thread = new Thread() { + @Override + public void run() { + status = 0; + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } finally { + status = 1; + System.exit(status); + } + } + }; + thread.setDaemon(true); + thread.start(); + + System.setProperty("java.awt.headless", "true"); + final EventQueue systemQueue = Toolkit.getDefaultToolkit().getSystemEventQueue(); + systemQueue.push(new EventQueue()); + EventQueue.invokeAndWait(new Runnable() { + @Override + public void run() { + System.out.println("Activated EDT"); + } + }); + System.out.println("After EDT activation"); + } + + public static void main(String[] args) throws Exception { + new EventQueuePushAutoshutdown(); + } + + @Override + public void run() { + Runtime.getRuntime().halt(status); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/awt/Toolkit/AutoShutdown/EventQueuePush/EventQueuePushAutoshutdown.sh Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,159 @@ +#!/bin/ksh -p + +# +# Copyright (c) 20015, 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 EventQueuePushAutoshutdown.sh +# @bug 8081485 +# @summary tests that a program terminates automatically +# after EventQueue.push() +# @author Anton Nashatyrev : area=toolkit +# +# @compile EventQueuePushAutoshutdown.java +# @run shell EventQueuePushAutoshutdown.sh + + +# Beginning of subroutines: +status=1 + +#Call this from anywhere to fail the test with an error message +# usage: fail "reason why the test failed" +fail() + { echo "The test failed :-(" + echo "$*" 1>&2 + echo "exit status was $status" + exit $status + } #end of fail() + +#Call this from anywhere to pass the test with a message +# usage: pass "reason why the test passed if applicable" +pass() + { echo "The test passed!!!" + echo "$*" 1>&2 + exit 0 + } #end of pass() + +# end of subroutines + + +# The beginning of the script proper +OS=`uname -s` +case "$OS" in + SunOS | Linux | Darwin | CYGWIN* ) + FILESEP="/" + ;; + + Windows_95 | Windows_98 | Windows_NT | Windows_ME ) + FILESEP="\\" + ;; + + # catch all other OSs + * ) + echo "Unrecognized system! $OS" + fail "Unrecognized system! $OS" + ;; +esac + + +# Want this test to run standalone as well as in the harness, so do the +# following to copy the test's directory into the harness's scratch directory +# and set all appropriate variables: + +if [ -z "${TESTJAVA}" ] ; then + # TESTJAVA is not set, so the test is running stand-alone. + # TESTJAVA holds the path to the root directory of the build of the JDK + # to be tested. That is, any java files run explicitly in this shell + # should use TESTJAVA in the path to the java interpreter. + # So, we'll set this to the JDK spec'd on the command line. If none + # is given on the command line, tell the user that and use a cheesy + # default. + # THIS IS THE JDK BEING TESTED. + if [ -n "$1" ] ; + then TESTJAVA=$1 + else fail "no JDK specified on command line!" + fi + TESTSRC=. + TESTCLASSES=. + STANDALONE=1; +fi +echo "JDK under test is: $TESTJAVA" + +#Deal with .class files: +if [ -n "${STANDALONE}" ] ; + then + #if standalone, remind user to cd to dir. containing test before running it + echo "Just a reminder: cd to the dir containing this test when running it" + # then compile all .java files (if there are any) into .class files + if [ -a *.java ] ; + then echo "Reminder, this test should be in its own directory with all" + echo "supporting files it needs in the directory with it." + ${TESTJAVA}/bin/javac ./*.java ; + fi + # else in harness so copy all the class files from where jtreg put them + # over to the scratch directory this test is running in. + else cp ${TESTCLASSES}/*.class . ; +fi + +#if in test harness, then copy the entire directory that the test is in over +# to the scratch directory. This catches any support files needed by the test. +if [ -z "${STANDALONE}" ] ; + then cp ${TESTSRC}/* . +fi + +#Just before executing anything, make sure it has executable permission! +chmod 777 ./* + +############### YOUR TEST CODE HERE!!!!!!! ############# + +#All files required for the test should be in the same directory with +# this file. If converting a standalone test to run with the harness, +# as long as all files are in the same directory and it returns 0 for +# pass, you should be able to cut and paste it into here and it will +# run with the test harness. + +${TESTJAVA}/bin/java EventQueuePushAutoshutdown + +############### END YOUR TEST CODE !!!!! ############ +#Be sure the last command executed above this line returns 0 for success, +# something non-zero for failure. +status=$? + +# pass or fail the test based on status of the command +case "$status" in + 0 ) + pass "" + ;; + + 1 ) + fail "The program didn't automatically shut down" + ;; + + * ) + fail "The program terminated unexpectedly!" + ;; +esac + +#For additional examples of how to write platform independent KSH scripts, +# see the jtreg file itself. It is a KSH script for both Solaris and Win32 +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,368 @@ +/* + * 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 8081787 8136763 + @author Mikhail Cherkasov + @run main/manual MacOsXFileAndMultipleFileCopingTest +*/ + +import javax.swing.*; +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.net.URL; + +public class MacOsXFileAndMultipleFileCopingTest { + private static void init() { + String[] instructions = + {"Test for MacOS X only:", + "1. The aim is to test that java works fine with \"application/" + + "x-java-url;class=java.net.URL\"falvor and support coping of multiple files", + "2. Open finder and select any file.", + "3. Press CMD+C or press \"Copy\" in context menu", + "4. Focus window with \"Test URL\" Button.", + "5. If you see URL for selected file, then test PASSED,", + "otherwise test FAILED.", + + "6. Open finder again and select several files.", + "7. Press CMD+C or press \"Copy\" in context menu", + "8. Focus window with \"Test multiple files coping\" Button.", + "9. If you see list of selected files, then test PASSED,", + "otherwise test FAILED.", + + }; + + Sysout.createDialog(); + Sysout.printInstructions(instructions); + + final Frame frame = new Frame(); + Panel panel = new Panel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); + + frame.add(panel); + Button testUrlBtn = new Button("Test URL"); + final TextArea textArea = new TextArea(5, 80); + testUrlBtn.addActionListener(new AbstractAction() { + @Override + public void actionPerformed(ActionEvent ae) { + try { + Clipboard board = Toolkit.getDefaultToolkit().getSystemClipboard(); + URL url = (URL) board.getData(new DataFlavor("application/x-java-url;class=java.net.URL")); + textArea.setText(url.toString()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + panel.add(testUrlBtn); + Button testUriList = new Button("Test multiple files coping"); + testUriList.addActionListener(new AbstractAction() { + @Override + public void actionPerformed(ActionEvent ae) { + try { + Clipboard board = Toolkit.getDefaultToolkit().getSystemClipboard(); + String files = (String) board.getData(new DataFlavor("text/uri-list;class=java.lang.String")); + textArea.setText(files); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + panel.add(testUriList); + panel.add(textArea); + frame.setBounds(200, 200, 400, 400); + frame.setVisible(true); + + }//End init() + + + /***************************************************** + * Standard Test Machinery Section + * DO NOT modify anything in this section -- it's a + * standard chunk of code which has all of the + * synchronisation necessary for the test harness. + * By keeping it the same in all tests, it is easier + * to read and understand someone else's test, as + * well as insuring that all tests behave correctly + * with the test harness. + * There is a section following this for test-defined + * classes + ******************************************************/ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + + private static Thread mainThread = null; + + private static int sleepTime = 300000; + + public static void main(String args[]) throws InterruptedException { + if (!System.getProperty("os.name").startsWith("Mac")) { + return; + } + mainThread = Thread.currentThread(); + try { + init(); + } catch (TestPassedException e) { + //The test passed, so just return from main and harness will + // interepret this return as a pass + return; + } + //At this point, neither test passed nor test failed has been + // called -- either would have thrown an exception and ended the + // test, so we know we have multiple threads. + + //Test involves other threads, so sleep and wait for them to + // called pass() or fail() + try { + Thread.sleep(sleepTime); + //Timed out, so fail the test + throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds"); + } catch (InterruptedException e) { + if (!testGeneratedInterrupt) throw e; + + //reset flag in case hit this code more than once for some reason (just safety) + testGeneratedInterrupt = false; + if (theTestPassed == false) { + throw new RuntimeException(failureMessage); + } + } + + }//main + + public static synchronized void setTimeoutTo(int seconds) { + sleepTime = seconds * 1000; + } + + public static synchronized void pass() { + Sysout.println("The test passed."); + Sysout.println("The test is over, hit Ctl-C to stop Java VM"); + //first check if this is executing in main thread + if (mainThread == Thread.currentThread()) { + //Still in the main thread, so set the flag just for kicks, + // and throw a test passed exception which will be caught + // and end the test. + theTestPassed = true; + throw new TestPassedException(); + } + //pass was called from a different thread, so set the flag and interrupt + // the main thead. + theTestPassed = true; + testGeneratedInterrupt = true; + if (mainThread != null) { + mainThread.interrupt(); + } + }//pass() + + public static synchronized void fail() { + //test writer didn't specify why test failed, so give generic + fail("it just plain failed! :-)"); + } + + public static synchronized void fail(String whyFailed) { + Sysout.println("The test failed: " + whyFailed); + Sysout.println("The test is over, hit Ctl-C to stop Java VM"); + //check if this called from main thread + if (mainThread == Thread.currentThread()) { + //If main thread, fail now 'cause not sleeping + throw new RuntimeException(whyFailed); + } + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + }//fail() + +}// class ManualMainTest + +//This exception is used to exit from any level of call nesting +// when it's determined that the test has passed, and immediately +// end the test. +class TestPassedException extends RuntimeException { +} + +//*********** End Standard Test Machinery Section ********** + + +/**************************************************** + * Standard Test Machinery + * DO NOT modify anything below -- it's a standard + * chunk of code whose purpose is to make user + * interaction uniform, and thereby make it simpler + * to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout { + private static TestDialog dialog; + private static boolean numbering = false; + private static int messageNumber = 0; + + public static void createDialogWithInstructions(String[] instructions) { + dialog = new TestDialog(new Frame(), "Instructions"); + dialog.printInstructions(instructions); + dialog.setVisible(true); + println("Any messages for the tester will display here."); + } + + public static void createDialog() { + dialog = new TestDialog(new Frame(), "Instructions"); + String[] defInstr = {"Instructions will appear here. ", ""}; + dialog.printInstructions(defInstr); + dialog.setVisible(true); + println("Any messages for the tester will display here."); + } + + + /* Enables message counting for the tester. */ + public static void enableNumbering(boolean enable) { + numbering = enable; + } + + public static void printInstructions(String[] instructions) { + dialog.printInstructions(instructions); + } + + + public static void println(String messageIn) { + if (numbering) { + messageIn = "" + messageNumber + " " + messageIn; + messageNumber++; + } + dialog.displayMessage(messageIn); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog implements ActionListener { + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + Panel buttonP = new Panel(); + Button passB = new Button("pass"); + Button failB = new Button("fail"); + + //DO NOT call this directly, go through Sysout + public TestDialog(Frame frame, String name) { + super(frame, name); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); + add("North", instructionsText); + + messageText = new TextArea("", 5, maxStringLength, scrollBoth); + add("Center", messageText); + + passB = new Button("pass"); + passB.setActionCommand("pass"); + passB.addActionListener(this); + buttonP.add("East", passB); + + failB = new Button("fail"); + failB.setActionCommand("fail"); + failB.addActionListener(this); + buttonP.add("West", failB); + + add("South", buttonP); + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions(String[] instructions) { + //Clear out any current instructions + instructionsText.setText(""); + + //Go down array of instruction strings + + String printStr, remainingStr; + for (int i = 0; i < instructions.length; i++) { + //chop up each into pieces maxSringLength long + remainingStr = instructions[i]; + while (remainingStr.length() > 0) { + //if longer than max then chop off first max chars to print + if (remainingStr.length() >= maxStringLength) { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf(' ', maxStringLength - 1); + + if (posOfSpace <= 0) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring(0, posOfSpace + 1); + remainingStr = remainingStr.substring(posOfSpace + 1); + } + //else just print + else { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append(printStr + "\n"); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage(String messageIn) { + messageText.append(messageIn + "\n"); + System.out.println(messageIn); + } + + //catch presses of the passed and failed buttons. + //simply call the standard pass() or fail() static methods of + //ManualMainTest + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand() == "pass") { + MacOsXFileAndMultipleFileCopingTest.pass(); + } else { + MacOsXFileAndMultipleFileCopingTest.fail(); + } + } + +}// TestDialog class \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/awt/dnd/MissingEventsOnModalDialog/MissingEventsOnModalDialogTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,237 @@ +/* + * 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.awt.Dialog; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DragGestureEvent; +import java.awt.dnd.DragGestureListener; +import java.awt.dnd.DragSource; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/* + * @test + * @bug 8134917 + * @summary [macosx] JOptionPane doesn't receive mouse events when opened from a drop event + * @author Alexandr Scherbatiy + */ +public class MissingEventsOnModalDialogTest { + + private static volatile boolean passed = false; + + public static void main(String[] args) throws Exception { + Frame sourceFrame = createFrame("Source Frame", 0, 0); + Frame targetFrame = createFrame("Target Frame", 250, 250); + + DragSource defaultDragSource + = DragSource.getDefaultDragSource(); + defaultDragSource.createDefaultDragGestureRecognizer(sourceFrame, + DnDConstants.ACTION_COPY_OR_MOVE, + new TestDragGestureListener()); + new DropTarget(targetFrame, DnDConstants.ACTION_COPY_OR_MOVE, + new TestDropTargetListener(targetFrame)); + + Robot robot = new Robot(); + robot.setAutoDelay(50); + + sourceFrame.toFront(); + robot.waitForIdle(); + + Point point = getCenterPoint(sourceFrame); + robot.mouseMove(point.x, point.y); + robot.waitForIdle(); + + mouseDragAndDrop(robot, point, getCenterPoint(targetFrame)); + + long time = System.currentTimeMillis() + 200; + + while (!passed) { + if (time < System.currentTimeMillis()) { + sourceFrame.dispose(); + targetFrame.dispose(); + throw new RuntimeException("Mouse clicked event is lost!"); + } + Thread.sleep(10); + } + sourceFrame.dispose(); + targetFrame.dispose(); + } + + private static Frame createFrame(String title, int x, int y) { + Frame frame = new Frame(); + frame.setSize(200, 200); + frame.setLocation(x, y); + frame.setTitle(title); + frame.setVisible(true); + return frame; + } + + private static Point getCenterPoint(Window window) { + Point centerPoint = window.getLocationOnScreen(); + centerPoint.translate(window.getWidth() / 2, window.getHeight() / 2); + return centerPoint; + } + + public static void mouseDragAndDrop(Robot robot, Point from, Point to) { + mouseDND(robot, from.x, from.y, to.x, to.y); + } + + public static void mouseDND(Robot robot, int x1, int y1, int x2, int y2) { + + int N = 20; + int x = x1; + int y = y1; + int dx = (x2 - x1) / N; + int dy = (y2 - y1) / N; + + robot.mousePress(InputEvent.BUTTON1_MASK); + + for (int i = 0; i < N; i++) { + robot.mouseMove(x += dx, y += dy); + } + + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + + private static class TestDragGestureListener implements DragGestureListener { + + public void dragGestureRecognized(DragGestureEvent dge) { + dge.startDrag(null, new StringTransferable()); + } + } + + static class StringTransferable implements Transferable { + + @Override + public DataFlavor[] getTransferDataFlavors() { + return new DataFlavor[]{DataFlavor.stringFlavor}; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return flavor.equals(DataFlavor.stringFlavor); + } + + @Override + public Object getTransferData(DataFlavor flavor) { + return "Hello World!"; + } + } + + private static class TestDropTargetListener implements DropTargetListener { + + private final Frame targetFrame; + + public TestDropTargetListener(Frame targetFrame) { + this.targetFrame = targetFrame; + } + + @Override + public void dragEnter(DropTargetDragEvent dtde) { + dtde.acceptDrag(dtde.getDropAction()); + } + + @Override + public void dragOver(DropTargetDragEvent dtde) { + dtde.acceptDrag(dtde.getDropAction()); + } + + @Override + public void dropActionChanged(DropTargetDragEvent dtde) { + dtde.acceptDrag(dtde.getDropAction()); + } + + @Override + public void dragExit(DropTargetEvent dte) { + } + + @Override + public void drop(DropTargetDropEvent dtde) { + dtde.acceptDrop(dtde.getDropAction()); + showModalDialog(targetFrame); + dtde.dropComplete(true); + } + } + + private static void showModalDialog(Frame targetFrame) { + + Dialog dialog = new Dialog(targetFrame, true); + + dialog.addMouseListener(new MouseAdapter() { + + @Override + public void mouseClicked(MouseEvent e) { + passed = true; + dialog.dispose(); + } + }); + + dialog.setSize(400, 300); + dialog.setTitle("Modal Dialog!"); + + clickOnModalDialog(dialog); + dialog.setVisible(true); + } + + private static void clickOnModalDialog(Dialog dialog) { + new Thread(() -> { + clickOnDialog(dialog); + }).start(); + } + + private static void clickOnDialog(Dialog dialog) { + try { + long time = System.currentTimeMillis() + 200; + + while (!dialog.isVisible()) { + if (time < System.currentTimeMillis()) { + throw new RuntimeException("Dialog is not visible!"); + } + Thread.sleep(10); + } + + Point point = getCenterPoint(dialog); + Robot robot = new Robot(); + robot.setAutoDelay(50); + + robot.mouseMove(point.x, point.y); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } +}
--- a/test/java/lang/invoke/ExplicitCastArgumentsTest.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/lang/invoke/ExplicitCastArgumentsTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -21,79 +21,582 @@ * questions. */ -package java.lang.invoke; - +import com.oracle.testlibrary.jsr292.Helper; +import java.io.File; +import java.io.Serializable; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.invoke.WrongMethodTypeException; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; import sun.invoke.util.Wrapper; -/* @test +/* + * @test + * @bug 8060483 8066746 + * @library /lib/testlibrary /lib/testlibrary/jsr292 * @summary unit tests for MethodHandles.explicitCastArguments() - * - * @run main/bootclasspath java.lang.invoke.ExplicitCastArgumentsTest + * @run main ExplicitCastArgumentsTest + */ + +/** + * Tests for MethodHandles.explicitCastArguments(). */ public class ExplicitCastArgumentsTest { - private static final boolean VERBOSE = Boolean.getBoolean("verbose"); + + private static final boolean VERBOSE = Helper.IS_VERBOSE; private static final Class<?> THIS_CLASS = ExplicitCastArgumentsTest.class; + private static final Random RNG = Helper.RNG; + private static final Map<Wrapper, Object> RANDOM_VALUES = new HashMap<>(9); + + static { + RANDOM_VALUES.put(Wrapper.BOOLEAN, RNG.nextBoolean()); + RANDOM_VALUES.put(Wrapper.BYTE, (byte) RNG.nextInt()); + RANDOM_VALUES.put(Wrapper.SHORT, (short) RNG.nextInt()); + RANDOM_VALUES.put(Wrapper.CHAR, (char) RNG.nextInt()); + RANDOM_VALUES.put(Wrapper.INT, RNG.nextInt()); + RANDOM_VALUES.put(Wrapper.LONG, RNG.nextLong()); + RANDOM_VALUES.put(Wrapper.FLOAT, RNG.nextFloat()); + RANDOM_VALUES.put(Wrapper.DOUBLE, RNG.nextDouble()); + RANDOM_VALUES.put(Wrapper.OBJECT, new Object()); + } public static void main(String[] args) throws Throwable { testVarargsCollector(); + testNullRef2Prim(); testRef2Prim(); + testPrim2Ref(); + testPrim2Prim(); + testNonBCPRef2NonBCPRef(); + testBCPRef2BCPRef(); + testNonBCPRef2BCPRef(); + testReturnAny2Void(); + testReturnVoid2Any(); + testMultipleArgs(); System.out.println("TEST PASSED"); } - public static String[] f(String... args) { return args; } + /** + * Dummy method used in {@link #testVarargsCollector} test to form a method + * handle. + * + * @param args - any args + * @return - returns args + */ + public static String[] f(String... args) { + return args; + } + /** + * Tests that MHs.explicitCastArguments does incorrect type checks for + * VarargsCollector. Bug 8066746. + * + * @throws java.lang.Throwable + */ public static void testVarargsCollector() throws Throwable { MethodType mt = MethodType.methodType(String[].class, String[].class); - MethodHandle mh = MethodHandles.publicLookup().findStatic(THIS_CLASS, "f", mt); - mh = MethodHandles.explicitCastArguments(mh, MethodType.methodType(Object.class, Object.class)); - mh.invokeWithArguments((Object)(new String[] {"str1", "str2"})); + MethodHandle mh = MethodHandles.publicLookup() + .findStatic(THIS_CLASS, "f", mt); + mh = MethodHandles.explicitCastArguments(mh, + MethodType.methodType(Object.class, Object.class)); + mh.invokeWithArguments((Object) (new String[]{"str1", "str2"})); + } + + /** + * Tests that null wrapper reference is successfully converted to primitive + * types. Converted result should be zero for a primitive. Bug 8060483. + */ + public static void testNullRef2Prim() { + for (Wrapper from : Wrapper.values()) { + for (Wrapper to : Wrapper.values()) { + if (from == Wrapper.VOID || to == Wrapper.VOID) { + continue; + } + // MHs.eCA javadoc: + // If T0 is a reference and T1 a primitive, and if the reference + // is null at runtime, a zero value is introduced. + for (TestConversionMode mode : TestConversionMode.values()) { + testConversion(mode, from.wrapperType(), + to.primitiveType(), null, to.zero(), false, null); + } + } + } } - public static void testRef2Prim() throws Throwable { + /** + * Tests that non-null wrapper reference is successfully converted to + * primitive types. + */ + public static void testRef2Prim() { + for (Wrapper from : Wrapper.values()) { + for (Wrapper to : Wrapper.values()) { + if (from == Wrapper.VOID || to == Wrapper.VOID + || to == Wrapper.OBJECT) { + continue; + } + Object value = RANDOM_VALUES.get(from); + for (TestConversionMode mode : TestConversionMode.values()) { + if (from != Wrapper.OBJECT) { + Object convValue = to.wrap(value); + testConversion(mode, from.wrapperType(), + to.primitiveType(), value, convValue, false, null); + } else { + testConversion(mode, from.wrapperType(), + to.primitiveType(), value, null, + true, ClassCastException.class); + } + } + } + } + } + + /** + * Tests that primitive is successfully converted to wrapper reference + * types, to the Number type (if possible) and to the Object type. + */ + public static void testPrim2Ref() { for (Wrapper from : Wrapper.values()) { for (Wrapper to : Wrapper.values()) { - if (from == Wrapper.VOID || to == Wrapper.VOID) continue; - testRef2Prim(from, to); + if (from == Wrapper.VOID || from == Wrapper.OBJECT + || to == Wrapper.VOID || to == Wrapper.OBJECT) { + continue; + } + Object value = RANDOM_VALUES.get(from); + for (TestConversionMode mode : TestConversionMode.values()) { + if (from == to) { + testConversion(mode, from.primitiveType(), + to.wrapperType(), value, value, false, null); + } else { + testConversion(mode, from.primitiveType(), + to.wrapperType(), value, null, true, ClassCastException.class); + } + if (from != Wrapper.BOOLEAN && from != Wrapper.CHAR) { + testConversion(mode, from.primitiveType(), + Number.class, value, value, false, null); + } else { + testConversion(mode, from.primitiveType(), + Number.class, value, null, + true, ClassCastException.class); + } + testConversion(mode, from.primitiveType(), + Object.class, value, value, false, null); + } + } + } + } + + /** + * Tests that primitive is successfully converted to other primitive type. + */ + public static void testPrim2Prim() { + for (Wrapper from : Wrapper.values()) { + for (Wrapper to : Wrapper.values()) { + if (from == Wrapper.VOID || to == Wrapper.VOID + || from == Wrapper.OBJECT || to == Wrapper.OBJECT) { + continue; + } + Object value = RANDOM_VALUES.get(from); + Object convValue = to.wrap(value); + for (TestConversionMode mode : TestConversionMode.values()) { + testConversion(mode, from.primitiveType(), + to.primitiveType(), value, convValue, false, null); + } } } } - public static void testRef2Prim(Wrapper from, Wrapper to) throws Throwable { - // MHs.eCA javadoc: - // If T0 is a reference and T1 a primitive, and if the reference is null at runtime, a zero value is introduced. - test(from.wrapperType(), to.primitiveType(), null, false); + /** + * Dummy interface for {@link #testNonBCPRef2Ref} test. + */ + public static interface TestInterface {} + + /** + * Dummy class for {@link #testNonBCPRef2Ref} test. + */ + public static class TestSuperClass implements TestInterface {} + + /** + * Dummy class for {@link #testNonBCPRef2Ref} test. + */ + public static class TestSubClass1 extends TestSuperClass {} + + /** + * Dummy class for {@link #testNonBCPRef2Ref} test. + */ + public static class TestSubClass2 extends TestSuperClass {} + + /** + * Tests non-bootclasspath reference to reference conversions. + * + * @throws java.lang.Throwable + */ + public static void testNonBCPRef2NonBCPRef() throws Throwable { + Class testInterface = TestInterface.class; + Class testSuperClass = TestSuperClass.class; + Class testSubClass1 = TestSubClass1.class; + Class testSubClass2 = TestSubClass2.class; + Object testSuperObj = new TestSuperClass(); + Object testObj01 = new TestSubClass1(); + Object testObj02 = new TestSubClass2(); + Class[] parents = {testInterface, testSuperClass}; + Class[] children = {testSubClass1, testSubClass2}; + Object[] childInst = {testObj01, testObj02}; + for (TestConversionMode mode : TestConversionMode.values()) { + for (Class parent : parents) { + for (int j = 0; j < children.length; j++) { + // Child type to parent type non-null conversion, shoud succeed + testConversion(mode, children[j], parent, childInst[j], childInst[j], false, null); + // Child type to parent type null conversion, shoud succeed + testConversion(mode, children[j], parent, null, null, false, null); + // Parent type to child type non-null conversion with parent + // type instance, should fail + testConversion(mode, parent, children[j], testSuperObj, null, true, ClassCastException.class); + // Parent type to child type non-null conversion with child + // type instance, should succeed + testConversion(mode, parent, children[j], childInst[j], childInst[j], false, null); + // Parent type to child type null conversion, should succeed + testConversion(mode, parent, children[j], null, null, false, null); + } + // Parent type to child type non-null conversion with sibling + // type instance, should fail + testConversion(mode, parent, testSubClass1, testObj02, null, true, ClassCastException.class); + } + // Sibling type non-null conversion, should fail + testConversion(mode, testSubClass1, + testSubClass2, testObj01, null, true, + ClassCastException.class); + // Sibling type null conversion, should succeed + testConversion(mode, testSubClass1, + testSubClass2, null, null, false, null); + } + } + + /** + * Dummy interface for {@link #testNonBCPRef2BCPRef} test. + */ + public static interface TestSerializableInterface extends Serializable {} + + /** + * Dummy class for {@link #testNonBCPRef2BCPRef} test. + */ + public static class TestSerializableClass + implements TestSerializableInterface {} + + /** + * Dummy class for {@link #testNonBCPRef2BCPRef} test. + */ + public static class TestFileChildClass extends File + implements TestSerializableInterface { + public TestFileChildClass(String pathname) { + super(pathname); + } + } + + /** + * Tests non-bootclasspath reference to bootclasspath reference conversions + * and vice-versa. + * + * @throws java.lang.Throwable + */ + public static void testNonBCPRef2BCPRef() throws Throwable { + Class bcpInterface = Serializable.class; + Class bcpSuperClass = File.class; + Class nonBcpInterface = TestSerializableInterface.class; + Class nonBcpSuperSiblingClass = TestSerializableClass.class; + Class nonBcpSubClass = TestFileChildClass.class; + Object bcpSuperObj = new File("."); + Object testSuperSiblingObj = new TestSerializableClass(); + Object testSubObj = new TestFileChildClass("."); + Class[] parents = {bcpInterface, bcpSuperClass}; + for (TestConversionMode mode : TestConversionMode.values()) { + for (Class parent : parents) { + // Child type to parent type non-null conversion, shoud succeed + testConversion(mode, nonBcpSubClass, parent, testSubObj, + testSubObj, false, null); + // Child type to parent type null conversion, shoud succeed + testConversion(mode, nonBcpSubClass, parent, null, null, + false, null); + // Parent type to child type non-null conversion with parent + // type instance, should fail + testConversion(mode, parent, nonBcpSubClass, bcpSuperObj, null, + true, ClassCastException.class); + // Parent type to child type non-null conversion with child + // type instance, should succeed + testConversion(mode, parent, nonBcpSubClass, testSubObj, + testSubObj, false, null); + // Parent type to child type null conversion, should succeed + testConversion(mode, parent, nonBcpSubClass, null, null, + false, null); + } + // Parent type to child type non-null conversion with + // super sibling type instance, should fail + testConversion(mode, bcpInterface, nonBcpSubClass, + testSuperSiblingObj, null, true, ClassCastException.class); + Class[] siblings = {nonBcpSubClass, bcpSuperClass}; + for (Class sibling : siblings) { + // Non-bcp class to bcp/non-bcp sibling class non-null + // conversion with nonBcpSuperSiblingClass instance, should fail + testConversion(mode, nonBcpSuperSiblingClass, sibling, + testSuperSiblingObj, null, true, ClassCastException.class); + // Non-bcp class to bcp/non-bcp sibling class null conversion, + // should succeed + testConversion(mode, nonBcpSuperSiblingClass, sibling, + null, null, false, null); + // Non-bcp interface to bcp/non-bcp sibling class non-null + // conversion with nonBcpSubClass instance, should succeed + testConversion(mode, nonBcpInterface, sibling, testSubObj, + testSubObj, false, null); + // Non-bcp interface to bcp/non-bcp sibling class + // null conversion, should succeed + testConversion(mode, nonBcpInterface, sibling, null, null, + false, null); + // Non-bcp interface to bcp/non-bcp sibling class non-null + // conversion with nonBcpSuperSiblingClass instance, should fail + testConversion(mode, nonBcpInterface, sibling, + testSuperSiblingObj, testSubObj, + true, ClassCastException.class); + } + } } - public static void test(Class<?> from, Class<?> to, Object param, boolean failureExpected) throws Throwable { - if (VERBOSE) System.out.printf("%-10s => %-10s: %5s: ", from.getSimpleName(), to.getSimpleName(), param); + /** + * Tests bootclasspath reference to reference conversions. + */ + public static void testBCPRef2BCPRef() { + Class bcpInterface = CharSequence.class; + Class bcpSubClass1 = String.class; + Class bcpSubClass2 = StringBuffer.class; + Object testObj01 = new String("test"); + Object testObj02 = new StringBuffer("test"); + Class[] children = {bcpSubClass1, bcpSubClass2}; + Object[] childInst = {testObj01, testObj02}; + for (TestConversionMode mode : TestConversionMode.values()) { + for (int i = 0; i < children.length; i++) { + // Child type to parent type non-null conversion, shoud succeed + testConversion(mode, children[i], bcpInterface, childInst[i], + childInst[i], false, null); + // Child type to parent type null conversion, shoud succeed + testConversion(mode, children[i], bcpInterface, null, + null, false, null); + // Parent type to child type non-null conversion with child + // type instance, should succeed + testConversion(mode, bcpInterface, + children[i], childInst[i], childInst[i], false, null); + // Parent type to child type null conversion, should succeed + testConversion(mode, bcpInterface, + children[i], null, null, false, null); + } + // Sibling type non-null conversion, should fail + testConversion(mode, bcpSubClass1, + bcpSubClass2, testObj01, null, true, + ClassCastException.class); + // Sibling type null conversion, should succeed + testConversion(mode, bcpSubClass1, + bcpSubClass2, null, null, false, null); + // Parent type to child type non-null conversion with sibling + // type instance, should fail + testConversion(mode, bcpInterface, bcpSubClass1, testObj02, + null, true, ClassCastException.class); + } + } + + /** + * Dummy method used in {@link #testReturnAny2Void} and + * {@link #testReturnVoid2Any} tests to form a method handle. + */ + public static void retVoid() {} + + /** + * Tests that non-null any return is successfully converted to non-type + * void. + */ + public static void testReturnAny2Void() { + for (Wrapper from : Wrapper.values()) { + testConversion(TestConversionMode.RETURN_VALUE, from.wrapperType(), + void.class, RANDOM_VALUES.get(from), + null, false, null); + testConversion(TestConversionMode.RETURN_VALUE, from.primitiveType(), + void.class, RANDOM_VALUES.get(from), + null, false, null); + } + } + + /** + * Tests that void return is successfully converted to primitive and + * reference. Result should be zero for primitives and null for references. + */ + public static void testReturnVoid2Any() { + for (Wrapper to : Wrapper.values()) { + testConversion(TestConversionMode.RETURN_VALUE, void.class, + to.primitiveType(), null, + to.zero(), false, null); + testConversion(TestConversionMode.RETURN_VALUE, void.class, + to.wrapperType(), null, + null, false, null); + } + } + + private static void checkForWrongMethodTypeException(MethodHandle mh, MethodType mt) { + try { + MethodHandles.explicitCastArguments(mh, mt); + throw new AssertionError("Expected WrongMethodTypeException is not thrown"); + } catch (WrongMethodTypeException wmte) { + if (VERBOSE) { + System.out.printf("Expected exception %s: %s\n", + wmte.getClass(), wmte.getMessage()); + } + } + } - MethodHandle original = MethodHandles.identity(from); - MethodType newType = original.type().changeReturnType(to); + /** + * Tests that MHs.eCA method works correctly with MHs with multiple arguments. + * @throws Throwable + */ + public static void testMultipleArgs() throws Throwable { + int arity = 1 + RNG.nextInt(Helper.MAX_ARITY / 2 - 2); + int arityMinus = RNG.nextInt(arity); + int arityPlus = arity + RNG.nextInt(Helper.MAX_ARITY / 2 - arity) + 1; + MethodType mType = Helper.randomMethodTypeGenerator(arity); + MethodType mTypeNew = Helper.randomMethodTypeGenerator(arity); + MethodType mTypeNewMinus = Helper.randomMethodTypeGenerator(arityMinus); + MethodType mTypeNewPlus = Helper.randomMethodTypeGenerator(arityPlus); + Class<?> rType = mType.returnType(); + MethodHandle original; + if (rType.equals(void.class)) { + MethodType mt = MethodType.methodType(void.class); + original = MethodHandles.publicLookup() + .findStatic(THIS_CLASS, "retVoid", mt); + } else { + Object rValue = Helper.castToWrapper(1, rType); + original = MethodHandles.constant(rType, rValue); + } + original = Helper.addTrailingArgs(original, arity, mType.parameterList()); + MethodHandle target = MethodHandles + .explicitCastArguments(original, mTypeNew); + Object[] parList = Helper.randomArgs(mTypeNew.parameterList()); + for (int i = 0; i < parList.length; i++) { + if (parList[i] instanceof String) { + parList[i] = null; //getting rid of Stings produced by randomArgs + } + } + target.invokeWithArguments(parList); + checkForWrongMethodTypeException(original, mTypeNewMinus); + checkForWrongMethodTypeException(original, mTypeNewPlus); + } + + /** + * Enumeration of test conversion modes. + */ + public enum TestConversionMode { + RETURN_VALUE, + ARGUMENT; + } + /** + * Tests type and value conversion. Comparing with the given expected result. + * + * @param mode - test conversion mode. See {@link #TestConversionMode}. + * @param from - source type. + * @param to - destination type. + * @param param - value to be converted. + * @param expectedResult - expected value after conversion. + * @param failureExpected - true if conversion failure expected. + * @param expectedException - expected exception class if + * {@code failureExpected} is true. + */ + public static void testConversion(TestConversionMode mode, + Class<?> from, Class<?> to, Object param, + Object expectedResult, boolean failureExpected, + Class<? extends Throwable> expectedException) { + if (VERBOSE) { + System.out.printf("Testing return value conversion: " + + "%-10s => %-10s: %5s: ", from.getSimpleName(), + to.getSimpleName(), param); + } + MethodHandle original = null; + MethodType newType = null; + switch (mode) { + case RETURN_VALUE: + if (from.equals(void.class)) { + MethodType mt = MethodType.methodType(void.class); + try { + original = MethodHandles.publicLookup() + .findStatic(THIS_CLASS, "retVoid", mt); + } catch (NoSuchMethodException | IllegalAccessException ex) { + throw new Error("Unexpected issue", ex); + } + } else { + original = MethodHandles.constant(from, param); + } + newType = original.type().changeReturnType(to); + break; + case ARGUMENT: + if (from.equals(void.class) || to.equals(void.class)) { + throw new Error("Test issue: argument conversion does not" + + " work with non-type void"); + } + original = MethodHandles.identity(to); + newType = original.type().changeParameterType(0, from); + break; + default: + String msg = String.format("Test issue: unknown test" + + " convertion mode %s.", mode.name()); + throw new Error(msg); + } try { - MethodHandle target = MethodHandles.explicitCastArguments(original, newType); - Object result = target.invokeWithArguments(param); - + MethodHandle target = MethodHandles + .explicitCastArguments(original, newType); + Object result; + switch (mode) { + case RETURN_VALUE: + result = target.invokeWithArguments(); + break; + case ARGUMENT: + result = target.invokeWithArguments(param); + break; + default: + String msg = String.format("Test issue: unknown test" + + " convertion mode %s.", mode.name()); + throw new Error(msg); + } + if (!failureExpected + && (expectedResult != null && !expectedResult.equals(result) + || expectedResult == null && result != null)) { + String msg = String.format("Conversion result %s is not equal" + + " to the expected result %10s", + result, expectedResult); + throw new AssertionError(msg); + } if (VERBOSE) { String resultStr; if (result != null) { - resultStr = String.format("%10s (%10s)", "'"+result+"'", result.getClass().getSimpleName()); + resultStr = String.format("Converted value and type are" + + " %10s (%10s)", "'" + result + "'", + result.getClass().getSimpleName()); } else { - resultStr = String.format("%10s", result); + resultStr = String.format("Converted value is %10s", result); } System.out.println(resultStr); } - if (failureExpected) { - String msg = String.format("No exception thrown: %s => %s; parameter: %s", from, to, param); + String msg = String.format("No exception thrown while testing" + + " return value conversion: %10s => %10s;" + + " parameter: %10s", + from, to, param); throw new AssertionError(msg); } } catch (AssertionError e) { throw e; // report test failure } catch (Throwable e) { - if (VERBOSE) System.out.printf("%s: %s\n", e.getClass(), e.getMessage()); - if (!failureExpected) { - String msg = String.format("Unexpected exception was thrown: %s => %s; parameter: %s", from, to, param); + if (VERBOSE) { + System.out.printf("%s: %s\n", e.getClass(), e.getMessage()); + } + if (!failureExpected || !e.getClass().equals(expectedException)) { + String msg = String.format("Unexpected exception was thrown" + + " while testing return value conversion:" + + " %s => %s; parameter: %s", from, to, param); throw new AssertionError(msg, e); } }
--- a/test/java/lang/invoke/LFCaching/TestMethods.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/lang/invoke/LFCaching/TestMethods.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -207,7 +207,7 @@ return MethodHandles.filterReturnValue(target, filter); } }, - INSERT_ARGUMENTS("insertArguments") { + INSERT_ARGUMENTS("insertArguments", Helper.MAX_ARITY - 3) { @Override public Map<String, Object> getTestCaseData() { Map<String, Object> data = new HashMap<>(); @@ -610,26 +610,7 @@ * @return MethodType generated randomly. */ private static MethodType randomMethodTypeGenerator(int arity) { - final Class<?>[] CLASSES = { - Object.class, - int.class, - boolean.class, - byte.class, - short.class, - char.class, - long.class, - float.class, - double.class - }; - if (arity > Helper.MAX_ARITY) { - throw new IllegalArgumentException( - String.format("Arity should not exceed %d!", Helper.MAX_ARITY)); - } - List<Class<?>> list = Helper.randomClasses(CLASSES, arity); - list = Helper.getParams(list, false, arity); - int i = Helper.RNG.nextInt(CLASSES.length + 1); - Class<?> rtype = i == CLASSES.length ? void.class : CLASSES[i]; - return MethodType.methodType(rtype, list); + return Helper.randomMethodTypeGenerator(arity); } /**
--- a/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -168,6 +168,11 @@ try { returned = target.invokeWithArguments(args); } catch (Throwable ex) { + if (CodeCacheOverflowProcessor.isThrowableCausedByVME(ex)) { + // This error will be treated by CodeCacheOverflowProcessor + // to prevent the test from failing because of code cache overflow. + throw new Error(ex); + } testCase.assertCatch(ex); returned = ex; }
--- a/test/java/lang/management/ThreadMXBean/ThreadInfoArray.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/lang/management/ThreadMXBean/ThreadInfoArray.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -23,11 +23,12 @@ /* * @test - * @bug 5058327 - * @summary Test if getThreadInfo(long[]) returns a ThreadInfo[] - * with null elements with no exception. + * @bug 5058327 8074368 + * @summary Tests the correct behaviour of getThreadInfo(long[]) for non-existent + * thread IDs and the empty thread id array. * * @author Mandy Chung + * @author Jaroslav Bachorik * * @build ThreadInfoArray * @run main ThreadInfoArray @@ -35,15 +36,30 @@ import java.lang.management.*; import javax.management.*; -import java.util.*; import static java.lang.management.ManagementFactory.*; public class ThreadInfoArray { public static void main(String[] argv) throws Exception { + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + ObjectName on = new ObjectName(THREAD_MXBEAN_NAME); + ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); + ThreadMXBean proxy = newPlatformMXBeanProxy(mbs, + on.toString(), + ThreadMXBean.class); + checkNullElement(mbean, proxy, mbs, on); + checkEmptyArray(mbean, proxy, mbs, on); + System.out.println("Test passed"); + } + + private static void checkNullElement(ThreadMXBean mbean, ThreadMXBean proxy, + MBeanServer mbs, ObjectName on) + throws Exception { + System.out.println("--- Check null element"); // ID for a new thread long [] ids = {new Thread().getId()}; + // direct call ThreadInfo[] tinfos = mbean.getThreadInfo(ids); if (tinfos[0] != null) { @@ -52,8 +68,6 @@ } // call getThreadInfo through MBeanServer - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName on = new ObjectName(THREAD_MXBEAN_NAME); Object[] params = {ids}; String[] sigs = {"[J"}; Object[] result = (Object[]) mbs.invoke(on, "getThreadInfo", params, sigs); @@ -64,14 +78,57 @@ } // call getThreadInfo through proxy - ThreadMXBean proxy = newPlatformMXBeanProxy(mbs, - on.toString(), - ThreadMXBean.class); tinfos = proxy.getThreadInfo(ids); if (tinfos[0] != null) { throw new RuntimeException("TEST FAILED: " + "Expected to have a null element"); } - System.out.println("Test passed"); + System.out.println("--- PASSED"); + } + + private static void checkEmptyArray(ThreadMXBean mbean, ThreadMXBean proxy, + MBeanServer mbs, ObjectName on) + throws Exception { + System.out.println("--- Check empty TID array"); + + long[] ids = new long[0]; + // direct call + assertEmptyArray(mbean.getThreadInfo(ids), "Expected empty ThreadInfo array"); + assertEmptyArray(mbean.getThreadInfo(ids, 1), "Expected empty ThreadInfo array"); + assertEmptyArray(mbean.getThreadInfo(ids, true, true), "Expected empty ThreadInfo array"); + + // call getThreadInfo through MBeanServer + assertEmptyArray( + (Object[]) mbs.invoke( + on, "getThreadInfo", new Object[]{ids}, new String[]{"[J"} + ), + "Expected empty ThreadInfo array via MBeanServer" + ); + assertEmptyArray( + (Object[]) mbs.invoke( + on, "getThreadInfo", new Object[]{ids, 1}, + new String[]{"[J", "int"} + ), + "Expected empty ThreadInfo array via MBeanServer" + ); + assertEmptyArray( + (Object[]) mbs.invoke( + on, "getThreadInfo", new Object[]{ids, true, true}, + new String[]{"[J", "boolean", "boolean"} + ), + "Expected empty ThreadInfo array via MBeanServer" + ); + + // call getThreadInfo through proxy + assertEmptyArray(proxy.getThreadInfo(ids), "Expected empty ThreadInfo array"); + assertEmptyArray(proxy.getThreadInfo(ids, 1), "Expected empty ThreadInfo array"); + assertEmptyArray(proxy.getThreadInfo(ids, true, true), "Expected empty ThreadInfo array"); + System.out.println("--- PASSED"); + } + + private static void assertEmptyArray(Object[] arr, String message) throws Exception { + if (arr.length > 0) { + throw new RuntimeException("TEST FAILED: " + message); + } } }
--- a/test/java/net/Inet4Address/PingThis.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/net/Inet4Address/PingThis.java Thu Oct 29 17:12:06 2015 -0700 @@ -26,7 +26,7 @@ */ /* @test - * @bug 7163874 + * @bug 7163874 8133015 * @summary InetAddress.isReachable is returning false * for InetAdress 0.0.0.0 and ::0 * @run main PingThis
--- a/test/java/net/Inet4Address/textToNumericFormat.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/net/Inet4Address/textToNumericFormat.java Thu Oct 29 17:12:06 2015 -0700 @@ -23,7 +23,7 @@ /* * @test - * @bug 4749938 + * @bug 4749938 8087190 * @summary Bug in the parsing IPv4 literal addresses * @compile -XDignore.symbol.file=true DummyNameService.java DummyNameServiceDescriptor.java * @run main/othervm -Dsun.net.spi.nameservice.provider.1=dummy,oracle textToNumericFormat @@ -62,7 +62,11 @@ "2380.255.255.255", "239.255.65536", "239.16777216", - "4294967296" }; + "4294967296", + ".1.1.1", + "1..1.1", + "1.1.1.", + "..." }; for (int i=0; i<goodAddrs.length; i++) { try {
--- a/test/java/net/InetAddress/IsHostReachableBug.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/net/InetAddress/IsHostReachableBug.java Thu Oct 29 17:12:06 2015 -0700 @@ -23,7 +23,7 @@ /** * @test - * @bug 4922568 + * @bug 4922568 8133015 * @run main/othervm -Djava.net.preferIPv4Stack=true IsHostReachableBug * @summary isReachable returns true for IPv6 */
--- a/test/java/net/InetAddress/IsReachable.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/net/InetAddress/IsReachable.java Thu Oct 29 17:12:06 2015 -0700 @@ -23,7 +23,7 @@ /** * @test - * @bug 4639861 + * @bug 4639861 8133015 * @summary API to test reachability of a host */ import java.net.InetAddress;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/net/InetAddress/IsReachableViaLoopbackTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,40 @@ +import java.io.*; +import java.net.*; +import java.util.*; + +/** + * @test + * @bug 8135305 + * @summary ensure we can't ping external hosts via loopback if + */ + +public class IsReachableViaLoopbackTest { + public static void main(String[] args) { + try { + InetAddress addr = InetAddress.getByName("localhost"); + InetAddress remoteAddr = InetAddress.getByName("bugs.openjdk.java.net"); + if (!addr.isReachable(10000)) + throw new RuntimeException("Localhost should always be reachable"); + NetworkInterface inf = NetworkInterface.getByInetAddress(addr); + if (inf != null) { + if (!addr.isReachable(inf, 20, 10000)) { + throw new RuntimeException("Localhost should always be reachable"); + } else { + System.out.println(addr + " is reachable"); + } + if (remoteAddr.isReachable(inf, 20, 10000)) { + throw new RuntimeException(remoteAddr + " is reachable"); + } else { + System.out.println(remoteAddr + " is NOT reachable"); + } + } else { + System.out.println("inf == null"); + } + + } catch (IOException e) { + throw new RuntimeException("Unexpected exception:" + e); + } + System.out.println("IsReachableViaLoopbackTest EXIT"); + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/net/MulticastSocket/MultiDead.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,114 @@ +/* + * 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 8072466 + * @summary Deadlock when initializing MulticastSocket and DatagramSocket + * @library /lib/testlibrary + * @build jdk.testlibrary.* + * @run main/othervm MultiDead + */ + +import java.net.DatagramSocket; +import java.net.MulticastSocket; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.CountDownLatch; +import jdk.testlibrary.JDKToolLauncher; + +public class MultiDead { + private static final int THREAD_PAIR_COUNT = 4; + private static final int CHILDREN_COUNT = 20; + + public static void main(String[] args) throws Throwable { + if (args.length == 0 || args[0].equals("parent")) { + parentProcess(); + } + + if (args.length > 0 && args[0].equals("child")) { + childProcess(); + } + } + + private static void parentProcess() throws Throwable { + JDKToolLauncher launcher = JDKToolLauncher + .createUsingTestJDK("java") + .addToolArg("MultiDead") + .addToolArg("child"); + ProcessBuilder pb = new ProcessBuilder(launcher.getCommand()); + + AtomicReference<Process> child = new AtomicReference<>(); + AtomicBoolean stopFlag = new AtomicBoolean(false); + + Thread th = new Thread(() -> { + for (int i = 0; i < CHILDREN_COUNT; ++i) { + System.out.println("child #" + (i + 1) + " of " + + CHILDREN_COUNT); + try { + child.set(pb.start()); + child.get().waitFor(); + if (stopFlag.get()) { + break; + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + + th.start(); + th.join(CHILDREN_COUNT * 1000); // 1 sec for a child to complete + stopFlag.set(true); + if (th.isAlive()) { + if (child.get() != null) { + child.get().destroyForcibly(); + } + throw new RuntimeException("Failed to complete on time."); + } + } + + private static void childProcess() { + CountDownLatch latch = new CountDownLatch(1); + for (int i = 0; i < THREAD_PAIR_COUNT; ++i) { + new Thread(() -> { + try { + latch.await(); + try (MulticastSocket a = new MulticastSocket(6000)) { + } + } catch (Exception ignore) { + } + }).start(); + + new Thread(() -> { + try { + latch.await(); + try (DatagramSocket b = new DatagramSocket(6000)) { + } + } catch (Exception ignore) { + } + }).start(); + } + latch.countDown(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/nio/Buffer/DirectBufferAllocTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * 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 6857566 + * @summary DirectByteBuffer garbage creation can outpace reclamation + * + * @run main/othervm -XX:MaxDirectMemorySize=128m DirectBufferAllocTest + */ + +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class DirectBufferAllocTest { + // defaults + static final int RUN_TIME_SECONDS = 5; + static final int MIN_THREADS = 4; + static final int MAX_THREADS = 64; + static final int CAPACITY = 1024 * 1024; // bytes + + /** + * This test spawns multiple threads that constantly allocate direct + * {@link ByteBuffer}s in a loop, trying to provoke {@link OutOfMemoryError}.<p> + * When run without command-line arguments, it runs as a regression test + * for at most 5 seconds.<p> + * Command line arguments: + * <pre> + * -r run-time-seconds <i>(duration of successful test - default 5 s)</i> + * -t threads <i>(default is 2 * # of CPUs, at least 4 but no more than 64)</i> + * -c capacity <i>(of direct buffers in bytes - default is 1MB)</i> + * -p print-alloc-time-batch-size <i>(every "batch size" iterations, + * average time per allocation is printed)</i> + * </pre> + * Use something like the following to run a 10 minute stress test and + * print allocation times as it goes: + * <pre> + * java -XX:MaxDirectMemorySize=128m DirectBufferAllocTest -r 600 -t 32 -p 5000 + * </pre> + */ + public static void main(String[] args) throws Exception { + int runTimeSeconds = RUN_TIME_SECONDS; + int threads = Math.max( + Math.min( + Runtime.getRuntime().availableProcessors() * 2, + MAX_THREADS + ), + MIN_THREADS + ); + int capacity = CAPACITY; + int printBatchSize = 0; + + // override with command line arguments + for (int i = 0; i < args.length; i++) { + switch (args[i]) { + case "-r": + runTimeSeconds = Integer.parseInt(args[++i]); + break; + case "-t": + threads = Integer.parseInt(args[++i]); + break; + case "-c": + capacity = Integer.parseInt(args[++i]); + break; + case "-p": + printBatchSize = Integer.parseInt(args[++i]); + break; + default: + System.err.println( + "Usage: java" + + " [-XX:MaxDirectMemorySize=XXXm]" + + " DirectBufferAllocTest" + + " [-r run-time-seconds]" + + " [-t threads]" + + " [-c capacity-of-direct-buffers]" + + " [-p print-alloc-time-batch-size]" + ); + System.exit(-1); + } + } + + System.out.printf( + "Allocating direct ByteBuffers with capacity %d bytes, using %d threads for %d seconds...\n", + capacity, threads, runTimeSeconds + ); + + ExecutorService executor = Executors.newFixedThreadPool(threads); + + int pbs = printBatchSize; + int cap = capacity; + + List<Future<Void>> futures = + IntStream.range(0, threads) + .mapToObj( + i -> (Callable<Void>) () -> { + long t0 = System.nanoTime(); + loop: + while (true) { + for (int n = 0; pbs == 0 || n < pbs; n++) { + if (Thread.interrupted()) { + break loop; + } + ByteBuffer.allocateDirect(cap); + } + long t1 = System.nanoTime(); + if (pbs > 0) { + System.out.printf( + "Thread %2d: %5.2f ms/allocation\n", + i, ((double) (t1 - t0) / (1_000_000d * pbs)) + ); + } + t0 = t1; + } + return null; + } + ) + .map(executor::submit) + .collect(Collectors.toList()); + + for (int i = 0; i < runTimeSeconds; i++) { + if (futures.stream().anyMatch(Future::isDone)) { + break; + } + Thread.sleep(1000L); + } + + Exception exception = null; + for (Future<Void> future : futures) { + if (future.isDone()) { + try { + future.get(); + } catch (ExecutionException e) { + if (exception == null) { + exception = new RuntimeException("Errors encountered!"); + } + exception.addSuppressed(e.getCause()); + } + } else { + future.cancel(true); + } + } + + executor.shutdown(); + + if (exception != null) { + throw exception; + } else { + System.out.printf("No errors after %d seconds.\n", runTimeSeconds); + } + } +}
--- a/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/nio/channels/AsynchronousSocketChannel/StressLoopback.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -22,7 +22,7 @@ */ /* @test - * @bug 6834246 6842687 + * @bug 6834246 6842687 8133647 * @summary Stress test connections through the loopback interface * @run main StressLoopback * @run main/othervm -Djdk.net.useFastTcpLoopback StressLoopback
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/nio/channels/FileChannel/LoopingTruncate.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,80 @@ +/* + * 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 8137121 8137230 + * @summary (fc) Infinite loop FileChannel.truncate + * @library /lib/testlibrary + * @build jdk.testlibrary.Utils + * @run main/othervm LoopingTruncate + */ + +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.ClosedByInterruptException; +import java.nio.file.Files; +import java.nio.file.Path; +import static java.nio.file.StandardOpenOption.*; +import static jdk.testlibrary.Utils.adjustTimeout; + +public class LoopingTruncate { + + // (int)FATEFUL_SIZE == -3 == IOStatus.INTERRUPTED + static long FATEFUL_SIZE = 0x1FFFFFFFDL; + + // At least 20 seconds + static long TIMEOUT = adjustTimeout(20_000); + + public static void main(String[] args) throws Throwable { + Path path = Files.createTempFile("LoopingTruncate.tmp", null); + try (FileChannel fc = FileChannel.open(path, CREATE, WRITE)) { + fc.position(FATEFUL_SIZE + 1L); + fc.write(ByteBuffer.wrap(new byte[] {0})); + + Thread th = new Thread(() -> { + try { + fc.truncate(FATEFUL_SIZE); + } catch (ClosedByInterruptException ignore) { + } catch (Exception e) { + throw new RuntimeException(e); + }}); + th.start(); + th.join(TIMEOUT); + + if (th.isAlive()) { + System.err.println("=== Stack trace of the guilty thread:"); + for (StackTraceElement el : th.getStackTrace()) { + System.err.println("\t" + el); + } + System.err.println("==="); + + th.interrupt(); + th.join(); + throw new RuntimeException("Failed to complete on time"); + } + } finally { + Files.deleteIfExists(path); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/nio/file/Files/probeContentType/ParallelProbes.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,96 @@ +/* + * 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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; + +/* @test + * @summary Test probing content type simultaneously from multiple threads. + * @requires (os.family == "linux") | (os.family == "solaris") + * @run main/othervm ParallelProbes 10 + */ +public class ParallelProbes { + + private static final int REPEATS = 1000; + + private int numThreads = 0; + private ArrayList<Thread> threads; + + public ParallelProbes(int numThreads) { + System.out.println("Using <" + numThreads + "> threads."); + this.numThreads = numThreads; + this.threads = new ArrayList<Thread>(numThreads); + } + + private Path createTmpFile() throws IOException { + final Path p = Files.createTempFile("prefix", ".json"); + Files.write(p, "{\"test\"}".getBytes()); + System.out.println("Write test file <" + p + ">"); + return p; + } + + private Runnable createRunnable(final Path p) { + Runnable r = new Runnable() { + public void run() { + for (int i = 0; i < REPEATS; i++) { + try { + System.out.println(Thread.currentThread().getName() + + " -> " + Files.probeContentType(p)); + } catch (IOException ioException) { + ioException.printStackTrace(); + } + } + } + }; + return r; + } + + public void start() throws IOException { + for (int i = 0; i < numThreads; i++) { + final Path p = createTmpFile(); + Runnable r = createRunnable(p); + Thread thread = new Thread(r, "thread-" + i); + thread.start(); + threads.add(thread); + } + } + + public void join() { + for (Thread thread : threads) { + try { + thread.join(); + } catch (InterruptedException e) { + // ignore it and proceed to the next one + } + } + } + + public static void main(String[] args) throws Exception { + ParallelProbes probes = + new ParallelProbes(args.length < 1 ? 1 : Integer.parseInt(args[0])); + probes.start(); + probes.join(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/nio/file/WatchService/LotsOfCancels.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * 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 8029516 + * @summary Bash on WatchKey.cancel with a view to causing a crash when + * an outstanding I/O operation on directory completes after the + * directory has been closed + */ + +import java.nio.file.ClosedWatchServiceException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import static java.nio.file.StandardWatchEventKinds.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class LotsOfCancels { + + // set to true for any exceptions + static volatile boolean failed; + + public static void main(String[] args) throws Exception { + + // create a bunch of directories. Create two tasks for each directory, + // one to bash on cancel, the other to poll the events + ExecutorService pool = Executors.newCachedThreadPool(); + try { + Path top = Files.createTempDirectory("work"); + top.toFile().deleteOnExit(); + for (int i=1; i<=16; i++) { + Path dir = Files.createDirectory(top.resolve("dir-" + i)); + WatchService watcher = FileSystems.getDefault().newWatchService(); + pool.submit(() -> handle(dir, watcher)); + pool.submit(() -> poll(watcher)); + } + } finally { + pool.shutdown(); + } + + // give thread pool lots of time to terminate + if (!pool.awaitTermination(5L, TimeUnit.MINUTES)) + throw new RuntimeException("Thread pool did not terminate"); + + if (failed) + throw new RuntimeException("Test failed, see log for details"); + } + + /** + * Stress the given WatchService, specifically the cancel method, in + * the given directory. Closes the WatchService when done. + */ + static void handle(Path dir, WatchService watcher) { + try { + try { + Path file = dir.resolve("anyfile"); + for (int i=0; i<2000; i++) { + WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE); + Files.createFile(file); + Files.delete(file); + key.cancel(); + } + } finally { + watcher.close(); + } + } catch (Exception e) { + e.printStackTrace(); + failed = true; + } + } + + /** + * Polls the given WatchService in a tight loop. This keeps the event + * queue drained, it also hogs a CPU core which seems necessary to + * tickle the original bug. + */ + static void poll(WatchService watcher) { + try { + for (;;) { + WatchKey key = watcher.take(); + if (key != null) { + key.pollEvents(); + key.reset(); + } + } + } catch (ClosedWatchServiceException expected) { + // nothing to do + } catch (Exception e) { + e.printStackTrace(); + failed = true; + } + } + +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/security/KeyStore/CheckInputStream.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,49 @@ +/* + * 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 8136534 + * @summary The input stream supplied to KeyStore.load should remain open. + */ + +import java.io.*; +import java.security.*; + +public class CheckInputStream { + private final static String DIR = System.getProperty("test.src", "."); + private static final char[] PASSWORD = "passphrase".toCharArray(); + private static final String KEYSTORE = DIR + "/keystore.jks"; + + public static final void main(String[] args) throws Exception { + + KeyStore keystore = KeyStore.getInstance("JKS"); + try (FileInputStream inStream = new FileInputStream(KEYSTORE)) { + System.out.println("Loading JKS keystore: " + KEYSTORE); + keystore.load(inStream, PASSWORD); + // check that the stream is still open + inStream.available(); + System.out.println("OK"); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/text/Format/DateFormat/Bug8081794.java Thu Oct 29 17:12:06 2015 -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. + */ + +/* + * @test + * @bug 8081794 + * @summary ParsePosition getErrorIndex should return correct index + */ +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +public class Bug8081794 { + + public static void main(String[] args) { + String date = "13 Jan 2005 21:45:34 ABC"; + String format = "dd MMM yyyy HH:mm:ss z"; + ParsePosition pp = new ParsePosition(0); + pp.setIndex(0); + SimpleDateFormat sd = new SimpleDateFormat(format, Locale.ENGLISH); + Date d = sd.parse(date, pp); + int errorIndex = pp.getErrorIndex(); + if (errorIndex == 21) { + System.out.println(": passed"); + } else { + System.out.println(": failed"); + throw new RuntimeException("Failed with wrong index: " + errorIndex); + } + } +}
--- a/test/java/time/tck/java/time/TCKInstant.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/time/tck/java/time/TCKInstant.java Thu Oct 29 17:12:06 2015 -0700 @@ -112,6 +112,8 @@ /** * Test Instant. + * + * @bug 8133022 */ @Test public class TCKInstant extends AbstractDateTimeTest { @@ -1928,6 +1930,16 @@ Instant.ofEpochSecond(Long.MIN_VALUE / 1000 - 1).toEpochMilli(); } + @Test(expectedExceptions=ArithmeticException.class) + public void test_toEpochMillis_overflow() { + Instant.ofEpochSecond(Long.MAX_VALUE / 1000, 809_000_000).toEpochMilli(); + } + + @Test(expectedExceptions=ArithmeticException.class) + public void test_toEpochMillis_overflow2() { + Instant.ofEpochSecond(-9223372036854776L, 1).toEpochMilli(); + } + //----------------------------------------------------------------------- // compareTo() //-----------------------------------------------------------------------
--- a/test/java/time/test/java/time/TestInstant.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/java/time/test/java/time/TestInstant.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -62,6 +62,8 @@ import java.time.Instant; import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; +import static org.testng.Assert.assertEquals; /** * Test Instant. @@ -74,4 +76,24 @@ assertImmutable(Instant.class); } + @DataProvider(name="sampleEpochMillis") + private Object[][] provider_sampleEpochMillis() { + return new Object[][] { + {"Long.MAX_VALUE", Long.MAX_VALUE}, + {"Long.MAX_VALUE-1", Long.MAX_VALUE - 1}, + {"1", 1L}, + {"0", 0L}, + {"-1", -1L}, + {"Long.MIN_VALUE+1", Long.MIN_VALUE + 1}, + {"Long.MIN_VALUE", Long.MIN_VALUE} + }; + } + + @Test(dataProvider="sampleEpochMillis") + public void test_epochMillis(String name, long millis) { + Instant t1 = Instant.ofEpochMilli(millis); + long m = t1.toEpochMilli(); + assertEquals(millis, m, name); + } + }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/java/util/zip/ZipFile/ZipEntryFreeTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,130 @@ +/* + * 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 6907252 + * @summary ZipFileInputStream Not Thread-Safe + * @library /lib/testlibrary + * @build jdk.testlibrary.* + * @run main ZipEntryFreeTest + */ + +import java.io.*; +import java.nio.file.Paths; +import java.util.Random; +import java.util.Timer; +import java.util.TimerTask; +import java.util.zip.*; +import jdk.testlibrary.FileUtils; + +public class ZipEntryFreeTest extends Thread { + + private static final int NUM_THREADS = 5; + private static final int TEST_ITERATIONS = 5; + private static final String ZIPFILE_NAME = "large.zip"; + private static final String ZIPENTRY_NAME = "random.txt"; + private static InputStream is = null; + final Timer timer = new Timer(); + + public static void main(String args[]) throws Exception { + createZipFile(); + try { + for (int i = 0; i < TEST_ITERATIONS; i++) { + runTest(); + } + } finally { + FileUtils.deleteFileIfExistsWithRetry(Paths.get(ZIPFILE_NAME)); + } + } + + private static void runTest() throws Exception { + try (ZipFile zf = new ZipFile(new File(ZIPFILE_NAME))) { + is = zf.getInputStream(zf.getEntry(ZIPENTRY_NAME + "_0")); + Thread[] threadArray = new Thread[NUM_THREADS]; + for (int i = 0; i < threadArray.length; i++) { + threadArray[i] = new ZipEntryFreeTest(); + } + for (int i = 0; i < threadArray.length; i++) { + threadArray[i].start(); + } + for (int i = 0; i < threadArray.length; i++) { + threadArray[i].join(); + } + } + } + + private static void createZipFile() throws Exception { + Random rnd = new Random(1000L); + byte[] contents = new byte[2_000_000]; + ZipEntry ze = null; + + try (ZipOutputStream zos = + new ZipOutputStream(new FileOutputStream(ZIPFILE_NAME))) { + // uncompressed mode seemed to tickle the crash + zos.setMethod(ZipOutputStream.STORED); + for (int ze_count = 0; ze_count < 10; ze_count++) { + rnd.nextBytes(contents); + ze = createZipEntry(contents, ze_count); + zos.putNextEntry(ze); + zos.write(contents, 0, contents.length); + } + zos.flush(); + } + } + + private static ZipEntry createZipEntry(byte[] b, int i) { + ZipEntry ze = new ZipEntry(ZIPENTRY_NAME + "_" + i); + ze.setCompressedSize(b.length); + ze.setSize(b.length); + CRC32 crc = new CRC32(); + crc.update(b); + ze.setCrc(crc.getValue()); + return ze; + } + + @Override + public void run() { + try { + int iteration = 0; + TimerTask tt = (new TimerTask() { + @Override + public void run() { + try { + is.close(); + } catch (Exception ex) { + ex.printStackTrace(System.out); + } + } + }); + timer.schedule(tt, 50); + while (is.read() != -1 && iteration++ < 1_000) { } + } catch (ZipException ze) { + // ZipException now expected instead of ZIP_Read crash + System.out.println(ze); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + timer.cancel(); + } + } +}
--- a/test/javax/print/PrintSEUmlauts/PrintSEUmlauts.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/javax/print/PrintSEUmlauts/PrintSEUmlauts.java Thu Oct 29 17:12:06 2015 -0700 @@ -85,7 +85,7 @@ private static final boolean DEBUG = false; private static void testPrintAndExit() { - String expected = "<e4> 7.44 100.0 100.0 S"; + String expected = "<e4>"; String content = ""; File file = new File("out.ps");
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/xml/bind/jxc/8073519/InputWithError.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,30 @@ +/* + * 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 javax.xml.bind.annotation.XmlType; + +@XmlType +public class InputWithError { + public int a; + int compile-error; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/javax/xml/bind/jxc/8073519/SchemagenErrorReporting.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,91 @@ +/* + * 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 8073519 + * @summary test that schemagen tool reports errors during + * xsd generation process + * @library /lib/testlibrary + * @run testng/othervm SchemagenErrorReporting + */ +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.stream.Collectors; +import jdk.testlibrary.JDKToolLauncher; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SchemagenErrorReporting { + + @Test + public void schemagenErrorReporting() throws Exception { + //schemagen tool output file name + final String SCHEMA_FILE = "schema1.xsd"; + //Schemagen input java file with not compilable source + final String CLASS_FILE = "InputWithError.java"; + //Test working, src directories and test output file + Path testWorkDir, testSrcDir, testOutput; + + //Prepare test environment + //Create test directory inside scratch + testWorkDir = Paths.get(System.getProperty("user.dir", ".")) + .resolve("SchemagenErrorReporting"); + //Get test source directory + testSrcDir = Paths.get(System.getProperty("test.src", ".")); + //Set test output file path + testOutput = testWorkDir.resolve("stdErrContent"); + //Create test directory inside scratch directory + Files.createDirectory(testWorkDir); + //Copy java source from test.src to the test directory + Files.copy(testSrcDir.resolve(CLASS_FILE), testWorkDir.resolve(CLASS_FILE), + StandardCopyOption.REPLACE_EXISTING); + + //Prepare process builder to run schemagen tool and save its output + JDKToolLauncher sgl = JDKToolLauncher.createUsingTestJDK("schemagen"); + sgl.addToolArg(CLASS_FILE); + System.out.println("Executing: " + Arrays.asList(sgl.getCommand())); + ProcessBuilder pb = new ProcessBuilder(sgl.getCommand()); + //Set schemagen work directory with the input java file + pb.directory(testWorkDir.toFile()); + //Redirect schemagen output to file + pb.redirectError(testOutput.toFile()); + Process p = pb.start(); + int result = p.waitFor(); + p.destroy(); + + //Read schemagen output from the file + String stdErrContent = Files.lines(testOutput) + .collect(Collectors.joining(System.lineSeparator(), System.lineSeparator(), "")); + System.out.println("Schemagen return value:" + result); + System.out.println("Error output:" + stdErrContent); + //Check test results: + //Schemagen finished with non-0 return value + Assert.assertNotEquals(result, 0); + //Schemagen output contains compile error message + Assert.assertTrue(stdErrContent.contains("InputWithError.java:28: error")); + } +}
--- a/test/lib/testlibrary/jsr292/com/oracle/testlibrary/jsr292/Helper.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/lib/testlibrary/jsr292/com/oracle/testlibrary/jsr292/Helper.java Thu Oct 29 17:12:06 2015 -0700 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -315,4 +315,33 @@ } return null; } + + /** + * Routine used to obtain a randomly generated method type. + * + * @param arity Arity of returned method type. + * @return MethodType generated randomly. + */ + public static MethodType randomMethodTypeGenerator(int arity) { + final Class<?>[] CLASSES = { + Object.class, + int.class, + boolean.class, + byte.class, + short.class, + char.class, + long.class, + float.class, + double.class + }; + if (arity > MAX_ARITY) { + throw new IllegalArgumentException( + String.format("Arity should not exceed %d!", MAX_ARITY)); + } + List<Class<?>> list = randomClasses(CLASSES, arity); + list = getParams(list, false, arity); + int i = RNG.nextInt(CLASSES.length + 1); + Class<?> rtype = i == CLASSES.length ? void.class : CLASSES[i]; + return MethodType.methodType(rtype, list); + } }
--- a/test/sun/net/util/IPAddressUtilTest.java Wed Oct 21 20:59:47 2015 +0300 +++ b/test/sun/net/util/IPAddressUtilTest.java Thu Oct 29 17:12:06 2015 -0700 @@ -21,6 +21,12 @@ * questions. */ +/* + * @test + * @bug 8087190 + * @summary Exercise the sun.net.util.IPAddressUtil class + */ + import sun.net.util.*; /* @@ -39,6 +45,10 @@ {"238.255.2550.255", bad}, {"238.2550.255.255", bad}, {"2380.255.255.255", bad}, + {".1.1.1", bad}, + {"1..1.1", bad}, + {"1.1.1.", bad}, + {"...", bad}, {"10::10", good}, {"10::10.1", bad}, {"10::10.1.2", bad},
--- a/test/sun/security/provider/certpath/ReverseBuilder/BuildPath.java Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2007, 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 6511784 - * @summary Make sure that building a path to a CRL issuer works in the - * reverse direction - * @library ../../../../../java/security/testlibrary - * @build CertUtils - * @run main BuildPath - */ -import java.security.cert.*; -import java.util.Collections; -import sun.security.provider.certpath.SunCertPathBuilderParameters; - -public class BuildPath { - - public static void main(String[] args) throws Exception { - - TrustAnchor anchor = - new TrustAnchor(CertUtils.getCertFromFile("mgrM2mgrM"), null); - X509Certificate target = CertUtils.getCertFromFile("mgrM2leadMA"); - X509CertSelector xcs = new X509CertSelector(); - xcs.setSubject("CN=leadMA,CN=mgrM,OU=prjM,OU=divE,OU=Comp,O=sun,C=us"); - xcs.setCertificate(target); - SunCertPathBuilderParameters params = - new SunCertPathBuilderParameters(Collections.singleton(anchor),xcs); - params.setBuildForward(false); - CertStore cs = CertUtils.createStore(new String[] - {"mgrM2prjM", "prjM2mgrM", "prjM2divE", "mgrM2leadMA" }); - params.addCertStore(cs); - CertStore cs2 = CertUtils.createCRLStore - (new String[] {"mgrMcrl", "prjMcrl"}); - params.addCertStore(cs2); - PKIXCertPathBuilderResult res = CertUtils.build(params); - } -}
--- a/test/sun/security/provider/certpath/ReverseBuilder/ReverseBuild.java Wed Oct 21 20:59:47 2015 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,345 +0,0 @@ -/* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * 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 7167988 - * @summary PKIX CertPathBuilder in reverse mode doesn't work if more than - * one trust anchor is specified - */ -import java.io.*; -import java.util.*; -import java.security.cert.*; - -import sun.security.provider.certpath.SunCertPathBuilderParameters; - -public class ReverseBuild { - // Certificate information: - // Issuer: C=US, ST=Some-State, L=Some-City, O=Some-Org - // Validity - // Not Before: Dec 8 02:43:36 2008 GMT - // Not After : Aug 25 02:43:36 2028 GMT - // Subject: C=US, ST=Some-State, L=Some-City, O=Some-Org - // X509v3 Subject Key Identifier: - // FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14 - // X509v3 Authority Key Identifier: - // keyid:FA:B9:51:BF:4C:E7:D9:86:98:33:F9:E7:CB:1E:F1:33:49:F7:A8:14 - // DirName:/C=US/ST=Some-State/L=Some-City/O=Some-Org - // serial:00 - static String NoiceTrusedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICrDCCAhWgAwIBAgIBADANBgkqhkiG9w0BAQQFADBJMQswCQYDVQQGEwJVUzET\n" + - "MBEGA1UECBMKU29tZS1TdGF0ZTESMBAGA1UEBxMJU29tZS1DaXR5MREwDwYDVQQK\n" + - "EwhTb21lLU9yZzAeFw0wODEyMDgwMjQzMzZaFw0yODA4MjUwMjQzMzZaMEkxCzAJ\n" + - "BgNVBAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMRIwEAYDVQQHEwlTb21lLUNp\n" + - "dHkxETAPBgNVBAoTCFNvbWUtT3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + - "gQDLxDggB76Ip5OwoUNRLdeOha9U3a2ieyNbz5kTU5lFfe5tui2/461uPZ8a+QOX\n" + - "4BdVrhEmV94BKY4FPyH35zboLjfXSKxT1mAOx1Bt9sWF94umxZE1cjyU7vEX8HHj\n" + - "7BvOyk5AQrBt7moO1uWtPA/JuoJPePiJl4kqlRJM2Akq6QIDAQABo4GjMIGgMB0G\n" + - "A1UdDgQWBBT6uVG/TOfZhpgz+efLHvEzSfeoFDBxBgNVHSMEajBogBT6uVG/TOfZ\n" + - "hpgz+efLHvEzSfeoFKFNpEswSTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUt\n" + - "U3RhdGUxEjAQBgNVBAcTCVNvbWUtQ2l0eTERMA8GA1UEChMIU29tZS1PcmeCAQAw\n" + - "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBcIm534U123Hz+rtyYO5uA\n" + - "ofd81G6FnTfEAV8Kw9fGyyEbQZclBv34A9JsFKeMvU4OFIaixD7nLZ/NZ+IWbhmZ\n" + - "LovmJXyCkOufea73pNiZ+f/4/ScZaIlM/PRycQSqbFNd4j9Wott+08qxHPLpsf3P\n" + - "6Mvf0r1PNTY2hwTJLJmKtg==\n" + - "-----END CERTIFICATE-----"; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: Aug 19 01:52:19 2011 GMT - // Not After : Jul 29 01:52:19 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce - - // X509v3 Subject Key Identifier: - // B9:7C:D5:D9:DF:A7:4C:03:AE:FD:0E:27:5B:31:95:6C:C7:F3:75:E1 - // X509v3 Authority Key Identifier: - // keyid:B9:7C:D5:D9:DF:A7:4C:03:AE:FD:0E:27:5B:31:95:6C:C7:F3:75:E1 - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String NoiceTrusedCertStr_2nd = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" + - "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" + - "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" + - "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" + - "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" + - "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" + - "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" + - "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" + - "-----END CERTIFICATE-----"; - - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:50 2012 GMT - // Not After : Apr 15 02:40:50 2033 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce - // X509v3 Subject Key Identifier: - // DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQIFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUwWhcNMzMwNDE1MDI0MDUwWjA7MQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" + - "KoZIhvcNAQEBBQADgY0AMIGJAoGBANtiq0AIJK+iVRwFrqcD7fYXTCbMYC5Qz/k6\n" + - "AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwvzuURbc9+paOBWeHbN+Sc\n" + - "x3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStFhSHXATjtdbskNOAYGLTV\n" + - "x8uEy9GbAgMBAAGjgaUwgaIwHQYDVR0OBBYEFN1OjSoRwIMD8Kzror/58n3IaR+b\n" + - "MGMGA1UdIwRcMFqAFN1OjSoRwIMD8Kzror/58n3IaR+boT+kPTA7MQswCQYDVQQG\n" + - "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" + - "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEC\n" + - "BQADgYEAjjkJesQrkbr36N40egybaIxw7RcqT6iy5fkAGS1JYlBDk8uSCK1o6bCH\n" + - "ls5EpYcGeEoabSS73WRdkO1lgeyWDduO4ef8cCCSpmpT6/YdZG0QS1PtcREeVig+\n" + - "Zr25jNemS4ADHX0aaXP4kiV/G80cR7nX5t5XCUm4bYdbwM07NgI=\n" + - "-----END CERTIFICATE-----"; - static String trustedPrivateKey = // Private key in the format of PKCS#8 - "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANtiq0AIJK+iVRwF\n" + - "rqcD7fYXTCbMYC5Qz/k6AXBy7/1rI8wDhEJLE3m/+NSqiJwZcmdq2dNh/1fJFrwv\n" + - "zuURbc9+paOBWeHbN+Scx3huw91oPZme385VpoK3G13rSE114S/rF4DM9mz4EStF\n" + - "hSHXATjtdbskNOAYGLTVx8uEy9GbAgMBAAECgYEA2VjHkIiA0ABjkX+PqKeb+VLb\n" + - "fxS7tSca5C8zfdRhLxAWRui0/3ihst0eCJNrBDuxvAOACovsDWyLuaUjtI2v2ysz\n" + - "vz6SPyGy82PhQOFzyKQuQ814N6EpothpiZzF0yFchfKIGhUsdY89UrGs9nM7m6NT\n" + - "rztYvgIu4avg2VPR2AECQQD+pFAqipR2BplQRIuuRSZfHRxvoEyDjT1xnHJsC6WP\n" + - "I5hCLghL91MhQGWbP4EJMKYQOTRVukWlcp2Kycpf+P5hAkEA3I43gmVUAPEdyZdY\n" + - "fatW7OaLlbbYJb6qEtpCZ1Rwe/BIvm6H6E3qSi/lpz7Ia7WDulpbF6BawHH3pRFq\n" + - "CUY5ewJBAP3pUDqrRpBN0jB0uSeDslhjSciQ+dqvSpZv3rSYBHUvlBJhnkpJiy37\n" + - "7ZUZhIxqYxyIPgRBolLwb+FFh7OdL+ECQCtldDic9WVmC+VheRDpCKZ+SlK/8lGi\n" + - "7VXeShiIvcU1JysJFoa35fSI7hf1O3wt7+hX5PqGG7Un94EsJwACKEcCQQC1TWt6\n" + - "ArKH6tRxKjOxFtqfs8fgEVYUaOr3j1jF4KBUuX2mtQtddZe3VfJ2wPsuKMMxmhkB\n" + - "e7xWWZnJsErt2e+E"; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce - // Validity - // Not Before: May 5 02:40:53 2012 GMT - // Not After : Jan 21 02:40:53 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // X509v3 Subject Key Identifier: - // 13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // X509v3 Authority Key Identifier: - // keyid:DD:4E:8D:2A:11:C0:83:03:F0:AC:EB:A2:BF:F9:F2:7D:C8:69:1F:9B - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:00 - static String caSignerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICqDCCAhGgAwIBAgIBAjANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" + - "MTIwNTA1MDI0MDUzWhcNMzIwMTIxMDI0MDUzWjBOMQswCQYDVQQGEwJVUzENMAsG\n" + - "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAPBgNV\n" + - "BAMTCGNhc2lnbmVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+x8+o7oM0\n" + - "ct/LZmZLXBL4CQ8jrULD5P7NtEW0hg/zxBFZfBHf+44Oo2eMPYZj+7xaREOH5BmV\n" + - "KRYlzRtONAaC5Ng4Mrm5UKNPcMIIUjUOvm7vWM4oSTMSfoEcSX+vp99uUAkw3w7Z\n" + - "+frYDm1M4At/j0b+lLij71GFN2L8drpgPQIDAQABo4GoMIGlMB0GA1UdDgQWBBQT\n" + - "B+ARB9vrMyOHMdDbfhZWvhGQCjBjBgNVHSMEXDBagBTdTo0qEcCDA/Cs66K/+fJ9\n" + - "yGkfm6E/pD0wOzELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsT\n" + - "FFN1bkpTU0UgVGVzdCBTZXJpdmNlggEAMBIGA1UdEwEB/wQIMAYBAf8CAQEwCwYD\n" + - "VR0PBAQDAgEGMA0GCSqGSIb3DQEBBAUAA4GBAI+LXA/UCPkTANablUkt80JNPWsl\n" + - "pS4XLNgPxWaN0bkRDs5oI4ooWAz1rwpeJ/nfetOvWlpmrVjSeovBFja5Hl+dUHTf\n" + - "VfuyzkxXbhuNiJIpo1mVBpNsjwu9YRxuwX6UA2LTUQpgvtVJEE012x3zRvxBCbu2\n" + - "Y/v1R5fZ4c+hXDfC\n" + - "-----END CERTIFICATE-----"; - static String caSignerPrivateKey = // Private key in the format of PKCS#8 - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL7Hz6jugzRy38tm\n" + - "ZktcEvgJDyOtQsPk/s20RbSGD/PEEVl8Ed/7jg6jZ4w9hmP7vFpEQ4fkGZUpFiXN\n" + - "G040BoLk2DgyublQo09wwghSNQ6+bu9YzihJMxJ+gRxJf6+n325QCTDfDtn5+tgO\n" + - "bUzgC3+PRv6UuKPvUYU3Yvx2umA9AgMBAAECgYBYvu30cW8LONyt62Zua9hPFTe7\n" + - "qt9B7QYyfkdmoG5PQMepTrOp84SzfoOukvgvDm0huFuJnSvhXQl2cCDhkgXskvFj\n" + - "Hh7KBCFViVXokGdq5YoS0/KYMyQV0TZfJUvILBl51uc4/siQ2tClC/N4sa+1JhgW\n" + - "a6dFGfRjiUKSSlmMwQJBAPWpIz3Q/c+DYMvoQr5OD8EaYwYIevlTdXb97RnJJh2b\n" + - "UnhB9jrqesJiHYVzPmP0ukyPOXOwlp2T5Am4Kw0LFOkCQQDGz150NoHOp28Mvyc4\n" + - "CTqz/zYzUhy2eCJESl196uyP4N65Y01VYQ3JDww4DlsXiU17tVSbgA9TCcfTYOzy\n" + - "vyw1AkARUky+1hafZCcWGZljK8PmnMKwsTZikCTvL/Zg5BMA8Wu+OQBwpQnk3OAy\n" + - "Aa87gw0DyvGFG8Vy9POWT9sRP1/JAkBqP0hrMvYMSs6+MSn0eHo2151PsAJIQcuO\n" + - "U2/Da1khSzu8N6WMi2GiobgV/RYRbf9KrY2ZzMZjykZQYOxAjopBAkEAghCu38cN\n" + - "aOsW6ueo24uzsWI1FTdE+qWNVEi3RSP120xXBCyhaBjIq4WVSlJK9K2aBaJpit3j\n" + - "iQ5tl6zrLlxQhg=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=casigner - // Validity - // Not Before: May 5 02:40:57 2012 GMT - // Not After : Jan 21 02:40:57 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // X509v3 Subject Key Identifier: - // 39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - // X509v3 Authority Key Identifier: - // keyid:13:07:E0:11:07:DB:EB:33:23:87:31:D0:DB:7E:16:56:BE:11:90:0A - // DirName:/C=US/O=Java/OU=SunJSSE Test Serivce - // serial:02 - static String certIssuerStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICvjCCAiegAwIBAgIBAzANBgkqhkiG9w0BAQQFADBOMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxETAP\n" + - "BgNVBAMTCGNhc2lnbmVyMB4XDTEyMDUwNTAyNDA1N1oXDTMyMDEyMTAyNDA1N1ow\n" + - "UDELMAkGA1UEBhMCVVMxDTALBgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0Ug\n" + - "VGVzdCBTZXJpdmNlMRMwEQYDVQQDEwpjZXJ0aXNzdWVyMIGfMA0GCSqGSIb3DQEB\n" + - "AQUAA4GNADCBiQKBgQCyz55zinU6kNL/LeiTNiBI0QWYmDG0YTotuC4D75liBNqs\n" + - "7Mmladsh2mTtQUAwmuGaGzaZV25a+cUax0DXZoyBwdbTI09u1bUYsZcaUUKbPoCC\n" + - "HH26e4jLFL4olW13Sv4ZAd57tIYevMw+Fp5f4fLPFGegCJTFlv2Qjpmic/cuvQID\n" + - "AQABo4GpMIGmMB0GA1UdDgQWBBQ5DsYzsVC8cwcx5dgE97uXVc+byDBjBgNVHSME\n" + - "XDBagBQTB+ARB9vrMyOHMdDbfhZWvhGQCqE/pD0wOzELMAkGA1UEBhMCVVMxDTAL\n" + - "BgNVBAoTBEphdmExHTAbBgNVBAsTFFN1bkpTU0UgVGVzdCBTZXJpdmNlggECMBMG\n" + - "A1UdEwEB/wQJMAcBAf8CAgQAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQQFAAOB\n" + - "gQCQTagenCdClT98C+oTJGJrw/dUBD9K3tE6ZJKPMc/2bUia8G5ei1C0eXj4mWG2\n" + - "lu9umR6C90/A6qB050QB2h50qtqxSrkpu+ym1yypauZpg7U3nUY9wZWJNI1vqrQZ\n" + - "pqUMRcXY3iQIVKx+Qj+4/Za1wwFQzpEoGmqRW31V1SdMEw==\n" + - "-----END CERTIFICATE-----"; - static String certIssuerPrivateKey = // Private key in the format of PKCS#8 - "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALLPnnOKdTqQ0v8t\n" + - "6JM2IEjRBZiYMbRhOi24LgPvmWIE2qzsyaVp2yHaZO1BQDCa4ZobNplXblr5xRrH\n" + - "QNdmjIHB1tMjT27VtRixlxpRQps+gIIcfbp7iMsUviiVbXdK/hkB3nu0hh68zD4W\n" + - "nl/h8s8UZ6AIlMWW/ZCOmaJz9y69AgMBAAECgYEAjtew2tgm4gxDojqIauF4VPM1\n" + - "pzsdqd1p3pAdomNLgrQiBLZ8N7oiph6TNb1EjA+OXc+ThFgF/oM9ZDD8qZZwcvjN\n" + - "qDZlpTkFs2TaGcyEZfUaMB45NHVs6Nn+pSkagSNwwy3xeyAct7sQEzGNTDlEwVv5\n" + - "7V9LQutQtBd6xT48KzkCQQDpNRfv2OFNG/6GtzJoO68oJhpnpl2MsYNi4ntRkre/\n" + - "6uXpiCYaDskcrPMRwOOs0m7mxG+Ev+uKnLnSoEMm1GCbAkEAxEmDtiD0Psb8Z9BL\n" + - "ZRb83Jqho3xe2MCAh3xUfz9b/Mhae9dZ44o4OCgQZuwvW1mczF0NtpgZl93BmYa2\n" + - "hTwHhwJBAKHrEj6ep/fA6x0gD2idoATRR94VfbiU+7NpqtO9ecVP0+gsdr/66hn1\n" + - "3yLBeZLh3MxvMTrLgkAQh1i9m0JXjOcCQQClLXAHHegrw+u3uNMZeKTFR+Lp3sk6\n" + - "AZSnbvr0Me9I45kxSeG81x3ENALJecvIRbrrRws5MvmmkNhQR8rkh8WVAkEAk6b+\n" + - "aVtmBgUaTS5+FFlHGHJY9HFrfT1a1C/dwyMuqlmbC3YsBmZaMOlKli5TXNybLff8\n" + - "5KMeGEpXMzgC7AscGA=="; - - // Certificate information: - // Issuer: C=US, O=Java, OU=SunJSSE Test Serivce, CN=certissuer - // Validity - // Not Before: May 5 02:41:01 2012 GMT - // Not After : Jan 21 02:41:01 2032 GMT - // Subject: C=US, O=Java, OU=SunJSSE Test Serivce, CN=localhost - // X509v3 Subject Key Identifier: - // AD:C0:2C:4C:E4:C2:2E:A1:BB:5D:92:BE:66:E0:4E:E0:0D:2F:11:EF - // X509v3 Authority Key Identifier: - // keyid:39:0E:C6:33:B1:50:BC:73:07:31:E5:D8:04:F7:BB:97:55:CF:9B:C8 - static String targetCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIICjTCCAfagAwIBAgIBBDANBgkqhkiG9w0BAQQFADBQMQswCQYDVQQGEwJVUzEN\n" + - "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEzAR\n" + - "BgNVBAMTCmNlcnRpc3N1ZXIwHhcNMTIwNTA1MDI0MTAxWhcNMzIwMTIxMDI0MTAx\n" + - "WjBPMQswCQYDVQQGEwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNT\n" + - "RSBUZXN0IFNlcml2Y2UxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0B\n" + - "AQEFAAOBjQAwgYkCgYEAvwaUd7wmBSKqycEstYLWD26vkU08DM39EtaT8wL9HnQ0\n" + - "fgPblwBFI4zdLa2cuYXRZcFUb04N8nrkcpR0D6kkE+AlFAoRWrrZF80B7JTbtEK4\n" + - "1PIeurihXvUT+4MpzGLOojIihMfvM4ufelblD56SInso4WFHm7t4qCln88J1gjkC\n" + - "AwEAAaN4MHYwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBStwCxM5MIuobtdkr5m4E7g\n" + - "DS8R7zAfBgNVHSMEGDAWgBQ5DsYzsVC8cwcx5dgE97uXVc+byDAnBgNVHSUEIDAe\n" + - "BggrBgEFBQcDAQYIKwYBBQUHAwIGCCsGAQUFBwMDMA0GCSqGSIb3DQEBBAUAA4GB\n" + - "AGfwcfdvEG/nSCiAn2MGbYHp34mgF3OA1SJLWUW0LvWJhwm2cn4AXlSoyvbwrkaB\n" + - "IDDCwhJvvc0vUyL2kTx7sqVaFTq3mDs+ktlB/FfH0Pb+i8FE+g+7T42Iw/j0qxHL\n" + - "YmgbrjBQf5WYN1AvBE/rrPt9aOtS3UsqtVGW574b0shW\n" + - "-----END CERTIFICATE-----"; - static String targetPrivateKey = // Private key in the format of PKCS#8 - "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAL8GlHe8JgUiqsnB\n" + - "LLWC1g9ur5FNPAzN/RLWk/MC/R50NH4D25cARSOM3S2tnLmF0WXBVG9ODfJ65HKU\n" + - "dA+pJBPgJRQKEVq62RfNAeyU27RCuNTyHrq4oV71E/uDKcxizqIyIoTH7zOLn3pW\n" + - "5Q+ekiJ7KOFhR5u7eKgpZ/PCdYI5AgMBAAECf3CscOYvFD3zNMnMJ5LomVqA7w3F\n" + - "gKYM2jlCWAH+wU41PMEXhW6Lujw92jgXL1o+lERwxFzirVdZJWZwKgUSvzP1G0h3\n" + - "fkucq1/UWnToK+8NSXNM/yS8hXbBgSEoJo5f7LKcIi1Ev6doBVofMxs+njzyWKbM\n" + - "Nb7rOLHadghoon0CQQDgQzbzzSN8Dc1YmmylhI5v+0sQRHH0DL7D24k4Weh4vInG\n" + - "EAbt4x8M7ZKEo8/dv0s4hbmNmAnJl93/RRxIyEqLAkEA2g87DiswSQam2pZ8GlrO\n" + - "+w4Qg9mH8uxx8ou2rl0XlHzH1XiTNbkjfY0EZoL7L31BHFk9n11Fb2P85g6ws+Hy\n" + - "ywJAM/xgyLNM/nzUlS128geAXUULaYH0SHaL4isJ7B4rXZGW/mrIsGxtzjlkNYsj\n" + - "rGujrD6TfNc5rZmexIXowJZtcQJBAIww+pCzZ4mrgx5JXWQ8OZHiiu+ZrPOa2+9J\n" + - "r5sOMpi+WGN/73S8oHqZbNjTINZ5OqEVJq8MchWZPQBTNXuQql0CQHEjUzzkCQa3\n" + - "j6JTa2KAdqyvLOx0XF9zcc1gA069uNQI2gPUHS8V215z57f/gMGnDNhVfLs/vMKz\n" + - "sFkVZ3zg7As="; - - - public static void main(String args[]) throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a set of trust anchors - LinkedHashSet<TrustAnchor> trustAnchors = new LinkedHashSet<>(); - - ByteArrayInputStream is = - new ByteArrayInputStream(NoiceTrusedCertStr.getBytes()); - Certificate trustedCert = cf.generateCertificate(is); - is.close(); - TrustAnchor anchor = - new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - is = new ByteArrayInputStream(trustedCertStr.getBytes()); - trustedCert = cf.generateCertificate(is); - is.close(); - anchor = new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - is = new ByteArrayInputStream(NoiceTrusedCertStr_2nd.getBytes()); - trustedCert = cf.generateCertificate(is); - is.close(); - anchor = new TrustAnchor((X509Certificate)trustedCert, null); - trustAnchors.add(anchor); - - // create a list of certificates - List<Certificate> chainList = new ArrayList<>(); - - is = new ByteArrayInputStream(targetCertStr.getBytes()); - Certificate cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - is = new ByteArrayInputStream(certIssuerStr.getBytes()); - cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - is = new ByteArrayInputStream(caSignerStr.getBytes()); - cert = cf.generateCertificate(is); - is.close(); - chainList.add(cert); - - // create a certificate selector - X509CertSelector xcs = new X509CertSelector(); - X509Certificate eeCert = (X509Certificate)chainList.get(0); - xcs.setSubject(eeCert.getSubjectX500Principal()); - - // reverse build - SunCertPathBuilderParameters params = - new SunCertPathBuilderParameters(trustAnchors, xcs); - params.setBuildForward(false); - params.setRevocationEnabled(false); - - CollectionCertStoreParameters ccsp = - new CollectionCertStoreParameters(chainList); - params.addCertStore(CertStore.getInstance("Collection", ccsp)); - - CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX"); - CertPathBuilderResult res = cpb.build(params); - } -}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/test/sun/util/resources/TimeZone/Bug8139107.java Thu Oct 29 17:12:06 2015 -0700 @@ -0,0 +1,59 @@ +/* + * 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 8139107 + * @summary Test that date parsing with DateTimeFormatter pattern + * that contains timezone field doesn't trigger NPE. All supported + * locales are tested. + * @run testng/othervm -Djava.locale.providers=JRE,SPI Bug8139107 + */ +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import org.testng.annotations.Test; + +public class Bug8139107 { + + @Test + public void testSupportedLocales() { + for (Locale loc:Locale.getAvailableLocales()) { + testLocale(loc); + } + } + + //Test one locale + void testLocale(Locale tl) { + System.out.println("Locale:" + tl); + DateTimeFormatter inputDateTimeFormat = DateTimeFormatter + .ofPattern(pattern) + .withLocale(tl); + System.out.println("Parse result: " + inputDateTimeFormat.parse(inputDate)); + } + + // Input date time string with short time zone name + static final String inputDate = "06-10-2015 18:58:04 MSK"; + // Pattern with time zone field + static final String pattern = "dd-MM-yyyy HH:mm:ss z"; +} +