This commit is contained in:
Lana Steuck 2014-12-11 12:27:27 -08:00
commit 7471e6a63c
113 changed files with 2352 additions and 1974 deletions

View File

@ -46,8 +46,7 @@ $(eval $(call SetupJavaCompilation,BUILD_INTERIM_RMIC, \
SRC := $(JDK_TOPDIR)/src/jdk.rmic/share/classes, \
INCLUDES := $(RMIC_PKGS), \
BIN := $(BUILDTOOLS_OUTPUTDIR)/interim_rmic_classes, \
COPY := .properties, \
JAVAC_SOURCE_PATH_OVERRIDE := $(addprefix $(JDK_TOPDIR)/src/jdk.rmic/share/classes/, $(RMIC_PKGS))))
COPY := .properties))
##########################################################################################

View File

@ -221,8 +221,13 @@ $(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/_the.sa.jar.unpacked: $(HOTSPOT_DIST)
# even if zip is already unpacked.
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.hotspot.agent/_the.sa.services: $(HOTSPOT_DIST)/lib/sa-jdi.jar
SA_TARGETS += $(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/_the.sa.jar.unpacked \
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.hotspot.agent/_the.sa.services
# Some platforms don't have the serviceability agent
ifeq (, $(filter $(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU), aix-ppc64))
ifneq ($(JVM_VARIANT_ZERO), true)
SA_TARGETS += $(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/_the.sa.jar.unpacked \
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.hotspot.agent/_the.sa.services
endif
endif
################################################################################

View File

@ -44,17 +44,10 @@ TEXT_SOURCES := $(TEXT_PKG)/BreakIteratorRules.java \
# Generate BreakIteratorData
BREAK_ITERATOR_CLASSES := $(BUILDTOOLS_OUTPUTDIR)/break_iterator_classes
# JAVAC_SOURCE_PATH_OVERRIDE is set to isolate the compile to just those
# two files in that directory and not get anything implicit from
# surrounding directories which aren't jdk N-1 compatible.
# Because we are targeting jdk N-1, but the surrounding source code is jdk N.
# These two files should be moved out to a build tool! We have to disable
# sjavac here as well.
# These two files should be moved out to a build tool!
$(eval $(call SetupJavaCompilation,BUILD_BREAKITERATOR, \
SETUP := GENERATE_OLDBYTECODE, \
SRC := $(TEXT_SRCDIR), \
DISABLE_SJAVAC := true, \
JAVAC_SOURCE_PATH_OVERRIDE := $(patsubst %, %/$(TEXT_PKG), $(TEXT_SRCDIR)), \
INCLUDES := $(TEXT_PKG), \
INCLUDE_FILES := $(TEXT_SOURCES), \
BIN := $(BREAK_ITERATOR_CLASSES)))

View File

@ -78,8 +78,13 @@ $(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/META-INF/services/com.sun.jdi.connect
$(SUPPORT_OUTPUTDIR)/gensrc/jdk.jdi/META-INF/services/com.sun.jdi.connect.Connector
$(install-file)
GENSRC_JDK_JDI += $(SUPPORT_OUTPUTDIR)/gensrc/jdk.jdi/META-INF/services/com.sun.jdi.connect.Connector \
$(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/META-INF/services/com.sun.jdi.connect.Connector
# Some platforms don't have the serviceability agent
ifeq (, $(filter $(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU), aix-ppc64))
ifneq ($(JVM_VARIANT_ZERO), true)
GENSRC_JDK_JDI += $(SUPPORT_OUTPUTDIR)/gensrc/jdk.jdi/META-INF/services/com.sun.jdi.connect.Connector \
$(JDK_OUTPUTDIR)/modules/jdk.hotspot.agent/META-INF/services/com.sun.jdi.connect.Connector
endif
endif
################################################################################

View File

@ -116,7 +116,7 @@ define SetupLauncher
endif
ifeq ($(OPENJDK_TARGET_OS), aix)
$1_LDFLAGS_SUFFIX += -L$(SUPPORT_OUTPUTDIR)/native/$(MODULE) -ljli_static
$1_LDFLAGS_SUFFIX += -L$(SUPPORT_OUTPUTDIR)/native/java.base -ljli_static
endif
ifeq ($(USE_EXTERNAL_LIBZ), true)

View File

@ -367,7 +367,7 @@ ifeq ($(findstring $(OPENJDK_TARGET_OS),windows macosx),)
$(X_LIBS) $(LIBAWT_XAWT_LDFLAGS) \
$(call SET_SHARED_LIBRARY_ORIGIN) \
$(call SET_SHARED_LIBRARY_ORIGIN,/..) \
-L $(INSTALL_LIBRARIES_HERE), \
-L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_SUFFIX := $(LIBAWT_XAWT_LDFLAGS_SUFFIX), \
VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \
RC_FLAGS := $(RC_FLAGS) \
@ -421,7 +421,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBLCMS, \
MAPFILE := $(JDK_TOPDIR)/make/mapfiles/liblcms/mapfile-vers, \
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN), \
LDFLAGS_unix := -L $(INSTALL_LIBRARIES_HERE), \
LDFLAGS_unix := -L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_solaris := /usr/lib$(OPENJDK_TARGET_CPU_ISADIR)/libm.so.2, \
LDFLAGS_windows := $(WIN_AWT_LIB) $(WIN_JAVA_LIB), \
LDFLAGS_SUFFIX_solaris := -lawt -ljava -ljvm -lc $(LCMS_LIBS), \
@ -581,7 +581,7 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBFONTMANAGER, \
MAPFILE := $(BUILD_LIBFONTMANAGER_MAPFILE), \
LDFLAGS := $(subst -Xlinker -z -Xlinker defs,,$(LDFLAGS_JDKLIB)) $(LDFLAGS_CXX_JDK) \
$(call SET_SHARED_LIBRARY_ORIGIN), \
LDFLAGS_unix := -L $(INSTALL_LIBRARIES_HERE), \
LDFLAGS_unix := -L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_SUFFIX := $(BUILD_LIBFONTMANAGER_FONTLIB), \
LDFLAGS_SUFFIX_linux := -lawt $(LIBM) $(LIBCXX) -ljava -ljvm -lc, \
LDFLAGS_SUFFIX_solaris := $(filter-out -R%, $(X_LIBS)) \
@ -698,7 +698,7 @@ else # OPENJDK_TARGET_OS not windows
MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libjawt/mapfile-vers, \
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN), \
LDFLAGS_unix := -L $(INSTALL_LIBRARIES_HERE), \
LDFLAGS_unix := -L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_solaris := $(X_LIBS), \
LDFLAGS_SUFFIX_linux := $(JAWT_LIBS) $(LDFLAGS_JDKLIB_SUFFIX), \
LDFLAGS_SUFFIX_aix := $(JAWT_LIBS) $(LDFLAGS_JDKLIB_SUFFIX),\
@ -775,7 +775,7 @@ ifeq ($(BUILD_HEADLESS), true)
MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libawt_headless/mapfile-vers, \
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN), \
LDFLAGS_unix := -L $(INSTALL_LIBRARIES_HERE), \
LDFLAGS_unix := -L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_linux := $(call SET_SHARED_LIBRARY_ORIGIN,/..), \
LDFLAGS_solaris := $(call SET_SHARED_LIBRARY_ORIGIN,/..), \
LDFLAGS_macosx := $(call SET_SHARED_LIBRARY_ORIGIN)., \
@ -954,7 +954,7 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
$(LIBAWT_LWAWT_CFLAGS), \
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN) \
-L $(INSTALL_LIBRARIES_HERE), \
-L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_SUFFIX_macosx := -lawt -lmlib_image -losxapp -ljvm $(LIBM) \
-framework Accelerate \
-framework ApplicationServices \
@ -1002,7 +1002,7 @@ ifeq ($(OPENJDK_TARGET_OS), macosx)
LDFLAGS := $(LDFLAGS_JDKLIB) \
$(call SET_SHARED_LIBRARY_ORIGIN) \
-Xlinker -rpath -Xlinker @loader_path \
-L $(INSTALL_LIBRARIES_HERE), \
-L$(INSTALL_LIBRARIES_HERE), \
LDFLAGS_SUFFIX_macosx := -lawt -losxapp -lawt_lwawt \
-framework Cocoa \
-framework Carbon \

View File

@ -72,8 +72,8 @@ $(eval $(call SetupNativeCompilation,BUILD_LIBINSTRUMENT, \
-framework Cocoa -framework Security -framework ApplicationServices, \
LDFLAGS_SUFFIX := $(LIBINSTRUMENT_LDFLAGS_SUFFIX), \
LDFLAGS_SUFFIX_macosx := -liconv $(LIBZ), \
LDFLAGS_SUFFIX_solaris := $(LIBZ) -L $(call FindLibDirForModule, java.base)/jli -ljli $(LIBDL) -lc, \
LDFLAGS_SUFFIX_linux := $(LIBZ) -L $(call FindLibDirForModule, java.base)/jli -ljli $(LIBDL), \
LDFLAGS_SUFFIX_solaris := $(LIBZ) -L$(call FindLibDirForModule, java.base)/jli -ljli $(LIBDL) -lc, \
LDFLAGS_SUFFIX_linux := $(LIBZ) -L$(call FindLibDirForModule, java.base)/jli -ljli $(LIBDL), \
LDFLAGS_SUFFIX_aix := $(LIBZ) -L$(SUPPORT_OUTPUTDIR)/native/java.base -ljli_static $(LIBDL),\
VERSIONINFO_RESOURCE := $(GLOBAL_VERSION_INFO_RESOURCE), \
RC_FLAGS := $(RC_FLAGS) \

View File

@ -79,7 +79,9 @@ endif
# Param 2 - library name
# Param 3 - subdir for library
define FindLib
$(call FindLibDirForModule, $(strip $1))$(strip $3)/$(LIBRARY_PREFIX)$(strip $2)$(SHARED_LIBRARY_SUFFIX)
$(strip \
$(call FindLibDirForModule, $(strip $1))$(strip $3)/$(LIBRARY_PREFIX)$(strip $2)$(SHARED_LIBRARY_SUFFIX) \
)
endef
################################################################################

View File

@ -349,21 +349,6 @@ class ImageBuilder {
return (new SimpleResolver(mods, moduleGraph)).resolve();
}
/**
* chmod ugo+x file
*/
private void setExecutable(Path file) {
try {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(file, perms);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
private void createImage() throws IOException {
Collection<String> modules = resolve(options.mods);
log.print(modules.stream().collect(Collectors.joining(" ")));
@ -377,7 +362,7 @@ class ImageBuilder {
.filter(f -> f.getFileName().equals(jspawnhelper))
.findFirst();
if (helper.isPresent())
setExecutable(helper.get());
helper.get().toFile().setExecutable(true, false);
}
private class ImageFileHelper {

View File

@ -194,7 +194,7 @@ public class ModuleArchive implements Archive {
case CMDS:
Path path = destFile("bin", filename);
writeEntry(in, path);
path.toFile().setExecutable(true);
path.toFile().setExecutable(true, false);
break;
case CONFIGS:
writeEntry(in, destFile("conf", filename));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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
@ -38,7 +38,6 @@
#include <sys/time.h>
#include "manifest_info.h"
#include "version_comp.h"
/* Support Cocoa event loop on the main thread */
#include <Cocoa/Cocoa.h>
@ -104,10 +103,6 @@ struct NSAppArgs {
* (incoming argv)
* |
* \|/
* SelectVersion
* (selects the JRE version, note: not data model)
* |
* \|/
* CreateExecutionEnvironment
* (determines desired data model)
* |

View File

@ -184,8 +184,8 @@ public final class String
* The length
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code count} arguments index
* characters outside the bounds of the {@code value} array
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code value.length - count}
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
@ -224,8 +224,8 @@ public final class String
* codePoints}
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code count} arguments index
* characters outside the bounds of the {@code codePoints} array
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code codePoints.length - count}
*
* @since 1.5
*/
@ -297,7 +297,8 @@ public final class String
* The length
*
* @throws IndexOutOfBoundsException
* If the {@code offset} or {@code count} argument is invalid
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code ascii.length - count}
*
* @see #String(byte[], int)
* @see #String(byte[], int, int, java.lang.String)
@ -401,8 +402,8 @@ public final class String
* If the named charset is not supported
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.1
*/
@ -439,8 +440,8 @@ public final class String
* decode the {@code bytes}
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.6
*/
@ -524,8 +525,8 @@ public final class String
* The number of bytes to decode
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and the {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.1
*/

View File

@ -2028,7 +2028,7 @@ return invoker;
MethodType oldType = target.type();
if (oldType == newType) return target;
if (oldType.explicitCastEquivalentToAsType(newType)) {
return target.asType(newType);
return target.asFixedArity().asType(newType);
}
return MethodHandleImpl.makePairwiseConvert(target, newType, false);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 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
@ -38,6 +38,7 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import sun.nio.ch.ChannelInputStream;
import sun.nio.cs.StreamDecoder;
@ -48,8 +49,8 @@ import sun.nio.cs.StreamEncoder;
* Utility methods for channels and streams.
*
* <p> This class defines static methods that support the interoperation of the
* stream classes of the <tt>{@link java.io}</tt> package with the channel
* classes of this package. </p>
* stream classes of the {@link java.io} package with the channel classes
* of this package. </p>
*
*
* @author Mark Reinhold
@ -60,12 +61,7 @@ import sun.nio.cs.StreamEncoder;
public final class Channels {
private Channels() { } // No instantiation
private static void checkNotNull(Object o, String name) {
if (o == null)
throw new NullPointerException("\"" + name + "\" is null!");
}
private Channels() { throw new Error("no instances"); }
/**
* Write all remaining bytes in buffer to the given channel.
@ -91,7 +87,7 @@ public final class Channels {
throws IOException
{
if (ch instanceof SelectableChannel) {
SelectableChannel sc = (SelectableChannel)ch;
SelectableChannel sc = (SelectableChannel) ch;
synchronized (sc.blockingLock()) {
if (!sc.isBlocking())
throw new IllegalBlockingModeException();
@ -107,7 +103,7 @@ public final class Channels {
/**
* Constructs a stream that reads bytes from the given channel.
*
* <p> The <tt>read</tt> methods of the resulting stream will throw an
* <p> The {@code read} methods of the resulting stream will throw an
* {@link IllegalBlockingModeException} if invoked while the underlying
* channel is in non-blocking mode. The stream will not be buffered, and
* it will not support the {@link InputStream#mark mark} or {@link
@ -121,14 +117,14 @@ public final class Channels {
* @return A new input stream
*/
public static InputStream newInputStream(ReadableByteChannel ch) {
checkNotNull(ch, "ch");
return new sun.nio.ch.ChannelInputStream(ch);
Objects.requireNonNull(ch, "ch");
return new ChannelInputStream(ch);
}
/**
* Constructs a stream that writes bytes to the given channel.
*
* <p> The <tt>write</tt> methods of the resulting stream will throw an
* <p> The {@code write} methods of the resulting stream will throw an
* {@link IllegalBlockingModeException} if invoked while the underlying
* channel is in non-blocking mode. The stream will not be buffered. The
* stream will be safe for access by multiple concurrent threads. Closing
@ -139,46 +135,49 @@ public final class Channels {
*
* @return A new output stream
*/
public static OutputStream newOutputStream(final WritableByteChannel ch) {
checkNotNull(ch, "ch");
public static OutputStream newOutputStream(WritableByteChannel ch) {
Objects.requireNonNull(ch, "ch");
return new OutputStream() {
private ByteBuffer bb = null;
private byte[] bs = null; // Invoker's previous array
private byte[] b1 = null;
private ByteBuffer bb;
private byte[] bs; // Invoker's previous array
private byte[] b1;
public synchronized void write(int b) throws IOException {
if (b1 == null)
b1 = new byte[1];
b1[0] = (byte)b;
this.write(b1);
}
@Override
public synchronized void write(int b) throws IOException {
if (b1 == null)
b1 = new byte[1];
b1[0] = (byte) b;
this.write(b1);
}
public synchronized void write(byte[] bs, int off, int len)
@Override
public synchronized void write(byte[] bs, int off, int len)
throws IOException
{
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
ByteBuffer bb = ((this.bs == bs)
? this.bb
: ByteBuffer.wrap(bs));
bb.limit(Math.min(off + len, bb.capacity()));
bb.position(off);
this.bb = bb;
this.bs = bs;
Channels.writeFully(ch, bb);
{
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
ByteBuffer bb = ((this.bs == bs)
? this.bb
: ByteBuffer.wrap(bs));
bb.limit(Math.min(off + len, bb.capacity()));
bb.position(off);
this.bb = bb;
this.bs = bs;
Channels.writeFully(ch, bb);
}
public void close() throws IOException {
ch.close();
}
@Override
public void close() throws IOException {
ch.close();
}
};
};
}
/**
@ -196,13 +195,13 @@ public final class Channels {
*
* @since 1.7
*/
public static InputStream newInputStream(final AsynchronousByteChannel ch) {
checkNotNull(ch, "ch");
public static InputStream newInputStream(AsynchronousByteChannel ch) {
Objects.requireNonNull(ch, "ch");
return new InputStream() {
private ByteBuffer bb = null;
private byte[] bs = null; // Invoker's previous array
private byte[] b1 = null;
private ByteBuffer bb;
private byte[] bs; // Invoker's previous array
private byte[] b1;
@Override
public synchronized int read() throws IOException {
@ -216,13 +215,14 @@ public final class Channels {
@Override
public synchronized int read(byte[] bs, int off, int len)
throws IOException
throws IOException
{
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0)
} else if (len == 0) {
return 0;
}
ByteBuffer bb = ((this.bs == bs)
? this.bb
@ -270,25 +270,25 @@ public final class Channels {
*
* @since 1.7
*/
public static OutputStream newOutputStream(final AsynchronousByteChannel ch) {
checkNotNull(ch, "ch");
public static OutputStream newOutputStream(AsynchronousByteChannel ch) {
Objects.requireNonNull(ch, "ch");
return new OutputStream() {
private ByteBuffer bb = null;
private byte[] bs = null; // Invoker's previous array
private byte[] b1 = null;
private ByteBuffer bb;
private byte[] bs; // Invoker's previous array
private byte[] b1;
@Override
public synchronized void write(int b) throws IOException {
if (b1 == null)
if (b1 == null)
b1 = new byte[1];
b1[0] = (byte)b;
b1[0] = (byte) b;
this.write(b1);
}
@Override
public synchronized void write(byte[] bs, int off, int len)
throws IOException
throws IOException
{
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
@ -343,12 +343,11 @@ public final class Channels {
*
* @return A new readable byte channel
*/
public static ReadableByteChannel newChannel(final InputStream in) {
checkNotNull(in, "in");
public static ReadableByteChannel newChannel(InputStream in) {
Objects.requireNonNull(in, "in");
if (in instanceof FileInputStream &&
FileInputStream.class.equals(in.getClass())) {
return ((FileInputStream)in).getChannel();
if (in.getClass() == FileInputStream.class) {
return ((FileInputStream) in).getChannel();
}
return new ReadableByteChannelImpl(in);
@ -358,16 +357,16 @@ public final class Channels {
extends AbstractInterruptibleChannel // Not really interruptible
implements ReadableByteChannel
{
InputStream in;
private final InputStream in;
private static final int TRANSFER_SIZE = 8192;
private byte buf[] = new byte[0];
private boolean open = true;
private Object readLock = new Object();
private byte[] buf = new byte[0];
private final Object readLock = new Object();
ReadableByteChannelImpl(InputStream in) {
this.in = in;
}
@Override
public int read(ByteBuffer dst) throws IOException {
int len = dst.remaining();
int totalRead = 0;
@ -399,9 +398,9 @@ public final class Channels {
}
}
@Override
protected void implCloseChannel() throws IOException {
in.close();
open = false;
}
}
@ -418,12 +417,11 @@ public final class Channels {
*
* @return A new writable byte channel
*/
public static WritableByteChannel newChannel(final OutputStream out) {
checkNotNull(out, "out");
public static WritableByteChannel newChannel(OutputStream out) {
Objects.requireNonNull(out, "out");
if (out instanceof FileOutputStream &&
FileOutputStream.class.equals(out.getClass())) {
return ((FileOutputStream)out).getChannel();
if (out.getClass() == FileOutputStream.class) {
return ((FileOutputStream) out).getChannel();
}
return new WritableByteChannelImpl(out);
@ -433,16 +431,16 @@ public final class Channels {
extends AbstractInterruptibleChannel // Not really interruptible
implements WritableByteChannel
{
OutputStream out;
private final OutputStream out;
private static final int TRANSFER_SIZE = 8192;
private byte buf[] = new byte[0];
private boolean open = true;
private Object writeLock = new Object();
private byte[] buf = new byte[0];
private final Object writeLock = new Object();
WritableByteChannelImpl(OutputStream out) {
this.out = out;
}
@Override
public int write(ByteBuffer src) throws IOException {
int len = src.remaining();
int totalWritten = 0;
@ -465,9 +463,9 @@ public final class Channels {
}
}
@Override
protected void implCloseChannel() throws IOException {
out.close();
open = false;
}
}
@ -479,7 +477,7 @@ public final class Channels {
* given decoder.
*
* <p> The resulting stream will contain an internal input buffer of at
* least <tt>minBufferCap</tt> bytes. The stream's <tt>read</tt> methods
* least {@code minBufferCap} bytes. The stream's {@code read} methods
* will, as needed, fill the buffer by reading bytes from the underlying
* channel; if the channel is in non-blocking mode when bytes are to be
* read then an {@link IllegalBlockingModeException} will be thrown. The
@ -495,7 +493,7 @@ public final class Channels {
*
* @param minBufferCap
* The minimum capacity of the internal byte buffer,
* or <tt>-1</tt> if an implementation-dependent
* or {@code -1} if an implementation-dependent
* default capacity is to be used
*
* @return A new reader
@ -504,7 +502,7 @@ public final class Channels {
CharsetDecoder dec,
int minBufferCap)
{
checkNotNull(ch, "ch");
Objects.requireNonNull(ch, "ch");
return StreamDecoder.forDecoder(ch, dec.reset(), minBufferCap);
}
@ -514,16 +512,15 @@ public final class Channels {
*
* <p> An invocation of this method of the form
*
* <blockquote><pre>
* Channels.newReader(ch, csname)</pre></blockquote>
* <pre> {@code
* Channels.newReader(ch, csname)
* } </pre>
*
* behaves in exactly the same way as the expression
*
* <blockquote><pre>
* Channels.newReader(ch,
* Charset.forName(csName)
* .newDecoder(),
* -1);</pre></blockquote>
* <pre> {@code
* Channels.newReader(ch, Charset.forName(csName).newDecoder(), -1)
* } </pre>
*
* @param ch
* The channel from which bytes will be read
@ -540,7 +537,7 @@ public final class Channels {
public static Reader newReader(ReadableByteChannel ch,
String csName)
{
checkNotNull(csName, "csName");
Objects.requireNonNull(csName, "csName");
return newReader(ch, Charset.forName(csName).newDecoder(), -1);
}
@ -549,7 +546,7 @@ public final class Channels {
* writes the resulting bytes to the given channel.
*
* <p> The resulting stream will contain an internal output buffer of at
* least <tt>minBufferCap</tt> bytes. The stream's <tt>write</tt> methods
* least {@code minBufferCap} bytes. The stream's {@code write} methods
* will, as needed, flush the buffer by writing bytes to the underlying
* channel; if the channel is in non-blocking mode when bytes are to be
* written then an {@link IllegalBlockingModeException} will be thrown.
@ -564,16 +561,16 @@ public final class Channels {
*
* @param minBufferCap
* The minimum capacity of the internal byte buffer,
* or <tt>-1</tt> if an implementation-dependent
* or {@code -1} if an implementation-dependent
* default capacity is to be used
*
* @return A new writer
*/
public static Writer newWriter(final WritableByteChannel ch,
final CharsetEncoder enc,
final int minBufferCap)
public static Writer newWriter(WritableByteChannel ch,
CharsetEncoder enc,
int minBufferCap)
{
checkNotNull(ch, "ch");
Objects.requireNonNull(ch, "ch");
return StreamEncoder.forEncoder(ch, enc.reset(), minBufferCap);
}
@ -582,17 +579,15 @@ public final class Channels {
* charset and writes the resulting bytes to the given channel.
*
* <p> An invocation of this method of the form
*
* <blockquote><pre>
* Channels.newWriter(ch, csname)</pre></blockquote>
*
* <p>
* <pre> {@code
* Channels.newWriter(ch, csname)
* } </pre>
* behaves in exactly the same way as the expression
*
* <blockquote><pre>
* Channels.newWriter(ch,
* Charset.forName(csName)
* .newEncoder(),
* -1);</pre></blockquote>
* <p>
* <pre> {@code
* Channels.newWriter(ch, Charset.forName(csName).newEncoder(), -1)
* } </pre>
*
* @param ch
* The channel to which bytes will be written
@ -609,7 +604,7 @@ public final class Channels {
public static Writer newWriter(WritableByteChannel ch,
String csName)
{
checkNotNull(csName, "csName");
Objects.requireNonNull(csName, "csName");
return newWriter(ch, Charset.forName(csName).newEncoder(), -1);
}
}

View File

@ -272,7 +272,7 @@ public class ChoiceFormat extends NumberFormat {
double tryLess = Math.abs(Math.IEEEremainder(less, 1.0d));
if (tryLessOrEqual < tryLess) {
result.append(""+choiceLimits[i]);
result.append(choiceLimits[i]);
result.append('#');
} else {
if (choiceLimits[i] == Double.POSITIVE_INFINITY) {
@ -280,7 +280,7 @@ public class ChoiceFormat extends NumberFormat {
} else if (choiceLimits[i] == Double.NEGATIVE_INFINITY) {
result.append("-\u221E");
} else {
result.append(""+less);
result.append(less);
}
result.append('<');
}

View File

@ -369,10 +369,9 @@ public enum LauncherHelper {
static void appendVmErgoMessage(boolean isServerClass, String vm) {
outBuf = outBuf.append(getLocalizedMessage("java.launcher.ergo.message1",
vm));
outBuf = (isServerClass)
? outBuf.append(",\n" +
getLocalizedMessage("java.launcher.ergo.message2") + "\n\n")
: outBuf.append(".\n\n");
outBuf = (isServerClass) ? outBuf.append(",\n")
.append(getLocalizedMessage("java.launcher.ergo.message2"))
.append("\n\n") : outBuf.append(".\n\n");
}
/**

View File

@ -220,21 +220,23 @@ public class HeaderParser {
public String toString () {
Iterator<String> k = keys();
StringBuffer sbuf = new StringBuffer();
sbuf.append ("{size="+asize+" nkeys="+nkeys+" ");
StringBuilder sb = new StringBuilder();
sb.append("{size=").append(asize).append(" nkeys=").append(nkeys)
.append(' ');
for (int i=0; k.hasNext(); i++) {
String key = k.next();
String val = findValue (i);
if (val != null && "".equals (val)) {
val = null;
}
sbuf.append (" {"+key+(val==null?"":","+val)+"}");
sb.append(" {").append(key).append(val == null ? "" : "," + val)
.append('}');
if (k.hasNext()) {
sbuf.append (",");
sb.append (',');
}
}
sbuf.append (" }");
return new String (sbuf);
sb.append (" }");
return sb.toString();
}
public int findInt(String k, int Default) {

View File

@ -38,6 +38,7 @@ import java.nio.channels.NonReadableChannelException;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.OverlappingFileLockException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.WritableByteChannel;
import java.security.AccessController;
import java.util.ArrayList;
@ -404,30 +405,13 @@ public class FileChannelImpl
//
private static volatile boolean fileSupported = true;
private long transferToDirectly(long position, int icount,
WritableByteChannel target)
private long transferToDirectlyInternal(long position, int icount,
WritableByteChannel target,
FileDescriptor targetFD)
throws IOException
{
if (!transferSupported)
return IOStatus.UNSUPPORTED;
FileDescriptor targetFD = null;
if (target instanceof FileChannelImpl) {
if (!fileSupported)
return IOStatus.UNSUPPORTED_CASE;
targetFD = ((FileChannelImpl)target).fd;
} else if (target instanceof SelChImpl) {
// Direct transfer to pipe causes EINVAL on some configurations
if ((target instanceof SinkChannelImpl) && !pipeSupported)
return IOStatus.UNSUPPORTED_CASE;
targetFD = ((SelChImpl)target).getFD();
}
if (targetFD == null)
return IOStatus.UNSUPPORTED;
int thisFDVal = IOUtil.fdVal(fd);
int targetFDVal = IOUtil.fdVal(targetFD);
if (thisFDVal == targetFDVal) // Not supported on some configurations
return IOStatus.UNSUPPORTED;
assert !nd.transferToDirectlyNeedsPositionLock() ||
Thread.holdsLock(positionLock);
long n = -1;
int ti = -1;
@ -437,7 +421,7 @@ public class FileChannelImpl
if (!isOpen())
return -1;
do {
n = transferTo0(thisFDVal, position, icount, targetFDVal);
n = transferTo0(fd, position, icount, targetFD);
} while ((n == IOStatus.INTERRUPTED) && isOpen());
if (n == IOStatus.UNSUPPORTED_CASE) {
if (target instanceof SinkChannelImpl)
@ -458,6 +442,54 @@ public class FileChannelImpl
}
}
private long transferToDirectly(long position, int icount,
WritableByteChannel target)
throws IOException
{
if (!transferSupported)
return IOStatus.UNSUPPORTED;
FileDescriptor targetFD = null;
if (target instanceof FileChannelImpl) {
if (!fileSupported)
return IOStatus.UNSUPPORTED_CASE;
targetFD = ((FileChannelImpl)target).fd;
} else if (target instanceof SelChImpl) {
// Direct transfer to pipe causes EINVAL on some configurations
if ((target instanceof SinkChannelImpl) && !pipeSupported)
return IOStatus.UNSUPPORTED_CASE;
// Platform-specific restrictions. Now there is only one:
// Direct transfer to non-blocking channel could be forbidden
SelectableChannel sc = (SelectableChannel)target;
if (!nd.canTransferToDirectly(sc))
return IOStatus.UNSUPPORTED_CASE;
targetFD = ((SelChImpl)target).getFD();
}
if (targetFD == null)
return IOStatus.UNSUPPORTED;
int thisFDVal = IOUtil.fdVal(fd);
int targetFDVal = IOUtil.fdVal(targetFD);
if (thisFDVal == targetFDVal) // Not supported on some configurations
return IOStatus.UNSUPPORTED;
if (nd.transferToDirectlyNeedsPositionLock()) {
synchronized (positionLock) {
long pos = position();
try {
return transferToDirectlyInternal(position, icount,
target, targetFD);
} finally {
position(pos);
}
}
} else {
return transferToDirectlyInternal(position, icount, target, targetFD);
}
}
// Maximum size to map when using a mapped buffer
private static final long MAPPED_TRANSFER_SIZE = 8L*1024L*1024L;
@ -1173,7 +1205,8 @@ public class FileChannelImpl
private static native int unmap0(long address, long length);
// Transfers from src to dst, or returns -2 if kernel can't do that
private native long transferTo0(int src, long position, long count, int dst);
private native long transferTo0(FileDescriptor src, long position,
long count, FileDescriptor dst);
// Sets or reports this file's position
// If offset is -1, the current position is returned

View File

@ -25,7 +25,9 @@
package sun.nio.ch;
import java.io.*;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.channels.SelectableChannel;
abstract class FileDispatcher extends NativeDispatcher {
@ -53,4 +55,8 @@ abstract class FileDispatcher extends NativeDispatcher {
*/
abstract FileDescriptor duplicateForMapping(FileDescriptor fd)
throws IOException;
abstract boolean canTransferToDirectly(SelectableChannel sc);
abstract boolean transferToDirectlyNeedsPositionLock();
}

View File

@ -1478,7 +1478,7 @@ class CertificateRequest extends HandshakeMessage
boolean opened = false;
for (SignatureAndHashAlgorithm signAlg : algorithms) {
if (opened) {
sb.append(", " + signAlg.getAlgorithmName());
sb.append(", ").append(signAlg.getAlgorithmName());
} else {
sb.append(signAlg.getAlgorithmName());
opened = true;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -72,9 +72,6 @@
#define CFG_ERROR8 "Error: missing `%s' JVM at `%s'.\nPlease install or use the JRE or JDK that contains these missing components."
#define CFG_ERROR9 "Error: could not determine JVM type."
#define SPC_ERROR1 "Error: Syntax error in version specification \"%s\""
#define JRE_ERROR1 "Error: Could not find Java SE Runtime Environment."
#define JRE_ERROR2 "Error: This Java instance does not support a %d-bit JVM.\nPlease install the desired version."
#define JRE_ERROR3 "Error: Improper value at line %d."
@ -89,6 +86,9 @@
#define JRE_ERROR12 "Error: Exec of %s failed"
#define JRE_ERROR13 "Error: String processing operation failed"
#define SPC_ERROR1 "Error: Specifying an alternate JDK/JRE version is no longer supported.\n The use of the flag '-version:' is no longer valid.\n Please download and execute the appropriate version."
#define SPC_ERROR2 "Error: Specifying an alternate JDK/JRE is no longer supported.\n The related flags -jre-restrict-search | -jre-no-restrict-search are also no longer valid."
#define DLL_ERROR1 "Error: dl failure on line %d"
#define DLL_ERROR2 "Error: failed %s, because %s"
#define DLL_ERROR3 "Error: could not find executable %s"

View File

@ -216,21 +216,14 @@ JLI_Launch(int argc, char ** argv, /* main argc, argc */
}
/*
* Make sure the specified version of the JRE is running.
* SelectVersion() has several responsibilities:
*
* There are three things to note about the SelectVersion() routine:
* 1) If the version running isn't correct, this routine doesn't
* return (either the correct version has been exec'd or an error
* was issued).
* 2) Argc and Argv in this scope are *not* altered by this routine.
* It is the responsibility of subsequent code to ignore the
* arguments handled by this routine.
* 3) As a side-effect, the variable "main_class" is guaranteed to
* be set (if it should ever be set). This isn't exactly the
* poster child for structured programming, but it is a small
* price to pay for not processing a jar file operand twice.
* (Note: This side effect has been disabled. See comment on
* bugid 5030265 below.)
* 1) Disallow specification of another JRE. With 1.9, another
* version of the JRE cannot be invoked.
* 2) Allow for a JRE version to invoke JDK 1.9 or later. Since
* all mJRE directives have been stripped from the request but
* the pre 1.9 JRE [ 1.6 thru 1.8 ], it is as if 1.9+ has been
* invoked from the command line.
*/
SelectVersion(argc, argv, &main_class);
@ -829,8 +822,6 @@ static void
SelectVersion(int argc, char **argv, char **main_class)
{
char *arg;
char **new_argv;
char **new_argp;
char *operand;
char *version = NULL;
char *jre = NULL;
@ -849,6 +840,17 @@ SelectVersion(int argc, char **argv, char **main_class)
* with the value passed through the environment (if any) and
* simply return.
*/
/*
* This environmental variable can be set by mJRE capable JREs
* [ 1.5 thru 1.8 ]. All other aspects of mJRE processing have been
* stripped by those JREs. This environmental variable allows 1.9+
* JREs to be started by these mJRE capable JREs.
* Note that mJRE directives in the jar manifest file would have been
* ignored for a JRE started by another JRE...
* .. skipped for JRE 1.5 and beyond.
* .. not even checked for pre 1.5.
*/
if ((env_in = getenv(ENV_ENTRY)) != NULL) {
if (*env_in != '\0')
*main_class = JLI_StringDup(env_in);
@ -857,41 +859,26 @@ SelectVersion(int argc, char **argv, char **main_class)
/*
* Scan through the arguments for options relevant to multiple JRE
* support. For reference, the command line syntax is defined as:
* support. Multiple JRE support existed in JRE versions 1.5 thru 1.8.
*
* SYNOPSIS
* java [options] class [argument...]
*
* java [options] -jar file.jar [argument...]
*
* As the scan is performed, make a copy of the argument list with
* the version specification options (new to 1.5) removed, so that
* a version less than 1.5 can be exec'd.
*
* Note that due to the syntax of the native Windows interface
* CreateProcess(), processing similar to the following exists in
* the Windows platform specific routine ExecJRE (in java_md.c).
* Changes here should be reproduced there.
* This capability is no longer available with JRE versions 1.9 and later.
* These command line options are reported as errors.
*/
new_argv = JLI_MemAlloc((argc + 1) * sizeof(char*));
new_argv[0] = argv[0];
new_argp = &new_argv[1];
argc--;
argv++;
while ((arg = *argv) != 0 && *arg == '-') {
if (JLI_StrCCmp(arg, "-version:") == 0) {
version = arg + 9;
JLI_ReportErrorMessage(SPC_ERROR1);
} else if (JLI_StrCmp(arg, "-jre-restrict-search") == 0) {
restrict_search = 1;
} else if (JLI_StrCmp(arg, "-no-jre-restrict-search") == 0) {
restrict_search = 0;
JLI_ReportErrorMessage(SPC_ERROR2);
} else if (JLI_StrCmp(arg, "-jre-no-restrict-search") == 0) {
JLI_ReportErrorMessage(SPC_ERROR2);
} else {
if (JLI_StrCmp(arg, "-jar") == 0)
jarflag = 1;
/* deal with "unfortunate" classpath syntax */
if ((JLI_StrCmp(arg, "-classpath") == 0 || JLI_StrCmp(arg, "-cp") == 0) &&
(argc >= 2)) {
*new_argp++ = arg;
argc--;
argv++;
arg = *argv;
@ -908,7 +895,6 @@ SelectVersion(int argc, char **argv, char **main_class)
} else if (JLI_StrCCmp(arg, "-splash:") == 0) {
splash_file_name = arg+8;
}
*new_argp++ = arg;
}
argc--;
argv++;
@ -917,11 +903,8 @@ SelectVersion(int argc, char **argv, char **main_class)
operand = NULL;
} else {
argc--;
*new_argp++ = operand = *argv++;
operand = *argv++;
}
while (argc-- > 0) /* Copy over [argument...] */
*new_argp++ = *argv++;
*new_argp = NULL;
/*
* If there is a jar file, read the manifest. If the jarfile can't be
@ -974,14 +957,6 @@ SelectVersion(int argc, char **argv, char **main_class)
putenv(splash_jar_entry);
}
/*
* The JRE-Version and JRE-Restrict-Search values (if any) from the
* manifest are overwritten by any specified on the command line.
*/
if (version != NULL)
info.jre_version = version;
if (restrict_search != -1)
info.jre_restrict_search = restrict_search;
/*
* "Valid" returns (other than unrecoverable errors) follow. Set
@ -990,72 +965,11 @@ SelectVersion(int argc, char **argv, char **main_class)
if (info.main_class != NULL)
*main_class = JLI_StringDup(info.main_class);
/*
* If no version selection information is found either on the command
* line or in the manifest, simply return.
*/
if (info.jre_version == NULL) {
JLI_FreeManifest();
JLI_MemFree(new_argv);
return;
}
/*
* Check for correct syntax of the version specification (JSR 56).
*/
if (!JLI_ValidVersionString(info.jre_version)) {
JLI_ReportErrorMessage(SPC_ERROR1, info.jre_version);
exit(1);
}
/*
* Find the appropriate JVM on the system. Just to be as forgiving as
* possible, if the standard algorithms don't locate an appropriate
* jre, check to see if the one running will satisfy the requirements.
* This can happen on systems which haven't been set-up for multiple
* JRE support.
*/
jre = LocateJRE(&info);
JLI_TraceLauncher("JRE-Version = %s, JRE-Restrict-Search = %s Selected = %s\n",
(info.jre_version?info.jre_version:"null"),
(info.jre_restrict_search?"true":"false"), (jre?jre:"null"));
if (jre == NULL) {
if (JLI_AcceptableRelease(GetFullVersion(), info.jre_version)) {
JLI_FreeManifest();
JLI_MemFree(new_argv);
return;
} else {
JLI_ReportErrorMessage(CFG_ERROR4, info.jre_version);
exit(1);
}
}
/*
* If I'm not the chosen one, exec the chosen one. Returning from
* ExecJRE indicates that I am indeed the chosen one.
*
* The private environment variable _JAVA_VERSION_SET is used to
* prevent the chosen one from re-reading the manifest file and
* using the values found within to override the (potential) command
* line flags stripped from argv (because the target may not
* understand them). Passing the MainClass value is an optimization
* to avoid locating, expanding and parsing the manifest extra
* times.
*/
if (info.main_class != NULL) {
if (JLI_StrLen(info.main_class) <= MAXNAMELEN) {
(void)JLI_StrCat(env_entry, info.main_class);
} else {
JLI_ReportErrorMessage(CLS_ERROR5, MAXNAMELEN);
exit(1);
}
}
(void)putenv(env_entry);
ExecJRE(jre, new_argv);
JLI_FreeManifest();
JLI_MemFree(new_argv);
return;
}
/*
@ -1154,10 +1068,7 @@ ParseArguments(int *pargc, char ***pargv,
JLI_StrCmp(arg, "-noasyncgc") == 0) {
/* No longer supported */
JLI_ReportErrorMessage(ARG_WARN, arg);
} else if (JLI_StrCCmp(arg, "-version:") == 0 ||
JLI_StrCmp(arg, "-no-jre-restrict-search") == 0 ||
JLI_StrCmp(arg, "-jre-restrict-search") == 0 ||
JLI_StrCCmp(arg, "-splash:") == 0) {
} else if (JLI_StrCCmp(arg, "-splash:") == 0) {
; /* Ignore machine independent options already handled */
} else if (ProcessPlatformOption(arg)) {
; /* Processing of platform dependent options */

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -40,9 +40,7 @@
#include "emessages.h"
#include "java_md.h"
#include "jli_util.h"
#include "manifest_info.h"
#include "version_comp.h"
#include "wildcard.h"
#include "splashscreen.h"

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -588,15 +588,16 @@ JLI_ParseManifest(char *jarfile, manifest_info *info)
}
lp = manifest;
while ((rc = parse_nv_pair(&lp, &name, &value)) > 0) {
if (JLI_StrCaseCmp(name, "Manifest-Version") == 0)
if (JLI_StrCaseCmp(name, "Manifest-Version") == 0) {
info->manifest_version = value;
else if (JLI_StrCaseCmp(name, "Main-Class") == 0)
} else if (JLI_StrCaseCmp(name, "Main-Class") == 0) {
info->main_class = value;
else if (JLI_StrCaseCmp(name, "JRE-Version") == 0)
info->jre_version = value;
else if (JLI_StrCaseCmp(name, "JRE-Restrict-Search") == 0) {
if (JLI_StrCaseCmp(value, "true") == 0)
info->jre_restrict_search = 1;
} else if (JLI_StrCaseCmp(name, "JRE-Version") == 0) {
/*
* Manifest specification overridden by command line option
* so we will silently override there with no specification.
*/
info->jre_version = 0;
} else if (JLI_StrCaseCmp(name, "Splashscreen-Image") == 0) {
info->splashscreen_image_file_name = value;
}

View File

@ -1,357 +0,0 @@
/*
* Copyright (c) 2003, 2006, 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 <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "jni.h"
#include "jli_util.h"
#include "version_comp.h"
/*
* A collection of useful strings. One should think of these as #define
* entries, but actual strings can be more efficient (with many compilers).
*/
static const char *separators = ".-_";
static const char *zero_string = "0";
/*
* Validate a string as parsable as a "Java int". If so parsable,
* return true (non-zero) and store the numeric value at the address
* passed in as "value"; otherwise return false (zero).
*
* Note that the maximum allowable value is 2147483647 as defined by
* the "Java Language Specification" which precludes the use of native
* conversion routines which may have other limits.
*
* Also note that we don't have to worry about the alternate maximum
* allowable value of 2147483648 because it is only allowed after
* the unary negation operator and this grammar doesn't have one
* of those.
*
* Finally, note that a value which exceeds the maximum jint value will
* return false (zero). This results in the otherwise purely numeric
* string being compared as a string of characters (as per the spec.)
*/
static int
isjavaint(const char *s, jint *value)
{
jlong sum = 0;
jint digit;
while (*s != '\0')
if (isdigit(*s)) {
digit = (jint)((int)(*s++) - (int)('0'));
sum = (sum * 10) + digit;
if (sum > 2147483647)
return (0); /* Overflows jint (but not jlong) */
} else
return (0);
*value = (jint)sum;
return (1);
}
/*
* Modeled after strcmp(), compare two strings (as in the grammar defined
* in Appendix A of JSR 56). If both strings can be interpreted as
* Java ints, do a numeric comparison, else it is strcmp().
*/
static int
comp_string(const char *s1, const char *s2)
{
jint v1, v2;
if (isjavaint(s1, &v1) && isjavaint(s2, &v2))
return ((int)(v1 - v2));
else
return (JLI_StrCmp(s1, s2));
}
/*
* Modeled after strcmp(), compare two version-ids for a Prefix
* Match as defined in JSR 56.
*/
int
JLI_PrefixVersionId(const char *id1, char *id2)
{
char *s1 = JLI_StringDup(id1);
char *s2 = JLI_StringDup(id2);
char *m1 = s1;
char *m2 = s2;
char *end1 = NULL;
char *end2 = NULL;
int res = 0;
do {
if ((s1 != NULL) && ((end1 = JLI_StrPBrk(s1, ".-_")) != NULL))
*end1 = '\0';
if ((s2 != NULL) && ((end2 = JLI_StrPBrk(s2, ".-_")) != NULL))
*end2 = '\0';
res = comp_string(s1, s2);
if (end1 != NULL)
s1 = end1 + 1;
else
s1 = NULL;
if (end2 != NULL)
s2 = end2 + 1;
else
s2 = NULL;
} while (res == 0 && ((s1 != NULL) && (s2 != NULL)));
JLI_MemFree(m1);
JLI_MemFree(m2);
return (res);
}
/*
* Modeled after strcmp(), compare two version-ids for an Exact
* Match as defined in JSR 56.
*/
int
JLI_ExactVersionId(const char *id1, char *id2)
{
char *s1 = JLI_StringDup(id1);
char *s2 = JLI_StringDup(id2);
char *m1 = s1;
char *m2 = s2;
char *end1 = NULL;
char *end2 = NULL;
int res = 0;
do {
if ((s1 != NULL) && ((end1 = JLI_StrPBrk(s1, separators)) != NULL))
*end1 = '\0';
if ((s2 != NULL) && ((end2 = JLI_StrPBrk(s2, separators)) != NULL))
*end2 = '\0';
if ((s1 != NULL) && (s2 == NULL))
res = comp_string(s1, zero_string);
else if ((s1 == NULL) && (s2 != NULL))
res = comp_string(zero_string, s2);
else
res = comp_string(s1, s2);
if (end1 != NULL)
s1 = end1 + 1;
else
s1 = NULL;
if (end2 != NULL)
s2 = end2 + 1;
else
s2 = NULL;
} while (res == 0 && ((s1 != NULL) || (s2 != NULL)));
JLI_MemFree(m1);
JLI_MemFree(m2);
return (res);
}
/*
* Return true if this simple-element (as defined in JSR 56) forms
* an acceptable match.
*
* JSR 56 is modified by the Java Web Start <rel> Developer Guide
* where it is stated "... Java Web Start will not consider an installed
* non-FCS (i.e., milestone) JRE as a match. ... a JRE from Sun
* Microsystems, Inc., is by convention a non-FCS (milestone) JRE
* if there is a dash (-) in the version string."
*
* An undocumented caveat to the above is that an exact match with a
* hyphen is accepted as a development extension.
*
* These modifications are addressed by the specific comparisons
* for releases with hyphens.
*/
static int
acceptable_simple_element(const char *release, char *simple_element)
{
char *modifier;
modifier = simple_element + JLI_StrLen(simple_element) - 1;
if (*modifier == '*') {
*modifier = '\0';
if (JLI_StrChr(release, '-'))
return ((JLI_StrCmp(release, simple_element) == 0)?1:0);
return ((JLI_PrefixVersionId(release, simple_element) == 0)?1:0);
} else if (*modifier == '+') {
*modifier = '\0';
if (JLI_StrChr(release, '-'))
return ((JLI_StrCmp(release, simple_element) == 0)?1:0);
return ((JLI_ExactVersionId(release, simple_element) >= 0)?1:0);
} else {
return ((JLI_ExactVersionId(release, simple_element) == 0)?1:0);
}
}
/*
* Return true if this element (as defined in JSR 56) forms
* an acceptable match. An element is the intersection (and)
* of multiple simple-elements.
*/
static int
acceptable_element(const char *release, char *element)
{
char *end;
do {
if ((end = JLI_StrChr(element, '&')) != NULL)
*end = '\0';
if (!acceptable_simple_element(release, element))
return (0);
if (end != NULL)
element = end + 1;
} while (end != NULL);
return (1);
}
/*
* Checks if release is acceptable by the specification version-string.
* Return true if this version-string (as defined in JSR 56) forms
* an acceptable match. A version-string is the union (or) of multiple
* elements.
*/
int
JLI_AcceptableRelease(const char *release, char *version_string)
{
char *vs;
char *m1;
char *end;
m1 = vs = JLI_StringDup(version_string);
do {
if ((end = JLI_StrChr(vs, ' ')) != NULL)
*end = '\0';
if (acceptable_element(release, vs)) {
JLI_MemFree(m1);
return (1);
}
if (end != NULL)
vs = end + 1;
} while (end != NULL);
JLI_MemFree(m1);
return (0);
}
/*
* Return true if this is a valid simple-element (as defined in JSR 56).
*
* The official grammar for a simple-element is:
*
* simple-element ::= version-id | version-id modifier
* modifier ::= '+' | '*'
* version-id ::= string ( separator string )*
* string ::= char ( char )*
* char ::= Any ASCII character except a space, an
* ampersand, a separator or a modifier
* separator ::= '.' | '-' | '_'
*
* However, for efficiency, it is time to abandon the top down parser
* implementation. After deleting the potential trailing modifier, we
* are left with a version-id.
*
* Note that a valid version-id has three simple properties:
*
* 1) Doesn't contain a space, an ampersand or a modifier.
*
* 2) Doesn't begin or end with a separator.
*
* 3) Doesn't contain two adjacent separators.
*
* Any other line noise constitutes a valid version-id.
*/
static int
valid_simple_element(char *simple_element)
{
char *last;
size_t len;
if ((simple_element == NULL) || ((len = JLI_StrLen(simple_element)) == 0))
return (0);
last = simple_element + len - 1;
if (*last == '*' || *last == '+') {
if (--len == 0)
return (0);
*last-- = '\0';
}
if (JLI_StrPBrk(simple_element, " &+*") != NULL) /* Property #1 */
return (0);
if ((JLI_StrChr(".-_", *simple_element) != NULL) || /* Property #2 */
(JLI_StrChr(".-_", *last) != NULL))
return (0);
for (; simple_element != last; simple_element++) /* Property #3 */
if ((JLI_StrChr(".-_", *simple_element) != NULL) &&
(JLI_StrChr(".-_", *(simple_element + 1)) != NULL))
return (0);
return (1);
}
/*
* Return true if this is a valid element (as defined in JSR 56).
* An element is the intersection (and) of multiple simple-elements.
*/
static int
valid_element(char *element)
{
char *end;
if ((element == NULL) || (JLI_StrLen(element) == 0))
return (0);
do {
if ((end = JLI_StrChr(element, '&')) != NULL)
*end = '\0';
if (!valid_simple_element(element))
return (0);
if (end != NULL)
element = end + 1;
} while (end != NULL);
return (1);
}
/*
* Validates a version string by the extended JSR 56 grammar.
*/
int
JLI_ValidVersionString(char *version_string)
{
char *vs;
char *m1;
char *end;
if ((version_string == NULL) || (JLI_StrLen(version_string) == 0))
return (0);
m1 = vs = JLI_StringDup(version_string);
do {
if ((end = JLI_StrChr(vs, ' ')) != NULL)
*end = '\0';
if (!valid_element(vs)) {
JLI_MemFree(m1);
return (0);
}
if (end != NULL)
vs = end + 1;
} while (end != NULL);
JLI_MemFree(m1);
return (1);
}

View File

@ -1,37 +0,0 @@
/*
* Copyright (c) 2003, 2005, 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.
*/
#ifndef _VERSION_COMP_H
#define _VERSION_COMP_H
/*
* Function prototypes.
*/
int JLI_ExactVersionId(const char *id1, char *id2);
int JLI_PrefixVersionId(const char *id1, char *id2);
int JLI_AcceptableRelease(const char *release, char *version_string);
int JLI_ValidVersionString(char *version_string);
#endif /* _VERSION_COMP_H */

View File

@ -25,10 +25,10 @@
package sun.nio.ch;
import java.io.*;
import java.io.FileDescriptor;
import java.io.IOException;
class FileDispatcherImpl extends FileDispatcher
{
class FileDispatcherImpl extends FileDispatcher {
static {
IOUtil.load();
@ -104,6 +104,14 @@ class FileDispatcherImpl extends FileDispatcher
return new FileDescriptor();
}
boolean canTransferToDirectly(java.nio.channels.SelectableChannel sc) {
return true;
}
boolean transferToDirectlyNeedsPositionLock() {
return false;
}
// -- Native methods --
static native int read0(FileDescriptor fd, long address, int len)

View File

@ -270,6 +270,22 @@ class UnixChannelFactory {
throw x;
}
// fail if the file is a directory
if (flags.read) {
UnixException exc = null;
try {
if (UnixFileAttributes.get(fd).isDirectory()) {
exc = new UnixException(EISDIR);
}
} catch (UnixException x) {
exc = x;
}
if (exc != null) {
close(fd);
throw exc;
}
}
// unlink file immediately if delete on close. The spec is clear that
// an implementation cannot guarantee to unlink the correct file when
// replaced by an attacker after it is opened.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -43,11 +43,6 @@
#define MAXNAMELEN PATH_MAX
#endif
/*
* Common function prototypes and sundries.
*/
char *LocateJRE(manifest_info *info);
void ExecJRE(char *jre, char **argv);
int UnsetEnv(char *name);
char *FindExecName(char *program);
const char *SetExecname(char **argv);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 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
@ -190,200 +190,6 @@ CheckSanity(char *path, char *dir)
return ((access(buffer, X_OK) == 0) ? 1 : 0);
}
/*
* Determine if there is an acceptable JRE in the directory dirname.
* Upon locating the "best" one, return a fully qualified path to
* it. "Best" is defined as the most advanced JRE meeting the
* constraints contained in the manifest_info. If no JRE in this
* directory meets the constraints, return NULL.
*
* Note that we don't check for errors in reading the directory
* (which would be done by checking errno). This is because it
* doesn't matter if we get an error reading the directory, or
* we just don't find anything interesting in the directory. We
* just return NULL in either case.
*
* The historical names of j2sdk and j2re were changed to jdk and
* jre respecively as part of the 1.5 rebranding effort. Since the
* former names are legacy on Linux, they must be recognized for
* all time. Fortunately, this is a minor cost.
*/
static char
*ProcessDir(manifest_info *info, char *dirname)
{
DIR *dirp;
struct dirent *dp;
char *best = NULL;
int offset;
int best_offset = 0;
char *ret_str = NULL;
char buffer[PATH_MAX];
if ((dirp = opendir(dirname)) == NULL)
return (NULL);
do {
if ((dp = readdir(dirp)) != NULL) {
offset = 0;
if ((JLI_StrNCmp(dp->d_name, "jre", 3) == 0) ||
(JLI_StrNCmp(dp->d_name, "jdk", 3) == 0))
offset = 3;
else if (JLI_StrNCmp(dp->d_name, "j2re", 4) == 0)
offset = 4;
else if (JLI_StrNCmp(dp->d_name, "j2sdk", 5) == 0)
offset = 5;
if (offset > 0) {
if ((JLI_AcceptableRelease(dp->d_name + offset,
info->jre_version)) && CheckSanity(dirname, dp->d_name))
if ((best == NULL) || (JLI_ExactVersionId(
dp->d_name + offset, best + best_offset) > 0)) {
if (best != NULL)
JLI_MemFree(best);
best = JLI_StringDup(dp->d_name);
best_offset = offset;
}
}
}
} while (dp != NULL);
(void) closedir(dirp);
if (best == NULL)
return (NULL);
else {
ret_str = JLI_MemAlloc(JLI_StrLen(dirname) + JLI_StrLen(best) + 2);
sprintf(ret_str, "%s/%s", dirname, best);
JLI_MemFree(best);
return (ret_str);
}
}
/*
* This is the global entry point. It examines the host for the optimal
* JRE to be used by scanning a set of directories. The set of directories
* is platform dependent and can be overridden by the environment
* variable JAVA_VERSION_PATH.
*
* This routine itself simply determines the set of appropriate
* directories before passing control onto ProcessDir().
*/
char*
LocateJRE(manifest_info* info)
{
char *path;
char *home;
char *target = NULL;
char *dp;
char *cp;
/*
* Start by getting JAVA_VERSION_PATH
*/
if (info->jre_restrict_search) {
path = JLI_StringDup(system_dir);
} else if ((path = getenv("JAVA_VERSION_PATH")) != NULL) {
path = JLI_StringDup(path);
} else {
if ((home = getenv("HOME")) != NULL) {
path = (char *)JLI_MemAlloc(JLI_StrLen(home) + \
JLI_StrLen(system_dir) + JLI_StrLen(user_dir) + 2);
sprintf(path, "%s%s:%s", home, user_dir, system_dir);
} else {
path = JLI_StringDup(system_dir);
}
}
/*
* Step through each directory on the path. Terminate the scan with
* the first directory with an acceptable JRE.
*/
cp = dp = path;
while (dp != NULL) {
cp = JLI_StrChr(dp, (int)':');
if (cp != NULL)
*cp = '\0';
if ((target = ProcessDir(info, dp)) != NULL)
break;
dp = cp;
if (dp != NULL)
dp++;
}
JLI_MemFree(path);
return (target);
}
/*
* Given a path to a jre to execute, this routine checks if this process
* is indeed that jre. If not, it exec's that jre.
*
* We want to actually check the paths rather than just the version string
* built into the executable, so that given version specification (and
* JAVA_VERSION_PATH) will yield the exact same Java environment, regardless
* of the version of the arbitrary launcher we start with.
*/
void
ExecJRE(char *jre, char **argv)
{
char wanted[PATH_MAX];
const char* progname = GetProgramName();
const char* execname = NULL;
/*
* Resolve the real path to the directory containing the selected JRE.
*/
if (realpath(jre, wanted) == NULL) {
JLI_ReportErrorMessage(JRE_ERROR9, jre);
exit(1);
}
/*
* Resolve the real path to the currently running launcher.
*/
SetExecname(argv);
execname = GetExecName();
if (execname == NULL) {
JLI_ReportErrorMessage(JRE_ERROR10);
exit(1);
}
/*
* If the path to the selected JRE directory is a match to the initial
* portion of the path to the currently executing JRE, we have a winner!
* If so, just return.
*/
if (JLI_StrNCmp(wanted, execname, JLI_StrLen(wanted)) == 0)
return; /* I am the droid you were looking for */
/*
* This should never happen (because of the selection code in SelectJRE),
* but check for "impossibly" long path names just because buffer overruns
* can be so deadly.
*/
if (JLI_StrLen(wanted) + JLI_StrLen(progname) + 6 > PATH_MAX) {
JLI_ReportErrorMessage(JRE_ERROR11);
exit(1);
}
/*
* Construct the path and exec it.
*/
(void)JLI_StrCat(JLI_StrCat(wanted, "/bin/"), progname);
argv[0] = JLI_StringDup(progname);
if (JLI_IsTraceLauncher()) {
int i;
printf("ReExec Command: %s (%s)\n", wanted, argv[0]);
printf("ReExec Args:");
for (i = 1; argv[i] != NULL; i++)
printf(" %s", argv[i]);
printf("\n");
}
JLI_TraceLauncher("TRACER_MARKER:About to EXEC\n");
(void)fflush(stdout);
(void)fflush(stderr);
execv(wanted, argv);
JLI_ReportErrorMessageSys(JRE_ERROR12, wanted);
exit(1);
}
/*
* "Borrowed" from Solaris 10 where the unsetenv() function is being added
* to libc thanks to SUSv3 (Standard Unix Specification, version 3). As

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -36,7 +36,6 @@
#include <unistd.h>
#include <sys/types.h>
#include "manifest_info.h"
#include "version_comp.h"
#define JVM_DLL "libjvm.so"
@ -100,10 +99,6 @@
* (incoming argv)
* |
* \|/
* SelectVersion
* (selects the JRE version, note: not data model)
* |
* \|/
* CreateExecutionEnvironment
* (determines desired data model)
* |

View File

@ -154,10 +154,13 @@ Java_sun_nio_ch_FileChannelImpl_close0(JNIEnv *env, jobject this, jobject fdo)
JNIEXPORT jlong JNICALL
Java_sun_nio_ch_FileChannelImpl_transferTo0(JNIEnv *env, jobject this,
jint srcFD,
jobject srcFDO,
jlong position, jlong count,
jint dstFD)
jobject dstFDO)
{
jint srcFD = fdval(env, srcFDO);
jint dstFD = fdval(env, dstFDO);
#if defined(__linux__)
off64_t offset = (off64_t)position;
jlong n = sendfile64(dstFD, srcFD, &offset, (size_t)count);

View File

@ -25,21 +25,21 @@
package sun.nio.ch;
import java.io.*;
import java.io.FileDescriptor;
import java.io.IOException;
import java.security.PrivilegedAction;
import sun.misc.SharedSecrets;
import sun.misc.JavaIOFileDescriptorAccess;
class FileDispatcherImpl extends FileDispatcher
{
class FileDispatcherImpl extends FileDispatcher {
private static final JavaIOFileDescriptorAccess fdAccess =
SharedSecrets.getJavaIOFileDescriptorAccess();
static {
IOUtil.load();
}
// set to true if fast file transmission (TransmitFile) is enabled
private static final boolean fastFileTransfer;
FileDispatcherImpl() {
}
FileDispatcherImpl() { }
@Override
boolean needsPositionLock() {
@ -110,6 +110,36 @@ class FileDispatcherImpl extends FileDispatcher
return result;
}
boolean canTransferToDirectly(java.nio.channels.SelectableChannel sc) {
return fastFileTransfer && sc.isBlocking();
}
boolean transferToDirectlyNeedsPositionLock() {
return true;
}
static boolean isFastFileTransferRequested() {
String fileTransferProp = java.security.AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("jdk.net.enableFastFileTransfer");
}
});
boolean enable;
if ("".equals(fileTransferProp)) {
enable = true;
} else {
enable = Boolean.parseBoolean(fileTransferProp);
}
return enable;
}
static {
IOUtil.load();
fastFileTransfer = isFastFileTransferRequested();
}
//-- Native methods
static native int read0(FileDescriptor fd, long address, int len)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -37,7 +37,6 @@
#include <jni.h>
#include "java.h"
#include "version_comp.h"
#define JVM_DLL "jvm.dll"
#define JAVA_DLL "java.dll"
@ -674,420 +673,6 @@ ServerClassMachine() {
return (GetErgoPolicy() == ALWAYS_SERVER_CLASS) ? JNI_TRUE : JNI_FALSE;
}
/*
* Determine if there is an acceptable JRE in the registry directory top_key.
* Upon locating the "best" one, return a fully qualified path to it.
* "Best" is defined as the most advanced JRE meeting the constraints
* contained in the manifest_info. If no JRE in this directory meets the
* constraints, return NULL.
*
* It doesn't matter if we get an error reading the registry, or we just
* don't find anything interesting in the directory. We just return NULL
* in either case.
*/
static char *
ProcessDir(manifest_info* info, HKEY top_key) {
DWORD index = 0;
HKEY ver_key;
char name[MAXNAMELEN];
int len;
char *best = NULL;
/*
* Enumerate "<top_key>/SOFTWARE/JavaSoft/Java Runtime Environment"
* searching for the best available version.
*/
while (RegEnumKey(top_key, index, name, MAXNAMELEN) == ERROR_SUCCESS) {
index++;
if (JLI_AcceptableRelease(name, info->jre_version))
if ((best == NULL) || (JLI_ExactVersionId(name, best) > 0)) {
if (best != NULL)
JLI_MemFree(best);
best = JLI_StringDup(name);
}
}
/*
* Extract "JavaHome" from the "best" registry directory and return
* that path. If no appropriate version was located, or there is an
* error in extracting the "JavaHome" string, return null.
*/
if (best == NULL)
return (NULL);
else {
if (RegOpenKeyEx(top_key, best, 0, KEY_READ, &ver_key)
!= ERROR_SUCCESS) {
JLI_MemFree(best);
if (ver_key != NULL)
RegCloseKey(ver_key);
return (NULL);
}
JLI_MemFree(best);
len = MAXNAMELEN;
if (RegQueryValueEx(ver_key, "JavaHome", NULL, NULL, (LPBYTE)name, &len)
!= ERROR_SUCCESS) {
if (ver_key != NULL)
RegCloseKey(ver_key);
return (NULL);
}
if (ver_key != NULL)
RegCloseKey(ver_key);
return (JLI_StringDup(name));
}
}
/*
* This is the global entry point. It examines the host for the optimal
* JRE to be used by scanning a set of registry entries. This set of entries
* is hardwired on Windows as "Software\JavaSoft\Java Runtime Environment"
* under the set of roots "{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }".
*
* This routine simply opens each of these registry directories before passing
* control onto ProcessDir().
*/
char *
LocateJRE(manifest_info* info) {
HKEY key = NULL;
char *path;
int key_index;
HKEY root_keys[2] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE };
for (key_index = 0; key_index <= 1; key_index++) {
if (RegOpenKeyEx(root_keys[key_index], JRE_KEY, 0, KEY_READ, &key)
== ERROR_SUCCESS)
if ((path = ProcessDir(info, key)) != NULL) {
if (key != NULL)
RegCloseKey(key);
return (path);
}
if (key != NULL)
RegCloseKey(key);
}
return NULL;
}
/*
* Local helper routine to isolate a single token (option or argument)
* from the command line.
*
* This routine accepts a pointer to a character pointer. The first
* token (as defined by MSDN command-line argument syntax) is isolated
* from that string.
*
* Upon return, the input character pointer pointed to by the parameter s
* is updated to point to the remainding, unscanned, portion of the string,
* or to a null character if the entire string has been consummed.
*
* This function returns a pointer to a null-terminated string which
* contains the isolated first token, or to the null character if no
* token could be isolated.
*
* Note the side effect of modifying the input string s by the insertion
* of a null character, making it two strings.
*
* See "Parsing C Command-Line Arguments" in the MSDN Library for the
* parsing rule details. The rule summary from that specification is:
*
* * Arguments are delimited by white space, which is either a space or a tab.
*
* * A string surrounded by double quotation marks is interpreted as a single
* argument, regardless of white space contained within. A quoted string can
* be embedded in an argument. Note that the caret (^) is not recognized as
* an escape character or delimiter.
*
* * A double quotation mark preceded by a backslash, \", is interpreted as a
* literal double quotation mark (").
*
* * Backslashes are interpreted literally, unless they immediately precede a
* double quotation mark.
*
* * If an even number of backslashes is followed by a double quotation mark,
* then one backslash (\) is placed in the argv array for every pair of
* backslashes (\\), and the double quotation mark (") is interpreted as a
* string delimiter.
*
* * If an odd number of backslashes is followed by a double quotation mark,
* then one backslash (\) is placed in the argv array for every pair of
* backslashes (\\) and the double quotation mark is interpreted as an
* escape sequence by the remaining backslash, causing a literal double
* quotation mark (") to be placed in argv.
*/
static char*
nextarg(char** s) {
char *p = *s;
char *head;
int slashes = 0;
int inquote = 0;
/*
* Strip leading whitespace, which MSDN defines as only space or tab.
* (Hence, no locale specific "isspace" here.)
*/
while (*p != (char)0 && (*p == ' ' || *p == '\t'))
p++;
head = p; /* Save the start of the token to return */
/*
* Isolate a token from the command line.
*/
while (*p != (char)0 && (inquote || !(*p == ' ' || *p == '\t'))) {
if (*p == '\\' && *(p+1) == '"' && slashes % 2 == 0)
p++;
else if (*p == '"')
inquote = !inquote;
slashes = (*p++ == '\\') ? slashes + 1 : 0;
}
/*
* If the token isolated isn't already terminated in a "char zero",
* then replace the whitespace character with one and move to the
* next character.
*/
if (*p != (char)0)
*p++ = (char)0;
/*
* Update the parameter to point to the head of the remaining string
* reflecting the command line and return a pointer to the leading
* token which was isolated from the command line.
*/
*s = p;
return (head);
}
/*
* Local helper routine to return a string equivalent to the input string
* s, but with quotes removed so the result is a string as would be found
* in argv[]. The returned string should be freed by a call to JLI_MemFree().
*
* The rules for quoting (and escaped quotes) are:
*
* 1 A double quotation mark preceded by a backslash, \", is interpreted as a
* literal double quotation mark (").
*
* 2 Backslashes are interpreted literally, unless they immediately precede a
* double quotation mark.
*
* 3 If an even number of backslashes is followed by a double quotation mark,
* then one backslash (\) is placed in the argv array for every pair of
* backslashes (\\), and the double quotation mark (") is interpreted as a
* string delimiter.
*
* 4 If an odd number of backslashes is followed by a double quotation mark,
* then one backslash (\) is placed in the argv array for every pair of
* backslashes (\\) and the double quotation mark is interpreted as an
* escape sequence by the remaining backslash, causing a literal double
* quotation mark (") to be placed in argv.
*/
static char*
unquote(const char *s) {
const char *p = s; /* Pointer to the tail of the original string */
char *un = (char*)JLI_MemAlloc(JLI_StrLen(s) + 1); /* Ptr to unquoted string */
char *pun = un; /* Pointer to the tail of the unquoted string */
while (*p != '\0') {
if (*p == '"') {
p++;
} else if (*p == '\\') {
const char *q = p + JLI_StrSpn(p,"\\");
if (*q == '"')
do {
*pun++ = '\\';
p += 2;
} while (*p == '\\' && p < q);
else
while (p < q)
*pun++ = *p++;
} else {
*pun++ = *p++;
}
}
*pun = '\0';
return un;
}
/*
* Given a path to a jre to execute, this routine checks if this process
* is indeed that jre. If not, it exec's that jre.
*
* We want to actually check the paths rather than just the version string
* built into the executable, so that given version specification will yield
* the exact same Java environment, regardless of the version of the arbitrary
* launcher we start with.
*/
void
ExecJRE(char *jre, char **argv) {
jint len;
char path[MAXPATHLEN + 1];
const char *progname = GetProgramName();
/*
* Resolve the real path to the currently running launcher.
*/
len = GetModuleFileName(NULL, path, MAXPATHLEN + 1);
if (len == 0 || len > MAXPATHLEN) {
JLI_ReportErrorMessageSys(JRE_ERROR9, progname);
exit(1);
}
JLI_TraceLauncher("ExecJRE: old: %s\n", path);
JLI_TraceLauncher("ExecJRE: new: %s\n", jre);
/*
* If the path to the selected JRE directory is a match to the initial
* portion of the path to the currently executing JRE, we have a winner!
* If so, just return.
*/
if (JLI_StrNCaseCmp(jre, path, JLI_StrLen(jre)) == 0)
return; /* I am the droid you were looking for */
/*
* If this isn't the selected version, exec the selected version.
*/
JLI_Snprintf(path, sizeof(path), "%s\\bin\\%s.exe", jre, progname);
/*
* Although Windows has an execv() entrypoint, it doesn't actually
* overlay a process: it can only create a new process and terminate
* the old process. Therefore, any processes waiting on the initial
* process wake up and they shouldn't. Hence, a chain of pseudo-zombie
* processes must be retained to maintain the proper wait semantics.
* Fortunately the image size of the launcher isn't too large at this
* time.
*
* If it weren't for this semantic flaw, the code below would be ...
*
* execv(path, argv);
* JLI_ReportErrorMessage("Error: Exec of %s failed\n", path);
* exit(1);
*
* The incorrect exec semantics could be addressed by:
*
* exit((int)spawnv(_P_WAIT, path, argv));
*
* Unfortunately, a bug in Windows spawn/exec impementation prevents
* this from completely working. All the Windows POSIX process creation
* interfaces are implemented as wrappers around the native Windows
* function CreateProcess(). CreateProcess() takes a single string
* to specify command line options and arguments, so the POSIX routine
* wrappers build a single string from the argv[] array and in the
* process, any quoting information is lost.
*
* The solution to this to get the original command line, to process it
* to remove the new multiple JRE options (if any) as was done for argv
* in the common SelectVersion() routine and finally to pass it directly
* to the native CreateProcess() Windows process control interface.
*/
{
char *cmdline;
char *p;
char *np;
char *ocl;
char *ccl;
char *unquoted;
DWORD exitCode;
STARTUPINFO si;
PROCESS_INFORMATION pi;
/*
* The following code block gets and processes the original command
* line, replacing the argv[0] equivalent in the command line with
* the path to the new executable and removing the appropriate
* Multiple JRE support options. Note that similar logic exists
* in the platform independent SelectVersion routine, but is
* replicated here due to the syntax of CreateProcess().
*
* The magic "+ 4" characters added to the command line length are
* 2 possible quotes around the path (argv[0]), a space after the
* path and a terminating null character.
*/
ocl = GetCommandLine();
np = ccl = JLI_StringDup(ocl);
p = nextarg(&np); /* Discard argv[0] */
cmdline = (char *)JLI_MemAlloc(JLI_StrLen(path) + JLI_StrLen(np) + 4);
if (JLI_StrChr(path, (int)' ') == NULL && JLI_StrChr(path, (int)'\t') == NULL)
cmdline = JLI_StrCpy(cmdline, path);
else
cmdline = JLI_StrCat(JLI_StrCat(JLI_StrCpy(cmdline, "\""), path), "\"");
while (*np != (char)0) { /* While more command-line */
p = nextarg(&np);
if (*p != (char)0) { /* If a token was isolated */
unquoted = unquote(p);
if (*unquoted == '-') { /* Looks like an option */
if (JLI_StrCmp(unquoted, "-classpath") == 0 ||
JLI_StrCmp(unquoted, "-cp") == 0) { /* Unique cp syntax */
cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
p = nextarg(&np);
if (*p != (char)0) /* If a token was isolated */
cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
} else if (JLI_StrNCmp(unquoted, "-version:", 9) != 0 &&
JLI_StrCmp(unquoted, "-jre-restrict-search") != 0 &&
JLI_StrCmp(unquoted, "-no-jre-restrict-search") != 0) {
cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
}
} else { /* End of options */
cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), p);
cmdline = JLI_StrCat(JLI_StrCat(cmdline, " "), np);
JLI_MemFree((void *)unquoted);
break;
}
JLI_MemFree((void *)unquoted);
}
}
JLI_MemFree((void *)ccl);
if (JLI_IsTraceLauncher()) {
np = ccl = JLI_StringDup(cmdline);
p = nextarg(&np);
printf("ReExec Command: %s (%s)\n", path, p);
printf("ReExec Args: %s\n", np);
JLI_MemFree((void *)ccl);
}
(void)fflush(stdout);
(void)fflush(stderr);
/*
* The following code is modeled after a model presented in the
* Microsoft Technical Article "Moving Unix Applications to
* Windows NT" (March 6, 1994) and "Creating Processes" on MSDN
* (Februrary 2005). It approximates UNIX spawn semantics with
* the parent waiting for termination of the child.
*/
memset(&si, 0, sizeof(si));
si.cb =sizeof(STARTUPINFO);
memset(&pi, 0, sizeof(pi));
if (!CreateProcess((LPCTSTR)path, /* executable name */
(LPTSTR)cmdline, /* command line */
(LPSECURITY_ATTRIBUTES)NULL, /* process security attr. */
(LPSECURITY_ATTRIBUTES)NULL, /* thread security attr. */
(BOOL)TRUE, /* inherits system handles */
(DWORD)0, /* creation flags */
(LPVOID)NULL, /* environment block */
(LPCTSTR)NULL, /* current directory */
(LPSTARTUPINFO)&si, /* (in) startup information */
(LPPROCESS_INFORMATION)&pi)) { /* (out) process information */
JLI_ReportErrorMessageSys(SYS_ERROR1, path);
exit(1);
}
if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
exitCode = 1;
} else {
JLI_ReportErrorMessage(SYS_ERROR2);
exitCode = 1;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
exit(exitCode);
}
}
/*
* Wrapper for platform dependent unsetenv function.
*/

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -50,8 +50,7 @@ extern jlong Counter2Micros(jlong counts);
/*
* Function prototypes.
*/
char *LocateJRE(manifest_info *info);
void ExecJRE(char *jre, char **argv);
int UnsetEnv(char *name);
#endif /* JAVA_MD_H */

View File

@ -31,6 +31,10 @@
#include "nio.h"
#include "nio_util.h"
#include "sun_nio_ch_FileChannelImpl.h"
#include "java_lang_Integer.h"
#include <Mswsock.h>
#pragma comment(lib, "Mswsock.lib")
static jfieldID chan_fd; /* id for jobject 'fd' in java.io.FileChannel */
@ -175,9 +179,42 @@ Java_sun_nio_ch_FileChannelImpl_close0(JNIEnv *env, jobject this, jobject fdo)
JNIEXPORT jlong JNICALL
Java_sun_nio_ch_FileChannelImpl_transferTo0(JNIEnv *env, jobject this,
jint srcFD,
jobject srcFD,
jlong position, jlong count,
jint dstFD)
jobject dstFD)
{
return IOS_UNSUPPORTED;
const int PACKET_SIZE = 524288;
HANDLE src = (HANDLE)(handleval(env, srcFD));
SOCKET dst = (SOCKET)(fdval(env, dstFD));
DWORD chunkSize = (count > java_lang_Integer_MAX_VALUE) ?
java_lang_Integer_MAX_VALUE : (DWORD)count;
BOOL result = 0;
jlong pos = Java_sun_nio_ch_FileChannelImpl_position0(env, this, srcFD, position);
if (pos == IOS_THROWN) {
return IOS_THROWN;
}
result = TransmitFile(
dst,
src,
chunkSize,
PACKET_SIZE,
NULL,
NULL,
TF_USE_KERNEL_APC
);
if (!result) {
int error = WSAGetLastError();
if (WSAEINVAL == error && count >= 0) {
return IOS_UNSUPPORTED_CASE;
}
if (WSAENOTSOCK == error) {
return IOS_UNSUPPORTED_CASE;
}
JNU_ThrowIOExceptionWithLastError(env, "transfer failed");
return IOS_THROWN;
}
return chunkSize;
}

View File

@ -256,7 +256,7 @@ final public class CNNameParser implements NameParser {
private static String stringifyComponent(NameComponent comp) {
StringBuilder one = new StringBuilder(escape(comp.id));
if (comp.kind != null && !comp.kind.equals("")) {
one.append(kindSeparator + escape(comp.kind));
one.append(kindSeparator).append(escape(comp.kind));
}
if (one.length() == 0) {
return ""+kindSeparator; // if neither id nor kind specified

View File

@ -458,11 +458,11 @@ public class LogManager {
JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
if (sm != null && javaAwtAccess != null) {
// for each applet, it has its own LoggerContext isolated from others
synchronized (javaAwtAccess) {
// find the AppContext of the applet code
// will be null if we are in the main app context.
final Object ecx = javaAwtAccess.getAppletContext();
if (ecx != null) {
final Object ecx = javaAwtAccess.getAppletContext();
if (ecx != null) {
synchronized (javaAwtAccess) {
// find the AppContext of the applet code
// will be null if we are in the main app context.
if (contextsMap == null) {
contextsMap = new WeakHashMap<>();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 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
@ -1707,16 +1707,19 @@ public class DefaultMBeanServerInterceptor implements MBeanServerInterceptor {
throw new UnsupportedOperationException("Not supported yet.");
}
@SuppressWarnings("deprecation")
public ObjectInputStream deserialize(ObjectName name, byte[] data) throws InstanceNotFoundException,
OperationsException {
throw new UnsupportedOperationException("Not supported yet.");
}
@SuppressWarnings("deprecation")
public ObjectInputStream deserialize(String className, byte[] data) throws OperationsException,
ReflectionException {
throw new UnsupportedOperationException("Not supported yet.");
}
@SuppressWarnings("deprecation")
public ObjectInputStream deserialize(String className, ObjectName loaderName,
byte[] data) throws InstanceNotFoundException, OperationsException,
ReflectionException {

View File

@ -455,11 +455,11 @@ public class MBeanPermission extends Permission {
name.append(className);
if (member == null)
member = "-";
name.append("#" + member);
name.append('#').append(member);
if (objectName == null)
name.append("[-]");
else
name.append("[").append(objectName.getCanonicalName()).append("]");
name.append('[').append(objectName.getCanonicalName()).append(']');
/* In the interests of legibility for Permission.toString(), we
transform the empty string into "*". */

View File

@ -716,15 +716,14 @@ public class RequiredModelMBean
}
retStr.append("\nMBeanInfo for ModelMBean is:");
retStr.append("\nCLASSNAME: \t"+ info.getClassName());
retStr.append("\nDESCRIPTION: \t"+ info.getDescription());
retStr.append("\nCLASSNAME: \t").append(info.getClassName());
retStr.append("\nDESCRIPTION: \t").append(info.getDescription());
try {
retStr.append("\nMBEAN DESCRIPTOR: \t"+
info.getMBeanDescriptor());
retStr.append("\nMBEAN DESCRIPTOR: \t").append(info.getMBeanDescriptor());
} catch (Exception e) {
retStr.append("\nMBEAN DESCRIPTOR: \t" + " is invalid");
retStr.append("\nMBEAN DESCRIPTOR: \t is invalid");
}
retStr.append("\nATTRIBUTES");
@ -734,13 +733,12 @@ public class RequiredModelMBean
for (int i=0; i<attrInfo.length; i++) {
final ModelMBeanAttributeInfo attInfo =
(ModelMBeanAttributeInfo)attrInfo[i];
retStr.append(" ** NAME: \t"+ attInfo.getName());
retStr.append(" DESCR: \t"+ attInfo.getDescription());
retStr.append(" TYPE: \t"+ attInfo.getType() +
" READ: \t"+ attInfo.isReadable() +
" WRITE: \t"+ attInfo.isWritable());
retStr.append(" DESCRIPTOR: " +
attInfo.getDescriptor().toString());
retStr.append(" ** NAME: \t").append(attInfo.getName());
retStr.append(" DESCR: \t").append(attInfo.getDescription());
retStr.append(" TYPE: \t").append(attInfo.getType())
.append(" READ: \t").append(attInfo.isReadable())
.append(" WRITE: \t").append(attInfo.isWritable());
retStr.append(" DESCRIPTOR: ").append(attInfo.getDescriptor());
}
} else {
retStr.append(" ** No attributes **");
@ -752,14 +750,13 @@ public class RequiredModelMBean
for (int i=0; i<constrInfo.length; i++) {
final ModelMBeanConstructorInfo ctorInfo =
(ModelMBeanConstructorInfo)constrInfo[i];
retStr.append(" ** NAME: \t"+ ctorInfo.getName());
retStr.append(" DESCR: \t"+
ctorInfo.getDescription());
retStr.append(" PARAM: \t"+
ctorInfo.getSignature().length +
" parameter(s)");
retStr.append(" DESCRIPTOR: " +
ctorInfo.getDescriptor().toString());
retStr.append(" ** NAME: \t").append(ctorInfo.getName());
retStr.append(" DESCR: \t").append(ctorInfo.getDescription());
retStr.append(" PARAM: \t")
.append(ctorInfo.getSignature().length)
.append(" parameter(s)");
retStr.append(" DESCRIPTOR: ").append(
ctorInfo.getDescriptor());
}
} else {
retStr.append(" ** No Constructors **");
@ -771,13 +768,12 @@ public class RequiredModelMBean
for (int i=0; i<opsInfo.length; i++) {
final ModelMBeanOperationInfo operInfo =
(ModelMBeanOperationInfo)opsInfo[i];
retStr.append(" ** NAME: \t"+ operInfo.getName());
retStr.append(" DESCR: \t"+ operInfo.getDescription());
retStr.append(" PARAM: \t"+
operInfo.getSignature().length +
" parameter(s)");
retStr.append(" DESCRIPTOR: " +
operInfo.getDescriptor().toString());
retStr.append(" ** NAME: \t").append(operInfo.getName());
retStr.append(" DESCR: \t").append(operInfo.getDescription());
retStr.append(" PARAM: \t")
.append(operInfo.getSignature().length)
.append(" parameter(s)");
retStr.append(" DESCRIPTOR: ").append(operInfo.getDescriptor());
}
} else {
retStr.append(" ** No operations ** ");
@ -790,10 +786,9 @@ public class RequiredModelMBean
for (int i=0; i<notifInfo.length; i++) {
final ModelMBeanNotificationInfo nInfo =
(ModelMBeanNotificationInfo)notifInfo[i];
retStr.append(" ** NAME: \t"+ nInfo.getName());
retStr.append(" DESCR: \t"+ nInfo.getDescription());
retStr.append(" DESCRIPTOR: " +
nInfo.getDescriptor().toString());
retStr.append(" ** NAME: \t").append(nInfo.getName());
retStr.append(" DESCR: \t").append(nInfo.getDescription());
retStr.append(" DESCRIPTOR: ").append(nInfo.getDescriptor());
}
} else {
retStr.append(" ** No notifications **");

View File

@ -458,8 +458,8 @@ public class ArrayType<T> extends OpenType<T> {
elementType = at.getElementOpenType();
isPrimitiveArray = at.isPrimitiveArray();
}
StringBuilder result =
new StringBuilder(dimension + "-dimension array of ");
StringBuilder result = new StringBuilder();
result.append(dimension).append("-dimension array of ");
final String elementClassName = elementType.getClassName();
if (isPrimitiveArray) {
// Convert from wrapper type to primitive type

View File

@ -499,7 +499,7 @@ public class Agent {
} else {
StringBuilder message = new StringBuilder(params[0]);
for (int i = 1; i < params.length; i++) {
message.append(" " + params[i]);
message.append(' ').append(params[i]);
}
error(key, message.toString());
}

View File

@ -289,7 +289,7 @@ public abstract class MappedMXBeanType {
if (et.isPrimitive()) {
className = new StringBuilder(c.getName());
} else {
className.append("L" + baseElementType.getTypeName() + ";");
className.append('L').append(baseElementType.getTypeName()).append(';');
}
try {
mappedTypeClass = Class.forName(className.toString());
@ -385,7 +385,7 @@ public abstract class MappedMXBeanType {
if (elementType instanceof Class && ((Class) elementType).isPrimitive()) {
className = new StringBuilder(gat.toString());
} else {
className.append("L" + baseElementType.getTypeName() + ";");
className.append('L').append(baseElementType.getTypeName()).append(';');
}
try {
mappedTypeClass = Class.forName(className.toString());

View File

@ -111,7 +111,6 @@ public final class Connection implements Runnable {
private static final boolean debug = false;
private static final int dump = 0; // > 0 r, > 1 rw
public static final long DEFAULT_READ_TIMEOUT_MILLIS = 15 * 1000; // 15 second timeout;
final private Thread worker; // Initialized in constructor
@ -414,10 +413,13 @@ public final class Connection implements Runnable {
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
ldr.wait(DEFAULT_READ_TIMEOUT_MILLIS);
// no timeout is set so we wait infinitely until
// a response is received
// http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
ldr.wait();
}
waited = true;
} else {
break;
}

View File

@ -90,7 +90,7 @@ final class DefaultCallbackHandler implements CallbackHandler {
if (selected == -1) {
StringBuilder allChoices = new StringBuilder();
for (int j = 0; j < choices.length; j++) {
allChoices.append(choices[j] + ",");
allChoices.append(choices[j]).append(',');
}
throw new IOException("Cannot match " +
"'java.naming.security.sasl.realm' property value, '" +

View File

@ -170,7 +170,7 @@ class NameImpl {
endQuote = one ? syntaxEndQuote1 : syntaxEndQuote2;
i += syntaxTypevalSeparator.length();
answer.append(syntaxTypevalSeparator+beginQuote); // add back
answer.append(syntaxTypevalSeparator).append(beginQuote); // add back
// consume string until matching quote
for (i += beginQuote.length();

View File

@ -30,19 +30,19 @@
*/
package sun.security.krb5;
import java.io.File;
import java.io.FilePermission;
import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.security.PrivilegedAction;
import java.util.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sun.net.dns.ResolverConfiguration;
import sun.security.krb5.internal.crypto.EType;
@ -314,6 +314,72 @@ public class Config {
}
}
/**
* Translates a duration value into seconds.
*
* The format can be one of "h:m[:s]", "NdNhNmNs", and "N". See
* http://web.mit.edu/kerberos/krb5-devel/doc/basic/date_format.html#duration
* for definitions.
*
* @param s the string duration
* @return time in seconds
* @throw KrbException if format is illegal
*/
public static int duration(String s) throws KrbException {
if (s.isEmpty()) {
throw new KrbException("Duration cannot be empty");
}
// N
if (s.matches("\\d+")) {
return Integer.parseInt(s);
}
// h:m[:s]
Matcher m = Pattern.compile("(\\d+):(\\d+)(:(\\d+))?").matcher(s);
if (m.matches()) {
int hr = Integer.parseInt(m.group(1));
int min = Integer.parseInt(m.group(2));
if (min >= 60) {
throw new KrbException("Illegal duration format " + s);
}
int result = hr * 3600 + min * 60;
if (m.group(4) != null) {
int sec = Integer.parseInt(m.group(4));
if (sec >= 60) {
throw new KrbException("Illegal duration format " + s);
}
result += sec;
}
return result;
}
// NdNhNmNs
// 120m allowed. Maybe 1h120m is not good, but still allowed
m = Pattern.compile(
"((\\d+)d)?\\s*((\\d+)h)?\\s*((\\d+)m)?\\s*((\\d+)s)?",
Pattern.CASE_INSENSITIVE).matcher(s);
if (m.matches()) {
int result = 0;
if (m.group(2) != null) {
result += 86400 * Integer.parseInt(m.group(2));
}
if (m.group(4) != null) {
result += 3600 * Integer.parseInt(m.group(4));
}
if (m.group(6) != null) {
result += 60 * Integer.parseInt(m.group(6));
}
if (m.group(8) != null) {
result += Integer.parseInt(m.group(8));
}
return result;
}
throw new KrbException("Illegal duration format " + s);
}
/**
* Gets the int value for the specified keys.
* @param keys the keys

View File

@ -527,4 +527,23 @@ public class Credentials {
return sb.toString();
}
public sun.security.krb5.internal.ccache.Credentials toCCacheCreds() {
return new sun.security.krb5.internal.ccache.Credentials(
getClient(), getServer(),
getSessionKey(),
date2kt(getAuthTime()),
date2kt(getStartTime()),
date2kt(getEndTime()),
date2kt(getRenewTill()),
false,
flags,
new HostAddresses(getClientAddresses()),
getAuthzData(),
getTicket(),
null);
}
private static KerberosTime date2kt(Date d) {
return d == null ? null : new KerberosTime(d);
}
}

View File

@ -35,6 +35,7 @@ import sun.security.krb5.internal.*;
import sun.security.krb5.internal.crypto.Nonce;
import sun.security.krb5.internal.crypto.KeyUsage;
import java.io.IOException;
import java.time.Instant;
/**
* This class encapsulates the KRB-AS-REQ message that the client
@ -64,7 +65,6 @@ public class KrbAsReq {
if (options == null) {
options = new KDCOptions();
}
// check if they are valid arguments. The optional fields should be
// consistent with settings in KDCOptions. Mar 17 2000
if (options.get(KDCOptions.FORWARDED) ||
@ -82,12 +82,6 @@ public class KrbAsReq {
} else {
if (from != null) from = null;
}
if (options.get(KDCOptions.RENEWABLE)) {
// if (rtime == null)
// throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS);
} else {
if (rtime != null) rtime = null;
}
PAData[] paData = null;
if (pakey != null) {
@ -109,8 +103,10 @@ public class KrbAsReq {
System.out.println(">>> KrbAsReq creating message");
}
Config cfg = Config.getInstance();
// check to use addresses in tickets
if (addresses == null && Config.getInstance().useAddresses()) {
if (addresses == null && cfg.useAddresses()) {
addresses = HostAddresses.getLocalAddresses();
}
@ -120,7 +116,26 @@ public class KrbAsReq {
}
if (till == null) {
till = new KerberosTime(0); // Choose KDC maximum allowed
String d = cfg.get("libdefaults", "ticket_lifetime");
if (d != null) {
till = new KerberosTime(Instant.now().plusSeconds(Config.duration(d)));
} else {
till = new KerberosTime(0); // Choose KDC maximum allowed
}
}
if (rtime == null) {
String d = cfg.get("libdefaults", "renew_lifetime");
if (d != null) {
rtime = new KerberosTime(Instant.now().plusSeconds(Config.duration(d)));
}
}
if (rtime != null) {
options.set(KDCOptions.RENEWABLE, true);
if (till.greaterThan(rtime)) {
rtime = till;
}
}
// enc-authorization-data and additional-tickets never in AS-REQ

View File

@ -224,6 +224,16 @@ public final class KrbAsReqBuilder {
this.options = options;
}
public void setTill(KerberosTime till) {
checkState(State.INIT, "Cannot specify till");
this.till = till;
}
public void setRTime(KerberosTime rtime) {
checkState(State.INIT, "Cannot specify rtime");
this.rtime = rtime;
}
/**
* Sets or clears target. If cleared, KrbAsReq might choose krbtgt
* for cname realm

View File

@ -96,13 +96,14 @@ public class KrbException extends Exception {
public String krbErrorMessage() {
StringBuilder strbuf = new StringBuilder("krb_error " + returnCode);
StringBuilder sb = new StringBuilder();
sb.append("krb_error ").append(returnCode);
String msg = getMessage();
if (msg != null) {
strbuf.append(" ");
strbuf.append(msg);
sb.append(" ");
sb.append(msg);
}
return strbuf.toString();
return sb.toString();
}
/**

View File

@ -80,49 +80,41 @@ abstract class KrbKdcRep {
rep.encKDCRepPart.flags.get(KDCOptions.RENEWABLE)) {
throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
}
if ((req.reqBody.from == null) || req.reqBody.from.isZero())
if ((req.reqBody.from == null) || req.reqBody.from.isZero()) {
// verify this is allowed
if ((rep.encKDCRepPart.starttime != null) &&
!rep.encKDCRepPart.starttime.inClockSkew()) {
!rep.encKDCRepPart.starttime.inClockSkew()) {
rep.encKDCRepPart.key.destroy();
throw new KrbApErrException(Krb5.KRB_AP_ERR_SKEW);
}
}
if ((req.reqBody.from != null) && !req.reqBody.from.isZero())
if ((req.reqBody.from != null) && !req.reqBody.from.isZero()) {
// verify this is allowed
if ((rep.encKDCRepPart.starttime != null) &&
!req.reqBody.from.equals(rep.encKDCRepPart.starttime)) {
!req.reqBody.from.equals(rep.encKDCRepPart.starttime)) {
rep.encKDCRepPart.key.destroy();
throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
}
}
if (!req.reqBody.till.isZero() &&
rep.encKDCRepPart.endtime.greaterThan(req.reqBody.till)) {
rep.encKDCRepPart.endtime.greaterThan(req.reqBody.till)) {
rep.encKDCRepPart.key.destroy();
throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
}
if (req.reqBody.kdcOptions.get(KDCOptions.RENEWABLE))
if (req.reqBody.rtime != null && !req.reqBody.rtime.isZero())
// verify this is required
if (req.reqBody.kdcOptions.get(KDCOptions.RENEWABLE)) {
if (req.reqBody.rtime != null && !req.reqBody.rtime.isZero()) {
// verify this is required
if ((rep.encKDCRepPart.renewTill == null) ||
rep.encKDCRepPart.renewTill.greaterThan(req.reqBody.rtime)
) {
rep.encKDCRepPart.key.destroy();
throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
}
if (req.reqBody.kdcOptions.get(KDCOptions.RENEWABLE_OK) &&
rep.encKDCRepPart.flags.get(KDCOptions.RENEWABLE))
if (!req.reqBody.till.isZero())
// verify this is required
if ((rep.encKDCRepPart.renewTill == null) ||
rep.encKDCRepPart.renewTill.greaterThan(req.reqBody.till)
) {
rep.encKDCRepPart.renewTill.greaterThan(req.reqBody.rtime)
) {
rep.encKDCRepPart.key.destroy();
throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
}
}
}
}
}

View File

@ -35,7 +35,6 @@ import sun.security.krb5.internal.*;
import sun.security.krb5.internal.crypto.*;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Arrays;
/**
* This class encapsulates a Kerberos TGS-REQ that is sent from the

View File

@ -250,6 +250,10 @@ public class HostAddresses implements Cloneable {
*/
public void writeAddrs(CCacheOutputStream cos) throws IOException {
if (addresses == null || addresses.length == 0) {
cos.write32(0);
return;
}
cos.write32(addresses.length);
for (int i = 0; i < addresses.length; i++) {
cos.write16(addresses[i].addrType);

View File

@ -38,6 +38,7 @@ import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import java.io.IOException;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
@ -128,6 +129,14 @@ public class KerberosTime {
this(time.getTime(), 0);
}
/**
* Creates a KerberosTime object from an Instant object
*/
public KerberosTime(Instant instant) {
this(instant.getEpochSecond()*1000 + instant.getNano()/1000000L,
instant.getNano()/1000%1000);
}
/**
* Creates a KerberosTime object for now. It uses System.nanoTime()
* to get a more precise time than "new Date()".

View File

@ -640,8 +640,7 @@ public abstract class DkCrypto {
for (int i = 0; i < digest.length; i++) {
if ((digest[i] & 0x000000ff) < 0x10) {
digestString.append("0" +
Integer.toHexString(digest[i] & 0x000000ff));
digestString.append('0').append(Integer.toHexString(digest[i] & 0x000000ff));
} else {
digestString.append(
Integer.toHexString(digest[i] & 0x000000ff));

View File

@ -36,7 +36,6 @@ import sun.security.krb5.internal.*;
import sun.security.krb5.internal.ccache.*;
import java.io.IOException;
import java.util.Arrays;
import javax.security.auth.kerberos.KerberosPrincipal;
import sun.security.util.Password;
import javax.security.auth.kerberos.KeyTab;
@ -53,22 +52,9 @@ public class Kinit {
/**
* The main method is used to accept user command line input for ticket
* request.
* <p>
* Usage: kinit [-A] [-f] [-p] [-c cachename] [[-k [-t keytab_file_name]]
* [principal] [password]
* <ul>
* <li> -A do not include addresses
* <li> -f forwardable
* <li> -p proxiable
* <li> -c cache name (i.e., FILE://c:\temp\mykrb5cc)
* <li> -k use keytab
* <li> -t keytab file name
* <li> principal the principal name (i.e., duke@java.sun.com)
* <li> password the principal's Kerberos password
* </ul>
* <p>
* Use java sun.security.krb5.tools.Kinit -help to bring up help menu.
* request. Read {@link KinitOptions#printHelp} for usages or call
* java sun.security.krb5.internal.tools.Kinit -help
* to bring up help menu.
* <p>
* We currently support only file-based credentials cache to
* store the tickets obtained from the KDC.
@ -146,6 +132,49 @@ public class Kinit {
} else {
options = new KinitOptions(args);
}
switch (options.action) {
case 1:
acquire();
break;
case 2:
renew();
break;
default:
throw new KrbException("kinit does not support action "
+ options.action);
}
}
private void renew()
throws IOException, RealmException, KrbException {
PrincipalName principal = options.getPrincipal();
String realm = principal.getRealmAsString();
CredentialsCache cache = CredentialsCache.getInstance(options.cachename);
if (cache == null) {
throw new IOException("Unable to find existing cache file " +
options.cachename);
}
sun.security.krb5.internal.ccache.Credentials credentials =
cache.getCreds(PrincipalName.tgsService(realm, realm));
credentials = credentials.setKrbCreds()
.renew()
.toCCacheCreds();
cache = CredentialsCache.create(principal, options.cachename);
if (cache == null) {
throw new IOException("Unable to create the cache file " +
options.cachename);
}
cache.update(credentials);
cache.save();
}
private void acquire()
throws IOException, RealmException, KrbException {
String princName = null;
PrincipalName principal = options.getPrincipal();
if (principal != null) {
@ -216,6 +245,9 @@ public class Kinit {
if (options.getAddressOption())
builder.setAddresses(HostAddresses.getLocalAddresses());
builder.setTill(options.lifetime);
builder.setRTime(options.renewable_lifetime);
builder.action();
sun.security.krb5.internal.ccache.Credentials credentials =

View File

@ -33,12 +33,8 @@ package sun.security.krb5.internal.tools;
import sun.security.krb5.*;
import sun.security.krb5.internal.*;
import sun.security.krb5.internal.ccache.*;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.Instant;
import java.io.FileInputStream;
/**
@ -49,14 +45,15 @@ import java.io.FileInputStream;
* @author Ram Marti
*/
class KinitOptions {
public boolean validate = false;
// 1. acquire, 2. renew, 3. validate
public int action = 1;
// forwardable and proxiable flags have two states:
// -1 - flag set to be not forwardable or proxiable;
// 1 - flag set to be forwardable or proxiable.
public short forwardable = -1;
public short proxiable = -1;
public boolean renew = false;
public short forwardable = 0;
public short proxiable = 0;
public KerberosTime lifetime;
public KerberosTime renewable_lifetime;
public String target_service;
@ -134,6 +131,12 @@ class KinitOptions {
}
useKeytab = true;
} else if (args[i].equals("-R")) {
action = 2;
} else if (args[i].equals("-l")) {
lifetime = getTime(Config.duration(args[++i]));
} else if (args[i].equals("-r")) {
renewable_lifetime = getTime(Config.duration(args[++i]));
} else if (args[i].equalsIgnoreCase("-help")) {
printHelp();
System.exit(0);
@ -223,23 +226,28 @@ class KinitOptions {
void printHelp() {
System.out.println("Usage: kinit " +
"[-A] [-f] [-p] [-c cachename] " +
"[[-k [-t keytab_file_name]] [principal] " +
System.out.println("Usage:\n\n1. Initial ticket request:\n" +
" kinit [-A] [-f] [-p] [-c cachename] " +
"[-l lifetime] [-r renewable_time]\n" +
" [[-k [-t keytab_file_name]] [principal] " +
"[password]");
System.out.println("\tavailable options to " +
System.out.println("2. Renew a ticket:\n" +
" kinit -R [-c cachename] [principal]");
System.out.println("\nAvailable options to " +
"Kerberos 5 ticket request:");
System.out.println("\t -A do not include addresses");
System.out.println("\t -f forwardable");
System.out.println("\t -p proxiable");
System.out.println("\t -c cache name " +
"(i.e., FILE:\\d:\\myProfiles\\mykrb5cache)");
System.out.println("\t -k use keytab");
System.out.println("\t -t keytab file name");
System.out.println("\t principal the principal name "+
"(i.e., qweadf@ATHENA.MIT.EDU qweadf)");
System.out.println("\t password " +
"the principal's Kerberos password");
System.out.println("\t-A do not include addresses");
System.out.println("\t-f forwardable");
System.out.println("\t-p proxiable");
System.out.println("\t-c cache name " +
"(i.e., FILE:\\d:\\myProfiles\\mykrb5cache)");
System.out.println("\t-l lifetime");
System.out.println("\t-r renewable time " +
"(total lifetime a ticket can be renewed)");
System.out.println("\t-k use keytab");
System.out.println("\t-t keytab file name");
System.out.println("\tprincipal the principal name "+
"(i.e., qweadf@ATHENA.MIT.EDU qweadf)");
System.out.println("\tpassword the principal's Kerberos password");
}
public boolean getAddressOption() {
@ -257,4 +265,8 @@ class KinitOptions {
public PrincipalName getPrincipal() {
return principal;
}
private KerberosTime getTime(int s) {
return new KerberosTime(Instant.now().plusSeconds(s));
}
}

View File

@ -196,8 +196,7 @@ abstract class CramMD5Base {
for (i = 0; i < digest.length; i++) {
if ((digest[i] & 0x000000ff) < 0x10) {
digestString.append("0" +
Integer.toHexString(digest[i] & 0x000000ff));
digestString.append('0').append(Integer.toHexString(digest[i] & 0x000000ff));
} else {
digestString.append(
Integer.toHexString(digest[i] & 0x000000ff));

View File

@ -391,8 +391,7 @@ abstract class DigestMD5Base extends AbstractSaslImpl {
for (int i = 0; i < digest.length; i ++) {
if ((digest[i] & 0x000000ff) < 0x10) {
digestString.append("0"+
Integer.toHexString(digest[i] & 0x000000ff));
digestString.append('0').append(Integer.toHexString(digest[i] & 0x000000ff));
} else {
digestString.append(
Integer.toHexString(digest[i] & 0x000000ff));

View File

@ -235,14 +235,15 @@ public abstract class AbstractSerializer implements Serializer {
String nodeName = att.getNodeName();
if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
&& !storedNamespaces.containsKey(att.getNodeName())) {
sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\"");
sb.append(' ').append(nodeName).append("=\"")
.append(att.getNodeValue()).append('"');
storedNamespaces.put(nodeName, att.getNodeValue());
}
}
}
wk = wk.getParentNode();
}
sb.append(">" + source + "</dummy>");
sb.append('>').append(source).append("</dummy>");
return sb.toString();
}

View File

@ -85,7 +85,7 @@ public class InclusiveNamespaces extends ElementProxy implements TransformParam
if (prefix.equals("xmlns")) {
sb.append("#default ");
} else {
sb.append(prefix + " ");
sb.append(prefix).append(' ');
}
}

View File

@ -88,7 +88,7 @@ public class RFC2253Parser {
l += countQuotes(DN, j, k);
if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) {
sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ",");
sb.append(parseRDN(DN.substring(i, k).trim(), toXml)).append(',');
i = k + 1;
l = 0;
@ -121,7 +121,7 @@ public class RFC2253Parser {
l += countQuotes(str, j, k);
if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+");
sb.append(parseATAV(trim(str.substring(i, k)), toXml)).append('+');
i = k + 1;
l = 0;
@ -369,7 +369,7 @@ public class RFC2253Parser {
int k;
for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) {
sb.append(trim(string.substring(i, k)) + "\\ ");
sb.append(trim(string.substring(i, k))).append("\\ ");
i = k + 3;
}
@ -418,7 +418,7 @@ public class RFC2253Parser {
l += countQuotes(str, j, k);
if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
sb.append(trim(str.substring(i, k)) + replace);
sb.append(trim(str.substring(i, k))).append(replace);
i = k + 1;
l = 0;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -445,6 +445,7 @@ abstract class P11Key implements Key, Length {
}
}
@SuppressWarnings("deprecation")
private static class P11TlsMasterSecretKey extends P11SecretKey
implements TlsMasterSecret {
private static final long serialVersionUID = -1318560923770573441L;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -169,6 +169,7 @@ final class P11RSACipher extends CipherSpi {
}
// see JCE spec
@SuppressWarnings("deprecation")
protected void engineInit(int opmode, Key key,
AlgorithmParameterSpec params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
@ -461,6 +462,7 @@ final class P11RSACipher extends CipherSpi {
}
// see JCE spec
@SuppressWarnings("deprecation")
protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
int type) throws InvalidKeyException, NoSuchAlgorithmException {

View File

@ -765,12 +765,14 @@ final class P11Signature extends SignatureSpi {
}
// see JCA spec
@SuppressWarnings("deprecation")
protected void engineSetParameter(String param, Object value)
throws InvalidParameterException {
throw new UnsupportedOperationException("setParameter() not supported");
}
// see JCA spec
@SuppressWarnings("deprecation")
protected Object engineGetParameter(String param)
throws InvalidParameterException {
throw new UnsupportedOperationException("getParameter() not supported");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -62,6 +62,7 @@ public final class P11TlsKeyMaterialGenerator extends KeyGeneratorSpi {
private long mechanism;
// parameter spec
@SuppressWarnings("deprecation")
private TlsKeyMaterialParameterSpec spec;
// master secret as a P11Key
@ -82,6 +83,7 @@ public final class P11TlsKeyMaterialGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
@SuppressWarnings("deprecation")
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsKeyMaterialParameterSpec == false) {
@ -107,6 +109,7 @@ public final class P11TlsKeyMaterialGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
@SuppressWarnings("deprecation")
protected SecretKey engineGenerateKey() {
if (spec == null) {
throw new IllegalStateException

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -57,6 +57,7 @@ public final class P11TlsMasterSecretGenerator extends KeyGeneratorSpi {
// mechanism id
private long mechanism;
@SuppressWarnings("deprecation")
private TlsMasterSecretParameterSpec spec;
private P11Key p11Key;
@ -74,6 +75,7 @@ public final class P11TlsMasterSecretGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
@SuppressWarnings("deprecation")
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsMasterSecretParameterSpec == false) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -63,6 +63,7 @@ final class P11TlsPrfGenerator extends KeyGeneratorSpi {
// mechanism id
private final long mechanism;
@SuppressWarnings("deprecation")
private TlsPrfParameterSpec spec;
private P11Key p11Key;
@ -79,6 +80,7 @@ final class P11TlsPrfGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
@SuppressWarnings("deprecation")
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsPrfParameterSpec == false) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
@ -57,6 +57,7 @@ final class P11TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
// mechanism id
private long mechanism;
@SuppressWarnings("deprecation")
private TlsRsaPremasterSecretParameterSpec spec;
P11TlsRsaPremasterSecretGenerator(Token token, String algorithm, long mechanism)
@ -71,6 +72,7 @@ final class P11TlsRsaPremasterSecretGenerator extends KeyGeneratorSpi {
throw new InvalidParameterException(MSG);
}
@SuppressWarnings("deprecation")
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {

View File

@ -346,12 +346,12 @@ public class JavaValueArray extends JavaLazyReadObject
public String valueString(boolean bigLimit) {
// Char arrays deserve special treatment
StringBuffer result;
StringBuilder result;
byte[] value = getValue();
int max = value.length;
byte elementSignature = getElementType();
if (elementSignature == 'C') {
result = new StringBuffer();
result = new StringBuilder();
for (int i = 0; i < value.length; ) {
char val = charAt(i, value);
result.append(val);
@ -362,7 +362,7 @@ public class JavaValueArray extends JavaLazyReadObject
if (bigLimit) {
limit = 1000;
}
result = new StringBuffer("{");
result = new StringBuilder("{");
int num = 0;
for (int i = 0; i < value.length; ) {
if (num > 0) {
@ -386,37 +386,37 @@ public class JavaValueArray extends JavaLazyReadObject
}
case 'B': {
int val = 0xFF & byteAt(i, value);
result.append("0x" + Integer.toString(val, 16));
result.append("0x").append(Integer.toString(val, 16));
i++;
break;
}
case 'S': {
short val = shortAt(i, value);
i += 2;
result.append("" + val);
result.append(val);
break;
}
case 'I': {
int val = intAt(i, value);
i += 4;
result.append("" + val);
result.append(val);
break;
}
case 'J': { // long
long val = longAt(i, value);
result.append("" + val);
result.append(val);
i += 8;
break;
}
case 'F': {
float val = floatAt(i, value);
result.append("" + val);
result.append(val);
i += 4;
break;
}
case 'D': { // double
double val = doubleAt(i, value);
result.append("" + val);
result.append(val);
i += 8;
break;
}
@ -425,7 +425,7 @@ public class JavaValueArray extends JavaLazyReadObject
}
}
}
result.append("}");
result.append('}');
}
return result.toString();
}

View File

@ -97,11 +97,11 @@ public class Misc {
} else if (ch == '&') {
sb.append("&amp;");
} else if (ch < ' ') {
sb.append("&#" + Integer.toString(ch) + ";");
sb.append("&#").append((int)ch).append(';');
} else {
int c = (ch & 0xFFFF);
if (c > 127) {
sb.append("&#" + Integer.toString(c) + ";");
sb.append("&#").append(c).append(';');
} else {
sb.append(ch);
}

View File

@ -676,14 +676,13 @@ public class Main {
((man.getAttributes(name) != null) ||
(man.getAttributes("./"+name) != null) ||
(man.getAttributes("/"+name) != null));
sb.append(
(isSigned ? rb.getString("s") : rb.getString("SPACE")) +
(inManifest ? rb.getString("m") : rb.getString("SPACE")) +
(inStore ? rb.getString("k") : rb.getString("SPACE")) +
(inScope ? rb.getString("i") : rb.getString("SPACE")) +
((inStoreOrScope & NOT_ALIAS) != 0 ?"X":" ") +
rb.getString("SPACE"));
sb.append("|");
sb.append(isSigned ? rb.getString("s") : rb.getString("SPACE"))
.append(inManifest ? rb.getString("m") : rb.getString("SPACE"))
.append(inStore ? rb.getString("k") : rb.getString("SPACE"))
.append(inScope ? rb.getString("i") : rb.getString("SPACE"))
.append((inStoreOrScope & NOT_ALIAS) != 0 ? 'X' : ' ')
.append(rb.getString("SPACE"));
sb.append('|');
}
// When -certs provided, display info has extra empty
@ -704,11 +703,15 @@ public class Main {
// Print no info for unsigned entries when -verbose:all,
// to be consistent with old behavior.
if (signatureRelated(name)) {
sb.append("\n" + tab + rb.getString(
".Signature.related.entries.") + "\n\n");
sb.append('\n')
.append(tab)
.append(rb
.getString(".Signature.related.entries."))
.append("\n\n");
} else {
sb.append("\n" + tab + rb.getString(
".Unsigned.entries.") + "\n\n");
sb.append('\n').append(tab)
.append(rb.getString(".Unsigned.entries."))
.append("\n\n");
}
}
@ -1605,8 +1608,8 @@ public class Main {
// No more warning, we alreay have hasExpiredCert or notYetValidCert
} else {
chainNotValidated = true;
sb.append(tab + rb.getString(".CertPath.not.validated.") +
e.getLocalizedMessage() + "]\n"); // TODO
sb.append(tab).append(rb.getString(".CertPath.not.validated."))
.append(e.getLocalizedMessage()).append("]\n"); // TODO
}
}
String result = sb.toString();

View File

@ -92,28 +92,28 @@ public class Jps {
vm = monitoredHost.getMonitoredVm(id, 0);
errorString = " -- main class information unavailable";
output.append(" " + MonitoredVmUtil.mainClass(vm,
output.append(' ').append(MonitoredVmUtil.mainClass(vm,
arguments.showLongPaths()));
if (arguments.showMainArgs()) {
errorString = " -- main args information unavailable";
String mainArgs = MonitoredVmUtil.mainArgs(vm);
if (mainArgs != null && mainArgs.length() > 0) {
output.append(" " + mainArgs);
output.append(' ').append(mainArgs);
}
}
if (arguments.showVmArgs()) {
errorString = " -- jvm args information unavailable";
String jvmArgs = MonitoredVmUtil.jvmArgs(vm);
if (jvmArgs != null && jvmArgs.length() > 0) {
output.append(" " + jvmArgs);
output.append(' ').append(jvmArgs);
}
}
if (arguments.showVmFlags()) {
errorString = " -- jvm flags information unavailable";
String jvmFlags = MonitoredVmUtil.jvmFlags(vm);
if (jvmFlags != null && jvmFlags.length() > 0) {
output.append(" " + jvmFlags);
output.append(' ').append(jvmFlags);
}
}

View File

@ -50,7 +50,7 @@ public class RawOutputFormatter implements OutputFormatter {
StringBuilder headerBuilder = new StringBuilder();
for (Iterator<Monitor> i = logged.iterator(); i.hasNext(); /* empty */ ) {
Monitor m = i.next();
headerBuilder.append(m.getName() + " ");
headerBuilder.append(m.getName()).append(' ');
}
header = headerBuilder.toString();
}

View File

@ -65,24 +65,21 @@ public class SyntaxException extends ParserException {
public SyntaxException(int lineno, Set<String> expected, Token found) {
StringBuilder msg = new StringBuilder();
msg.append("Syntax error at line " + lineno + ": Expected one of \'");
msg.append("Syntax error at line ").append(lineno)
.append(": Expected one of \'");
boolean first = true;
for (Iterator<String> i = expected.iterator(); i.hasNext(); /* empty */) {
String keyWord = i.next();
if (first) {
msg.append(keyWord);
first = false;
} else {
msg.append("|" + keyWord);
}
for (String keyWord : expected) {
msg.append(keyWord).append('|');
}
if (!expected.isEmpty()) {
msg.setLength(msg.length() - 1);
}
msg.append("\', Found " + found.toMessage());
message = msg.toString();
message = msg.append("\', Found ").append(found.toMessage()).toString();
}
public String getMessage() {
return message;
}
}

View File

@ -368,7 +368,7 @@ class ThreadTab extends Tab implements ActionListener, DocumentListener, ListSel
sb.append(Messages.STACK_TRACE);
int index = 0;
for (StackTraceElement e : ti.getStackTrace()) {
sb.append(e.toString()+"\n");
sb.append(e).append('\n');
if (monitors != null) {
for (MonitorInfo mi : monitors) {
if (mi.getLockedStackDepth() == index) {

View File

@ -79,25 +79,25 @@ class XArrayDataViewer {
String textColor = String.format("%06x",
foreground.getRGB() & 0xFFFFFF);
StringBuilder sb = new StringBuilder();
sb.append("<html><body text=#"+textColor+"><table width=\"100%\">");
sb.append("<html><body text=#").append(textColor).append("><table width=\"100%\">");
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
sb.append("<tr style=\"background-color: " +
evenRowColorStr + "\"><td><pre>" +
(arr[i] == null ?
arr[i] : htmlize(arr[i].toString())) +
"</pre></td></tr>");
sb.append("<tr style=\"background-color: ")
.append(evenRowColorStr).append("\"><td><pre>")
.append(arr[i] == null ?
arr[i] : htmlize(arr[i].toString()))
.append("</pre></td></tr>");
} else {
sb.append("<tr style=\"background-color: " +
oddRowColorStr + "\"><td><pre>" +
(arr[i] == null ?
arr[i] : htmlize(arr[i].toString())) +
"</pre></td></tr>");
sb.append("<tr style=\"background-color: ")
.append(oddRowColorStr).append("\"><td><pre>")
.append(arr[i] == null ?
arr[i] : htmlize(arr[i].toString()))
.append("</pre></td></tr>");
}
}
if (arr.length == 0) {
sb.append("<tr style=\"background-color: " +
evenRowColorStr + "\"><td></td></tr>");
sb.append("<tr style=\"background-color: ")
.append(evenRowColorStr).append("\"><td></td></tr>");
}
sb.append("</table></body></html>");
arrayEditor.setText(sb.toString());

View File

@ -507,13 +507,13 @@ public class XTree extends JTree {
// key order defined by the "orderedKeyPropertyList"
for (String key : orderedKeyPropertyList) {
if (map.containsKey(key)) {
sb.append(key + "=" + map.get(key) + ",");
sb.append(key).append('=').append(map.get(key)).append(',');
map.remove(key);
}
}
// Add the remaining key/value pairs to the buffer
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue() + ",");
sb.append(entry.getKey()).append('=').append(entry.getValue()).append(',');
}
String orderedKeyPropertyListString = sb.toString();
orderedKeyPropertyListString = orderedKeyPropertyListString.substring(
@ -622,7 +622,7 @@ public class XTree extends JTree {
//
StringBuilder sb = new StringBuilder();
for (MBeanParameterInfo mbpi : mboi.getSignature()) {
sb.append(mbpi.getType() + ",");
sb.append(mbpi.getType()).append(',');
}
String signature = sb.toString();
if (signature.length() > 0) {

View File

@ -59,6 +59,7 @@ public class ExpressionParser implements ExpressionParserConstants {
StackFrame get() throws IncompatibleThreadStateException;
}
@SuppressWarnings("deprecation")
public static Value evaluate(String expr, VirtualMachine vm,
GetFrame frameGetter) throws ParseException,
InvocationException,

View File

@ -198,7 +198,7 @@ public class ParseException extends Exception {
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}

View File

@ -107,7 +107,7 @@ public class TokenMgrError extends Error
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}

View File

@ -881,12 +881,12 @@ class VirtualMachineImpl extends MirrorImpl
} else if (tag == JDWP.TypeTag.ARRAY) {
sb.append("ArrayType");
} else {
sb.append("UNKNOWN TAG: " + tag);
sb.append("UNKNOWN TAG: ").append(tag);
}
if (signature != null) {
sb.append(", signature='" + signature + "'");
sb.append(", signature='").append(signature).append('\'');
}
sb.append(", id=" + id);
sb.append(", id=").append(id);
vm.printTrace(sb.toString());
}
if (id == 0) {

View File

@ -66,8 +66,10 @@ printLastError(jdwpTransportEnv *t, jdwpTransportError err)
len = (int)strlen(msg);
maxlen = len+len/2+2; /* Should allow for plenty of room */
utf8msg = (jbyte*)jvmtiAllocate(maxlen+1);
(void)utf8FromPlatform(msg, len, utf8msg, maxlen);
utf8msg[maxlen] = 0;
if (utf8msg != NULL) {
(void)utf8FromPlatform(msg, len, utf8msg, maxlen);
utf8msg[maxlen] = 0;
}
}
if (rv == JDWPTRANSPORT_ERROR_NONE) {
ERROR_MESSAGE(("transport error %d: %s",err, utf8msg));
@ -391,6 +393,10 @@ launch(char *command, char *name, char *address)
/* Convert commandLine from UTF-8 to platform encoding */
len = (int)strlen(commandLine);
buf = jvmtiAllocate(len*3+3);
if (buf == NULL) {
jvmtiDeallocate(commandLine);
return JDWP_ERROR(OUT_OF_MEMORY);
}
(void)utf8ToPlatform((jbyte*)commandLine, len, buf, len*3+3);
/* Exec commandLine */
@ -447,21 +453,23 @@ transport_startTransport(jboolean isServer, char *name, char *address,
if (info == NULL) {
return JDWP_ERROR(OUT_OF_MEMORY);
}
info->name = jvmtiAllocate((int)strlen(name)+1);
(void)strcpy(info->name, name);
info->address = NULL;
info->timeout = timeout;
info->name = jvmtiAllocate((int)strlen(name)+1);
if (info->name == NULL) {
serror = JDWP_ERROR(OUT_OF_MEMORY);
goto handleError;
}
(void)strcpy(info->name, name);
info->address = NULL;
if (address != NULL) {
info->address = jvmtiAllocate((int)strlen(address)+1);
(void)strcpy(info->address, address);
if (info->address == NULL) {
serror = JDWP_ERROR(OUT_OF_MEMORY);
goto handleError;
}
(void)strcpy(info->address, address);
}
info->transport = trans;
@ -478,6 +486,10 @@ transport_startTransport(jboolean isServer, char *name, char *address,
*/
len = (int)strlen(name) + (int)strlen(retAddress) + 2; /* ':' and '\0' */
prop_value = (char*)jvmtiAllocate(len);
if (prop_value == NULL) {
serror = JDWP_ERROR(OUT_OF_MEMORY);
goto handleError;
}
strcpy(prop_value, name);
strcat(prop_value, ":");
strcat(prop_value, retAddress);

View File

@ -158,6 +158,7 @@ public abstract class PerfDataBufferImpl {
* the sun.jvmstat.perfdata.aliasmap file indicates some other
* file as the source.
*/
@SuppressWarnings("deprecation")
private void buildAliasMap() {
assert Thread.holdsLock(this);

View File

@ -76,6 +76,7 @@ public class Jstatd {
}
}
@SuppressWarnings("deprecation") // Use of RMISecurityManager
public static void main(String[] args) {
String rminame = null;
int argc = 0;

View File

@ -68,7 +68,7 @@ public class RemoteHostImpl implements RemoteHost, HostListener {
sb.append("local://").append(lvmid).append("@localhost");
if (mode != null) {
sb.append("?mode=" + mode);
sb.append("?mode=").append(mode);
}
String vmidStr = sb.toString();

View File

@ -463,12 +463,12 @@ public final class DNSNameService implements NameService {
// ---------
private static void appendIfLiteralAddress(String addr, StringBuffer sb) {
private static void appendIfLiteralAddress(String addr, StringBuilder sb) {
if (IPAddressUtil.isIPv4LiteralAddress(addr)) {
sb.append("dns://" + addr + " ");
sb.append("dns://").append(addr).append(' ');
} else {
if (IPAddressUtil.isIPv6LiteralAddress(addr)) {
sb.append("dns://[" + addr + "] ");
sb.append("dns://[").append(addr).append("] ");
}
}
}
@ -478,7 +478,7 @@ public final class DNSNameService implements NameService {
* corresponding to the supplied List of nameservers.
*/
private static String createProviderURL(List<String> nsList) {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (String s: nsList) {
appendIfLiteralAddress(s, sb);
}
@ -491,7 +491,7 @@ public final class DNSNameService implements NameService {
* contained in the provided str.
*/
private static String createProviderURL(String str) {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
appendIfLiteralAddress(st.nextToken(), sb);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 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
@ -353,6 +353,7 @@ public class RegistryContext implements Context, Referenceable {
/**
* Wrap a RemoteException inside a NamingException.
*/
@SuppressWarnings("deprecation")
public static NamingException wrapRemoteException(RemoteException re) {
NamingException ne;
@ -413,6 +414,7 @@ public class RegistryContext implements Context, Referenceable {
* Attempts to install a security manager if none is currently in
* place.
*/
@SuppressWarnings("deprecation")
private static void installSecurityMgr() {
try {

View File

@ -980,8 +980,9 @@ class PolicyEntry {
grantEntry.principals.listIterator();
while (list.hasNext()) {
PolicyParser.PrincipalEntry pppe = list.next();
sb.append(" Principal " + pppe.getDisplayClass() + " " +
pppe.getDisplayName(true));
sb.append(" Principal ").append(pppe.getDisplayClass())
.append(' ')
.append(pppe.getDisplayName(true));
if (list.hasNext()) sb.append(", ");
}
result = sb.toString();

View File

@ -103,6 +103,7 @@ class ZipUtils {
/*
* Converts DOS time to Java time (number of milliseconds since epoch).
*/
@SuppressWarnings("deprecation")
public static long dosToJavaTime(long dtime) {
Date d = new Date((int)(((dtime >> 25) & 0x7f) + 80),
(int)(((dtime >> 21) & 0x0f) - 1),
@ -116,6 +117,7 @@ class ZipUtils {
/*
* Converts Java time to DOS time.
*/
@SuppressWarnings("deprecation")
public static long javaToDosTime(long time) {
Date d = new Date(time);
int year = d.getYear() + 1900;

View File

@ -1,5 +1,5 @@
#
# Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 1995, 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
@ -258,6 +258,11 @@ jdk_% core_% svc_%:
# ------------------------------------------------------------------
# When called from JPRT the TESTDIRS variable is set to the jtreg tests to run
ifdef TESTDIRS
TEST_SELECTION = $(TESTDIRS)
endif
ifdef CONCURRENCY
EXTRA_JTREG_OPTIONS += -concurrency:$(CONCURRENCY)
endif

View File

@ -28,144 +28,59 @@
* @summary Timeout tests for ldap
*/
import com.sun.jndi.ldap.Connection;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.io.*;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.List;
import java.util.Hashtable;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
public class LdapTimeoutTest {
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
abstract class LdapTest implements Callable {
public static void main(String[] args) throws Exception {
ServerSocket serverSock = new ServerSocket(0);
Server s = new Server(serverSock);
s.start();
Thread.sleep(200);
Hashtable env;
TestServer server;
ScheduledExecutorService killSwitchPool;
boolean passed = false;
private int HANGING_TEST_TIMEOUT = 20_000;
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:" +
serverSock.getLocalPort());
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL, "user");
env.put(Context.SECURITY_CREDENTIALS, "password");
InitialContext ctx = null;
try {
new LdapTimeoutTest().deadServerNoTimeout(env);
env.put("com.sun.jndi.ldap.connect.timeout", "10");
env.put("com.sun.jndi.ldap.read.timeout", "3000");
new LdapTimeoutTest().ldapReadTimeoutTest(env, false);
new LdapTimeoutTest().ldapReadTimeoutTest(env, true);
new LdapTimeoutTest().simpleAuthConnectTest(env);
} finally {
s.interrupt();
}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");
public LdapTest (TestServer server, Hashtable env) {
this.server = server;
this.env = env;
}
void ldapReadTimeoutTest(Hashtable env, boolean ssl) {
InitialContext ctx = null;
if (ssl) env.put(Context.SECURITY_PROTOCOL, "ssl");
long start = System.nanoTime();
try {
ctx = new InitialDirContext(env);
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = ((InitialDirContext)ctx)
.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
// shouldn't reach here
fail();
} catch (NamingException e) {
if (ssl) {
if (e.getCause() instanceof SocketTimeoutException) {
pass();
} else if (e.getCause() instanceof InterruptedIOException) {
Thread.interrupted();
fail();
}
} else {
pass();
}
} finally {
if (!shutItDown(ctx)) fail();
}
public LdapTest(TestServer server, Hashtable env,
ScheduledExecutorService killSwitchPool)
{
this(server, env);
this.killSwitchPool = killSwitchPool;
}
void simpleAuthConnectTest(Hashtable env) {
InitialContext ctx = null;
long start = System.nanoTime();
try {
ctx = new InitialDirContext(env);
// shouldn't reach here
System.err.println("Fail: InitialDirContext succeeded");
fail();
} catch (NamingException e) {
long end = System.nanoTime();
if (e.getCause() instanceof SocketTimeoutException) {
if (NANOSECONDS.toMillis(end - start) < 2_900) {
pass();
} else {
System.err.println("Fail: Waited too long");
fail();
}
} else if (e.getCause() instanceof InterruptedIOException) {
Thread.interrupted();
fail();
} else {
fail();
}
} finally {
if (!shutItDown(ctx)) fail();
}
public abstract void performOp(InitialContext ctx) throws NamingException;
public abstract void handleNamingException(
NamingException e, long start, long end);
public void pass() {
this.passed = true;
}
void deadServerNoTimeout(Hashtable env) {
InitialContext ctx = null;
long start = System.currentTimeMillis();
try {
ctx = new InitialDirContext(env);
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = ((InitialDirContext)ctx)
.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
// shouldn't reach here
fail();
} catch (NamingException e) {
long elapsed = System.currentTimeMillis() - start;
if (elapsed < Connection.DEFAULT_READ_TIMEOUT_MILLIS) {
System.err.printf("fail: timeout should be at least %s ms, " +
"actual time is %s ms%n",
Connection.DEFAULT_READ_TIMEOUT_MILLIS, elapsed);
e.printStackTrace();
fail();
} else {
pass();
}
} finally {
if (!shutItDown(ctx)) fail();
}
public void fail() {
throw new RuntimeException("Test failed");
}
boolean shutItDown(InitialContext ctx) {
@ -177,18 +92,376 @@ public class LdapTimeoutTest {
}
}
static class Server extends Thread {
final ServerSocket serverSock;
public Boolean call() {
InitialContext ctx = null;
ScheduledFuture killer = null;
long start = System.nanoTime();
Server(ServerSocket serverSock) {
this.serverSock = serverSock;
}
try {
while(!server.accepting())
Thread.sleep(200); // allow the server to start up
Thread.sleep(200); // to be sure
// if this is a hanging test, scheduled a thread to
// interrupt after a certain time
if (killSwitchPool != null) {
final Thread current = Thread.currentThread();
killer = killSwitchPool.schedule(
new Callable<Void>() {
public Void call() throws Exception {
current.interrupt();
return null;
}
}, HANGING_TEST_TIMEOUT, MILLISECONDS);
}
env.put(Context.PROVIDER_URL, "ldap://localhost:" +
server.getLocalPort());
public void run() {
try {
Socket socket = serverSock.accept();
} catch (IOException e) {}
ctx = new InitialDirContext(env);
performOp(ctx);
fail();
} catch (NamingException e) {
long end = System.nanoTime();
System.out.println(this.getClass().toString() + " - elapsed: "
+ NANOSECONDS.toMillis(end - start));
handleNamingException(e, start, end);
} finally {
if (killer != null && !killer.isDone())
killer.cancel(true);
shutItDown(ctx);
server.close();
}
return passed;
} catch (IOException|InterruptedException e) {
throw new RuntimeException(e);
}
}
}
abstract class ReadServerTest extends LdapTest {
public ReadServerTest(Hashtable env) throws IOException {
super(new BindableServer(), env);
}
public ReadServerTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(new BindableServer(), env, killSwitchPool);
}
public void performOp(InitialContext ctx) throws NamingException {
SearchControls scl = new SearchControls();
scl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = ((InitialDirContext)ctx)
.search("ou=People,o=JNDITutorial", "(objectClass=*)", scl);
}
}
abstract class DeadServerTest extends LdapTest {
public DeadServerTest(Hashtable env) throws IOException {
super(new DeadServer(), env);
}
public DeadServerTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(new DeadServer(), env, killSwitchPool);
}
public void performOp(InitialContext ctx) throws NamingException {}
}
class DeadServerNoTimeoutTest extends DeadServerTest {
public DeadServerNoTimeoutTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(env, killSwitchPool);
}
public void handleNamingException(NamingException e, long start, long end) {
if (e instanceof InterruptedNamingException) Thread.interrupted();
if (NANOSECONDS.toMillis(end - start) < LdapTimeoutTest.MIN_TIMEOUT) {
System.err.printf("DeadServerNoTimeoutTest fail: timeout should be " +
"at least %s ms, actual time is %s ms%n",
LdapTimeoutTest.MIN_TIMEOUT,
NANOSECONDS.toMillis(end - start));
fail();
} else {
pass();
}
}
}
class DeadServerTimeoutTest extends DeadServerTest {
public DeadServerTimeoutTest(Hashtable env) throws IOException {
super(env);
}
public void handleNamingException(NamingException e, long start, long end)
{
// non SSL connect will timeout via readReply using connectTimeout
if (NANOSECONDS.toMillis(end - start) < 2_900) {
pass();
} else {
System.err.println("Fail: Waited too long");
fail();
}
}
}
class DeadServerTimeoutSSLTest extends DeadServerTest {
public DeadServerTimeoutSSLTest(Hashtable env) throws IOException {
super(env);
}
public void handleNamingException(NamingException e, long start, long end) {
if (e.getCause() instanceof SocketTimeoutException) {
// SSL connect will timeout via readReply using
// SocketTimeoutException
pass();
} else {
fail();
}
}
}
class ReadServerNoTimeoutTest extends ReadServerTest {
public ReadServerNoTimeoutTest(Hashtable env,
ScheduledExecutorService killSwitchPool)
throws IOException
{
super(env, killSwitchPool);
}
public void handleNamingException(NamingException e, long start, long end) {
if (e instanceof InterruptedNamingException) Thread.interrupted();
if (NANOSECONDS.toMillis(end - start) < LdapTimeoutTest.MIN_TIMEOUT) {
System.err.printf("ReadServerNoTimeoutTest fail: timeout should be " +
"at least %s ms, actual time is %s ms%n",
LdapTimeoutTest.MIN_TIMEOUT,
NANOSECONDS.toMillis(end - start));
fail();
} else {
pass();
}
}
}
class ReadServerTimeoutTest extends ReadServerTest {
public ReadServerTimeoutTest(Hashtable env) throws IOException {
super(env);
}
public void handleNamingException(NamingException e, long start, long end) {
if (NANOSECONDS.toMillis(end - start) < 2_900) {
fail();
} else {
pass();
}
}
}
class TestServer extends Thread {
ServerSocket serverSock;
boolean accepting = false;
public TestServer() throws IOException {
this.serverSock = new ServerSocket(0);
start();
}
public int getLocalPort() {
return serverSock.getLocalPort();
}
public boolean accepting() {
return accepting;
}
public void close() throws IOException {
serverSock.close();
}
}
class BindableServer extends TestServer {
public BindableServer() throws IOException {
super();
}
private byte[] bindResponse = {
0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
0x01, 0x00, 0x04, 0x00, 0x04, 0x00
};
public void run() {
try {
accepting = true;
Socket socket = serverSock.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Read the LDAP BindRequest
while (in.read() != -1) {
in.skip(in.available());
break;
}
// Write an LDAP BindResponse
out.write(bindResponse);
out.flush();
} catch (IOException e) {
// ignore
}
}
}
class DeadServer extends TestServer {
public DeadServer() throws IOException {
super();
}
public void run() {
while(true) {
try {
accepting = true;
Socket socket = serverSock.accept();
} catch (Exception e) {
break;
}
}
}
}
public class LdapTimeoutTest {
private static final ExecutorService testPool =
Executors.newFixedThreadPool(3);
private static final ScheduledExecutorService killSwitchPool =
Executors.newScheduledThreadPool(3);
public static int MIN_TIMEOUT = 18_000;
static Hashtable createEnv() {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
return env;
}
public static void main(String[] args) throws Exception {
InitialContext ctx = null;
List<Future> results = new ArrayList<>();
try {
// run the DeadServerTest with no timeouts set
// this should get stuck indefinitely, so we need to kill
// it after a timeout
System.out.println("Running connect timeout test with 20s kill switch");
Hashtable env = createEnv();
results.add(
testPool.submit(new DeadServerNoTimeoutTest(env, killSwitchPool)));
// run the ReadServerTest with connect timeout set
// this should get stuck indefinitely so we need to kill
// it after a timeout
System.out.println("Running read timeout test with 10ms connect timeout & 20s kill switch");
Hashtable env1 = createEnv();
env1.put("com.sun.jndi.ldap.connect.timeout", "10");
results.add(testPool.submit(
new ReadServerNoTimeoutTest(env1, killSwitchPool)));
// run the ReadServerTest with no timeouts set
// this should get stuck indefinitely, so we need to kill
// it after a timeout
System.out.println("Running read timeout test with 20s kill switch");
Hashtable env2 = createEnv();
results.add(testPool.submit(
new ReadServerNoTimeoutTest(env2, killSwitchPool)));
// run the DeadServerTest with connect / read timeouts set
// this should exit after the connect timeout expires
System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout");
Hashtable env3 = createEnv();
env3.put("com.sun.jndi.ldap.connect.timeout", "10");
env3.put("com.sun.jndi.ldap.read.timeout", "3000");
results.add(testPool.submit(new DeadServerTimeoutTest(env3)));
// run the ReadServerTest with connect / read timeouts set
// this should exit after the connect timeout expires
System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
Hashtable env4 = createEnv();
env4.put("com.sun.jndi.ldap.connect.timeout", "10");
env4.put("com.sun.jndi.ldap.read.timeout", "3000");
results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
// run the DeadServerTest with connect timeout set
// this should exit after the connect timeout expires
System.out.println("Running connect timeout test with 10ms connect timeout");
Hashtable env5 = createEnv();
env5.put("com.sun.jndi.ldap.connect.timeout", "10");
results.add(testPool.submit(new DeadServerTimeoutTest(env5)));
// 8000487: Java JNDI connection library on ldap conn is
// not honoring configured timeout
System.out.println("Running simple auth connection test");
Hashtable env6 = createEnv();
env6.put("com.sun.jndi.ldap.connect.timeout", "10");
env6.put("com.sun.jndi.ldap.read.timeout", "3000");
env6.put(Context.SECURITY_AUTHENTICATION, "simple");
env6.put(Context.SECURITY_PRINCIPAL, "user");
env6.put(Context.SECURITY_CREDENTIALS, "password");
results.add(testPool.submit(new DeadServerTimeoutTest(env6)));
boolean testFailed = false;
for (Future test : results) {
while (!test.isDone()) {
if ((Boolean) test.get() == false)
testFailed = true;
}
}
//
// Running this test serially as it seems to tickle a problem
// on older kernels
//
// run the DeadServerTest with connect / read timeouts set
// and ssl enabled
// this should exit with a SocketTimeoutException as the root cause
// it should also use the connect timeout instead of the read timeout
System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout & SSL");
Hashtable sslenv = createEnv();
sslenv.put("com.sun.jndi.ldap.connect.timeout", "10");
sslenv.put("com.sun.jndi.ldap.read.timeout", "3000");
sslenv.put(Context.SECURITY_PROTOCOL, "ssl");
testFailed = (new DeadServerTimeoutSSLTest(sslenv).call()) ? false : true;
if (testFailed) {
throw new AssertionError("some tests failed");
}
} finally {
LdapTimeoutTest.killSwitchPool.shutdown();
LdapTimeoutTest.testPool.shutdown();
}
}
}

View File

@ -32,21 +32,36 @@ import sun.invoke.util.Wrapper;
*/
public class ExplicitCastArgumentsTest {
private static final boolean VERBOSE = Boolean.getBoolean("verbose");
private static final Class<?> THIS_CLASS = ExplicitCastArgumentsTest.class;
public static void main(String[] args) throws Throwable {
testVarargsCollector();
testRef2Prim();
System.out.println("TEST PASSED");
}
public static String[] f(String... args) { return args; }
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"}));
}
public static void testRef2Prim() throws Throwable {
for (Wrapper from : Wrapper.values()) {
for (Wrapper to : Wrapper.values()) {
if (from == Wrapper.VOID || to == Wrapper.VOID) continue;
testRef2Prim (from, to);
testRef2Prim(from, to);
}
}
System.out.println("TEST PASSED");
}
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);
test(from.wrapperType(), to.primitiveType(), null, false);
}
public static void test(Class<?> from, Class<?> to, Object param, boolean failureExpected) throws Throwable {

View File

@ -26,7 +26,6 @@
* @bug 8046703
* @summary Test verifies that lambda forms are garbage collected
* @author kshefov
* @ignore 8057020
* @library /lib/testlibrary/jsr292 /lib/testlibrary
* @build TestMethods
* @build LambdaFormTestCase

View File

@ -31,6 +31,7 @@ import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import jdk.testlibrary.Utils;
import jdk.testlibrary.TimeLimitedRunner;
/**
* Lambda forms caching test case class. Contains all necessary test routines to
@ -45,7 +46,7 @@ public abstract class LambdaFormTestCase {
private final static String INTERNAL_FORM_METHOD_NAME = "internalForm";
private static final double ITERATIONS_TO_CODE_CACHE_SIZE_RATIO
= 45 / (128.0 * 1024 * 1024);
private static final long TIMEOUT = Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT);
private static final long TIMEOUT = Helper.IS_THOROUGH ? 0L : (long) (Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT) * 0.9);
/**
* Reflection link to {@code j.l.i.MethodHandle.internalForm} method. It is
@ -68,13 +69,98 @@ public abstract class LambdaFormTestCase {
}
gcInfo = ManagementFactory.getGarbageCollectorMXBeans();
if (gcInfo.size() == 0) {
if (gcInfo.size() == 0) {
throw new Error("No GarbageCollectorMXBeans found.");
}
}
private final TestMethods testMethod;
private long gcCountAtStart;
private static class TestRun {
final Function<TestMethods, LambdaFormTestCase> ctor;
final Collection<TestMethods> testMethods;
final long totalIterations;
long doneIterations;
long testCounter;
long failCounter;
boolean passed;
TestRun(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
this.ctor = ctor;
this.testMethods = testMethods;
long testCaseNum = testMethods.size();
long iterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
iterations, iterations * testCaseNum);
HotSpotDiagnosticMXBean hsDiagBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
long codeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("ReservedCodeCacheSize").getValue());
System.out.printf("Code cache size is %d bytes%n", codeCacheSize);
long iterationsByCodeCacheSize = (long) (codeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
long nonProfiledCodeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("NonProfiledCodeHeapSize").getValue());
System.out.printf("Non-profiled code cache size is %d bytes%n", nonProfiledCodeCacheSize);
long iterationsByNonProfiledCodeCacheSize = (long) (nonProfiledCodeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
System.out.printf("Number of iterations limited by code cache size is %d (%d cases)%n",
iterationsByCodeCacheSize, iterationsByCodeCacheSize * testCaseNum);
System.out.printf("Number of iterations limited by non-profiled code cache size is %d (%d cases)%n",
iterationsByNonProfiledCodeCacheSize, iterationsByNonProfiledCodeCacheSize * testCaseNum);
iterations = Math.min(iterationsByCodeCacheSize,
Math.min(iterations, iterationsByNonProfiledCodeCacheSize));
if (iterations == 0) {
System.out.println("Warning: code cache size is too small to provide at"
+ " least one iteration! Test will try to do one iteration.");
iterations = 1;
}
System.out.printf("Number of iterations is set to %d (%d cases)%n",
iterations, iterations * testCaseNum);
System.out.flush();
totalIterations = iterations;
doneIterations = 0L;
testCounter = 0L;
failCounter = 0L;
passed = true;
}
Boolean doIteration() {
if (doneIterations >= totalIterations) {
return false;
}
System.err.println(String.format("Iteration %d:", doneIterations));
for (TestMethods testMethod : testMethods) {
LambdaFormTestCase testCase = ctor.apply(testMethod);
try {
System.err.printf("Tested LF caching feature with MethodHandles.%s method.%n",
testCase.getTestMethod().name);
testCase.doTest();
System.err.println("PASSED");
} catch (Throwable t) {
t.printStackTrace();
System.err.printf("FAILED. Caused by %s%n", t.getMessage());
passed = false;
failCounter++;
}
testCounter++;
}
doneIterations++;
return true;
}
void checkPassed() {
if (!passed) {
throw new Error(String.format("%d of %d test cases FAILED! %n"
+ "Rerun the test with the same \"-Dseed=\" option as in the log file!",
failCounter, testCounter));
} else {
System.err.printf("All %d test cases PASSED!%n", testCounter);
}
}
}
/**
* Test case constructor. Generates test cases with random method types for
* given methods form {@code j.l.i.MethodHandles} class.
@ -108,71 +194,15 @@ public abstract class LambdaFormTestCase {
* @param testMethods list of test methods
*/
public static void runTests(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
boolean passed = true;
int testCounter = 0;
int failCounter = 0;
long testCaseNum = testMethods.size();
long iterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
iterations, iterations * testCaseNum);
HotSpotDiagnosticMXBean hsDiagBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
long codeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("ReservedCodeCacheSize").getValue());
System.out.printf("Code cache size is %d bytes%n", codeCacheSize);
long iterationsByCodeCacheSize = (long) (codeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
long nonProfiledCodeCacheSize = Long.parseLong(
hsDiagBean.getVMOption("NonProfiledCodeHeapSize").getValue());
System.out.printf("Non-profiled code cache size is %d bytes%n", nonProfiledCodeCacheSize);
long iterationsByNonProfiledCodeCacheSize = (long) (nonProfiledCodeCacheSize
* ITERATIONS_TO_CODE_CACHE_SIZE_RATIO);
System.out.printf("Number of iterations limited by code cache size is %d (%d cases)%n",
iterationsByCodeCacheSize, iterationsByCodeCacheSize * testCaseNum);
System.out.printf("Number of iterations limited by non-profiled code cache size is %d (%d cases)%n",
iterationsByNonProfiledCodeCacheSize, iterationsByNonProfiledCodeCacheSize * testCaseNum);
iterations = Math.min(iterationsByCodeCacheSize,
Math.min(iterations, iterationsByNonProfiledCodeCacheSize));
if (iterations == 0) {
System.out.println("Warning: code cache size is too small to provide at"
+ " least one iteration! Test will try to do one iteration.");
iterations = 1;
}
System.out.printf("Number of iterations is set to %d (%d cases)%n",
iterations, iterations * testCaseNum);
System.out.flush();
long startTime = System.currentTimeMillis();
for (long i = 0; i < iterations; i++) {
System.err.println(String.format("Iteration %d:", i));
for (TestMethods testMethod : testMethods) {
LambdaFormTestCase testCase = ctor.apply(testMethod);
try {
System.err.printf("Tested LF caching feature with MethodHandles.%s method.%n",
testCase.getTestMethod().name);
testCase.doTest();
System.err.println("PASSED");
} catch (Throwable t) {
t.printStackTrace();
System.err.println("FAILED");
passed = false;
failCounter++;
}
testCounter++;
}
long passedTime = System.currentTimeMillis() - startTime;
long avgIterTime = passedTime / (i + 1);
long remainTime = TIMEOUT - passedTime;
if (avgIterTime > 2 * remainTime) {
System.err.printf("Stopping iterations because of lack of time.%n"
+ "Increase timeout factor for more iterations.%n");
break;
}
}
if (!passed) {
throw new Error(String.format("%d of %d test cases FAILED! %n"
+ "Rerun the test with the same \"-Dseed=\" option as in the log file!",
failCounter, testCounter));
} else {
System.err.println(String.format("All %d test cases PASSED!", testCounter));
LambdaFormTestCase.TestRun run =
new LambdaFormTestCase.TestRun(ctor, testMethods);
TimeLimitedRunner runner = new TimeLimitedRunner(TIMEOUT, 4.0d, run::doIteration);
try {
runner.call();
} catch (Exception ex) {
System.err.println("FAILED");
throw new Error("Unexpected error!", ex);
}
run.checkPassed();
}
}

View File

@ -24,6 +24,8 @@
/* @test
* @bug 4652496
* @summary Test transferTo with different target channels
* @run main TransferToChannel
* @run main/othervm -Djdk.net.enableFastFileTransfer TransferToChannel
*/
import java.nio.channels.FileChannel;

View File

@ -22,7 +22,7 @@
*/
/* @test
* @bug 4313887
* @bug 4313887 8066915
* @summary Unit test for java.nio.file.Files.newByteChannel
* @library ..
*/
@ -59,6 +59,7 @@ public class SBC {
dosSharingOptionTests(dir);
// misc. tests
directoryOpenTests(dir);
badCombinations(dir);
unsupportedOptions(dir);
nullTests(dir);
@ -278,6 +279,21 @@ public class SBC {
}
}
// test opening a directory for read or write
static void directoryOpenTests(Path dir) throws Exception {
try (SeekableByteChannel sbc = Files.newByteChannel(dir, READ)) {
throw new RuntimeException("Opened directory for read");
} catch (IOException expected) { }
try (SeekableByteChannel sbc = Files.newByteChannel(dir, WRITE)) {
throw new RuntimeException("Opened directory for write");
} catch (IOException expected) { }
try (SeekableByteChannel sbc = Files.newByteChannel(dir, APPEND)) {
throw new RuntimeException("Opened directory for append ");
} catch (IOException expected) { }
}
// Windows specific options for the use by applications that really want
// to use legacy DOS sharing options
static void dosSharingOptionTests(Path dir) throws Exception {

View File

@ -34,6 +34,8 @@ import java.util.concurrent.TimeoutException;
*/
public class JavaVM {
public static final long POLLTIME_MS = 100L;
protected Process vm = null;
private String classname = "";
@ -192,23 +194,21 @@ public class JavaVM {
throws InterruptedException, TimeoutException {
if (vm == null)
throw new IllegalStateException("can't wait for JavaVM that isn't running");
long startTime = System.currentTimeMillis();
long rem = timeout;
long deadline = computeDeadline(System.currentTimeMillis(), timeout);
do {
while (true) {
try {
int status = vm.exitValue();
outPipe.join();
errPipe.join();
return status;
} catch (IllegalThreadStateException ex) {
if (rem > 0) {
Thread.sleep(Math.min(rem, 100));
}
}
rem = timeout - (System.currentTimeMillis() - startTime);
} while (rem > 0);
throw new TimeoutException();
} catch (IllegalThreadStateException ignore) { }
if (System.currentTimeMillis() > deadline)
throw new TimeoutException();
Thread.sleep(POLLTIME_MS);
}
}
/**
@ -218,4 +218,21 @@ public class JavaVM {
start();
return waitFor();
}
/**
* Computes a deadline from a timestamp and a timeout value.
* Maximum timeout (before multipliers are applied) is one hour.
*/
public static long computeDeadline(long timestamp, long timeout) {
final long MAX_TIMEOUT_MS = 3_600_000L;
if (timeout < 0L || timeout > MAX_TIMEOUT_MS) {
throw new IllegalArgumentException("timeout " + timeout + "ms out of range");
}
// TODO apply test.timeout.factor (and possibly jcov.sleep.multiplier)
// here instead of upstream
return timestamp + timeout;
}
}

Some files were not shown because too many files have changed in this diff Show More