This commit is contained in:
Jesper Wilhelmsson 2017-12-08 23:43:25 +01:00
commit 42d9cdb7a0
40 changed files with 1035 additions and 471 deletions
.hgtags
make/conf
src
java.base
share/classes
unix/native/libnio/fs
java.logging/share/classes/java/util/logging
jdk.dynalink/share/classes/jdk/dynalink/beans
jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit
jdk.jdi/share/native/libdt_shmem
jdk.jlink/share/classes/jdk/tools/jlink/internal
jdk.jshell/share/classes/jdk/jshell
jdk.scripting.nashorn/share/classes/jdk/nashorn/tools
test
jdk
java
lang/module
nio/file/Files
util/logging/LogManager/Configuration/rootLoggerHandlers
sun/security/tools/keytool
tools/jlink
langtools
nashorn
script/nosecurity
src/jdk/dynalink/beans/test

@ -459,3 +459,4 @@ e6278add9ff28fab70fe1cc4c1d65f7363dc9445 jdk-10+31
a2008587c13fa05fa2dbfcb09fe987576fbedfd1 jdk-10+32
bbd692ad4fa300ecca7939ffbe3b1d5e52a28cc6 jdk-10+33
89deac44e51517841491ba86ff44aa82a5ca96b3 jdk-10+34
d8c634b016c628622c9abbdc6bf50509e5dedbec jdk-10+35

@ -662,6 +662,16 @@ var getJibProfilesProfiles = function (input, common, data) {
}
});
// For open profiles, the non-debug jdk bundles, need an "open" prefix on the
// remote bundle names, forming the word "openjdk". See JDK-8188789.
common.main_profile_names.forEach(function (name) {
var openName = name + common.open_suffix;
profiles[openName].artifacts["jdk"].remote = replaceAll(
"\/jdk-", "/openjdk-",
replaceAll("\/\\1", "/open\\1",
profiles[openName].artifacts["jdk"].remote));
});
// Profiles used to run tests. Used in JPRT and Mach 5.
var testOnlyProfiles = {
"run-test-jprt": {

@ -38,6 +38,7 @@ import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
@ -45,7 +46,6 @@ import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
@ -2496,7 +2496,7 @@ public abstract class ClassLoader {
}
// native libraries being loaded
static Deque<NativeLibrary> nativeLibraryContext = new LinkedList<>();
static Deque<NativeLibrary> nativeLibraryContext = new ArrayDeque<>(8);
/*
* The run() method will be invoked when this class loader becomes

@ -876,62 +876,6 @@ public class Runtime {
ClassLoader.loadLibrary(fromClass, libname, false);
}
/**
* Creates a localized version of an input stream. This method takes
* an {@code InputStream} and returns an {@code InputStream}
* equivalent to the argument in all respects except that it is
* localized: as characters in the local character set are read from
* the stream, they are automatically converted from the local
* character set to Unicode.
* <p>
* If the argument is already a localized stream, it may be returned
* as the result.
*
* @param in InputStream to localize
* @return a localized input stream
* @see java.io.InputStream
* @see java.io.BufferedReader#BufferedReader(java.io.Reader)
* @see java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
* @deprecated As of JDK&nbsp;1.1, the preferred way to translate a byte
* stream in the local encoding into a character stream in Unicode is via
* the {@code InputStreamReader} and {@code BufferedReader}
* classes.
* This method is subject to removal in a future version of Java SE.
*/
@Deprecated(since="1.1", forRemoval=true)
public InputStream getLocalizedInputStream(InputStream in) {
return in;
}
/**
* Creates a localized version of an output stream. This method
* takes an {@code OutputStream} and returns an
* {@code OutputStream} equivalent to the argument in all respects
* except that it is localized: as Unicode characters are written to
* the stream, they are automatically converted to the local
* character set.
* <p>
* If the argument is already a localized stream, it may be returned
* as the result.
*
* @deprecated As of JDK&nbsp;1.1, the preferred way to translate a
* Unicode character stream into a byte stream in the local encoding is via
* the {@code OutputStreamWriter}, {@code BufferedWriter}, and
* {@code PrintWriter} classes.
* This method is subject to removal in a future version of Java SE.
*
* @param out OutputStream to localize
* @return a localized output stream
* @see java.io.OutputStream
* @see java.io.BufferedWriter#BufferedWriter(java.io.Writer)
* @see java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
* @see java.io.PrintWriter#PrintWriter(java.io.OutputStream)
*/
@Deprecated(since="1.1", forRemoval=true)
public OutputStream getLocalizedOutputStream(OutputStream out) {
return out;
}
/**
* Returns the version of the Java Runtime Environment as a {@link Version}.
*

@ -25,15 +25,13 @@
package java.security;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.WeakHashMap;
import jdk.internal.misc.JavaSecurityAccess;
import jdk.internal.misc.JavaSecurityProtectionDomainAccess;
import static jdk.internal.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
@ -115,23 +113,10 @@ public class ProtectionDomain {
}
static {
// setup SharedSecrets to allow access to doIntersectionPrivilege
// methods and ProtectionDomain cache
// Set up JavaSecurityAccess in SharedSecrets
SharedSecrets.setJavaSecurityAccess(new JavaSecurityAccessImpl());
SharedSecrets.setJavaSecurityProtectionDomainAccess(
new JavaSecurityProtectionDomainAccess() {
@Override
public ProtectionDomainCache getProtectionDomainCache() {
return new PDCache();
}
});
}
/**
* Used for storing ProtectionDomains as keys in a Map.
*/
static final class Key {}
/* CodeSource */
private CodeSource codesource ;
@ -571,117 +556,27 @@ public class ProtectionDomain {
}
/**
* A cache of ProtectionDomains and their Permissions.
*
* This class stores ProtectionDomains as weak keys in a ConcurrentHashMap
* with additional support for checking and removing weak keys that are no
* longer in use. There can be cases where the permission collection may
* have a chain of strong references back to the ProtectionDomain, which
* ordinarily would prevent the entry from being removed from the map. To
* address that, we wrap the permission collection in a SoftReference so
* that it can be reclaimed by the garbage collector due to memory demand.
* Used for storing ProtectionDomains as keys in a Map.
*/
private static class PDCache implements ProtectionDomainCache {
private final ConcurrentHashMap<WeakProtectionDomainKey,
SoftReference<PermissionCollection>>
pdMap = new ConcurrentHashMap<>();
private final ReferenceQueue<Key> queue = new ReferenceQueue<>();
final class Key {}
@Override
public void put(ProtectionDomain pd, PermissionCollection pc) {
processQueue(queue, pdMap);
WeakProtectionDomainKey weakPd =
new WeakProtectionDomainKey(pd, queue);
pdMap.put(weakPd, new SoftReference<>(pc));
}
@Override
public PermissionCollection get(ProtectionDomain pd) {
processQueue(queue, pdMap);
WeakProtectionDomainKey weakPd = new WeakProtectionDomainKey(pd);
SoftReference<PermissionCollection> sr = pdMap.get(weakPd);
return (sr == null) ? null : sr.get();
}
/**
* Removes weak keys from the map that have been enqueued
* on the reference queue and are no longer in use.
*/
private static void processQueue(ReferenceQueue<Key> queue,
ConcurrentHashMap<? extends
WeakReference<Key>, ?> pdMap) {
Reference<? extends Key> ref;
while ((ref = queue.poll()) != null) {
pdMap.remove(ref);
}
}
}
/**
* A weak key for a ProtectionDomain.
*/
private static class WeakProtectionDomainKey extends WeakReference<Key> {
/**
* Saved value of the referent's identity hash code, to maintain
* a consistent hash code after the referent has been cleared
*/
private final int hash;
/**
* A key representing a null ProtectionDomain.
*/
private static final Key NULL_KEY = new Key();
/**
* Create a new WeakProtectionDomain with the specified domain and
* registered with a queue.
*/
WeakProtectionDomainKey(ProtectionDomain pd, ReferenceQueue<Key> rq) {
this((pd == null ? NULL_KEY : pd.key), rq);
}
WeakProtectionDomainKey(ProtectionDomain pd) {
this(pd == null ? NULL_KEY : pd.key);
}
private WeakProtectionDomainKey(Key key, ReferenceQueue<Key> rq) {
super(key, rq);
hash = key.hashCode();
}
private WeakProtectionDomainKey(Key key) {
super(key);
hash = key.hashCode();
}
/**
* Returns the identity hash code of the original referent.
*/
@Override
public int hashCode() {
return hash;
}
/**
* Returns true if the given object is an identical
* WeakProtectionDomainKey instance, or, if this object's referent
* has not been cleared and the given object is another
* WeakProtectionDomainKey instance with an identical non-null
* referent as this one.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof WeakProtectionDomainKey) {
Object referent = get();
return (referent != null) &&
(referent == ((WeakProtectionDomainKey)obj).get());
} else {
return false;
}
}
static {
SharedSecrets.setJavaSecurityProtectionDomainAccess(
new JavaSecurityProtectionDomainAccess() {
public ProtectionDomainCache getProtectionDomainCache() {
return new ProtectionDomainCache() {
private final Map<Key, PermissionCollection> map =
Collections.synchronizedMap
(new WeakHashMap<Key, PermissionCollection>());
public void put(ProtectionDomain pd,
PermissionCollection pc) {
map.put((pd == null ? null : pd.key), pc);
}
public PermissionCollection get(ProtectionDomain pd) {
return pd == null ? map.get(null) : map.get(pd.key);
}
};
}
});
}
}

@ -63,6 +63,9 @@ import static jdk.internal.module.ClassFileConstants.*;
public final class ModuleInfo {
private final int JAVA_MIN_SUPPORTED_VERSION = 53;
private final int JAVA_MAX_SUPPORTED_VERSION = 54;
private static final JavaLangModuleAccess JLMA
= SharedSecrets.getJavaLangModuleAccess();
@ -188,8 +191,10 @@ public final class ModuleInfo {
int minor_version = in.readUnsignedShort();
int major_version = in.readUnsignedShort();
if (major_version < 53) {
throw invalidModuleDescriptor("Must be >= 53.0");
if (major_version < JAVA_MIN_SUPPORTED_VERSION ||
major_version > JAVA_MAX_SUPPORTED_VERSION) {
throw invalidModuleDescriptor("Unsupported major.minor version "
+ major_version + "." + minor_version);
}
ConstantPool cpool = new ConstantPool(in);
@ -245,7 +250,7 @@ public final class ModuleInfo {
switch (attribute_name) {
case MODULE :
builder = readModuleAttribute(in, cpool);
builder = readModuleAttribute(in, cpool, major_version);
break;
case MODULE_PACKAGES :
@ -334,7 +339,7 @@ public final class ModuleInfo {
* Reads the Module attribute, returning the ModuleDescriptor.Builder to
* build the corresponding ModuleDescriptor.
*/
private Builder readModuleAttribute(DataInput in, ConstantPool cpool)
private Builder readModuleAttribute(DataInput in, ConstantPool cpool, int major)
throws IOException
{
// module_name
@ -390,8 +395,21 @@ public final class ModuleInfo {
JLMA.requires(builder, mods, dn, vs);
}
if (dn.equals("java.base"))
if (dn.equals("java.base")) {
if (major >= 54
&& (mods.contains(Requires.Modifier.TRANSITIVE)
|| mods.contains(Requires.Modifier.STATIC))) {
String flagName;
if (mods.contains(Requires.Modifier.TRANSITIVE)) {
flagName = "ACC_TRANSITIVE";
} else {
flagName = "ACC_STATIC_PHASE";
}
throw invalidModuleDescriptor("The requires entry for java.base"
+ " has " + flagName + " set");
}
requiresJavaBase = true;
}
}
if (mn.equals("java.base")) {
if (requires_count > 0) {

@ -80,7 +80,7 @@ public final class ModuleInfoWriter {
*/
private static byte[] toModuleInfo(ModuleDescriptor md, ModuleTarget target) {
ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V9, ACC_MODULE, "module-info", null, null, null);
cw.visit(Opcodes.V10, ACC_MODULE, "module-info", null, null, null);
int moduleFlags = md.modifiers().stream()
.map(MODULE_MODS_TO_FLAGS::get)

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -93,8 +93,9 @@ public class KeyStoreUtil {
* MSCAPI KeyStores
*/
public static boolean isWindowsKeyStore(String storetype) {
return storetype.equalsIgnoreCase("Windows-MY")
|| storetype.equalsIgnoreCase("Windows-ROOT");
return storetype != null
&& (storetype.equalsIgnoreCase("Windows-MY")
|| storetype.equalsIgnoreCase("Windows-ROOT"));
}
/**

@ -134,8 +134,6 @@ public final class Main {
private Set<Pair <String, String>> providers = null;
private Set<Pair <String, String>> providerClasses = null;
private String storetype = null;
private boolean hasStoretypeOption = false;
private boolean hasSrcStoretypeOption = false;
private String srcProviderName = null;
private String providerName = null;
private String pathlist = null;
@ -549,14 +547,12 @@ public final class Main {
passwords.add(storePass);
} else if (collator.compare(flags, "-storetype") == 0 ||
collator.compare(flags, "-deststoretype") == 0) {
storetype = args[++i];
hasStoretypeOption = true;
storetype = KeyStoreUtil.niceStoreTypeName(args[++i]);
} else if (collator.compare(flags, "-srcstorepass") == 0) {
srcstorePass = getPass(modifier, args[++i]);
passwords.add(srcstorePass);
} else if (collator.compare(flags, "-srcstoretype") == 0) {
srcstoretype = args[++i];
hasSrcStoretypeOption = true;
srcstoretype = KeyStoreUtil.niceStoreTypeName(args[++i]);
} else if (collator.compare(flags, "-srckeypass") == 0) {
srckeyPass = getPass(modifier, args[++i]);
passwords.add(srckeyPass);
@ -708,16 +704,6 @@ public final class Main {
ksfname = KeyStoreUtil.getCacerts();
}
if (storetype == null) {
storetype = KeyStore.getDefaultType();
}
storetype = KeyStoreUtil.niceStoreTypeName(storetype);
if (srcstoretype == null) {
srcstoretype = KeyStore.getDefaultType();
}
srcstoretype = KeyStoreUtil.niceStoreTypeName(srcstoretype);
if (P11KEYSTORE.equalsIgnoreCase(storetype) ||
KeyStoreUtil.isWindowsKeyStore(storetype)) {
token = true;
@ -742,11 +728,6 @@ public final class Main {
(".storepasswd.and.keypasswd.commands.not.supported.if.storetype.is.{0}"), storetype));
}
if (P12KEYSTORE.equalsIgnoreCase(storetype) && command == KEYPASSWD) {
throw new UnsupportedOperationException(rb.getString
(".keypasswd.commands.not.supported.if.storetype.is.PKCS12"));
}
if (token && (keyPass != null || newPass != null || destKeyPass != null)) {
throw new IllegalArgumentException(MessageFormat.format(rb.getString
(".keypass.and.new.can.not.be.specified.if.storetype.is.{0}"), storetype));
@ -923,9 +904,13 @@ public final class Main {
// Create new keystore
// Probe for keystore type when filename is available
if (ksfile != null && ksStream != null && providerName == null &&
hasStoretypeOption == false && !inplaceImport) {
storetype == null && !inplaceImport) {
keyStore = KeyStore.getInstance(ksfile, storePass);
storetype = keyStore.getType();
} else {
if (storetype == null) {
storetype = KeyStore.getDefaultType();
}
if (providerName == null) {
keyStore = KeyStore.getInstance(storetype);
} else {
@ -964,6 +949,11 @@ public final class Main {
}
}
if (P12KEYSTORE.equalsIgnoreCase(storetype) && command == KEYPASSWD) {
throw new UnsupportedOperationException(rb.getString
(".keypasswd.commands.not.supported.if.storetype.is.PKCS12"));
}
// All commands that create or modify the keystore require a keystore
// password.
@ -2123,9 +2113,13 @@ public final class Main {
try {
// Probe for keystore type when filename is available
if (srcksfile != null && is != null && srcProviderName == null &&
hasSrcStoretypeOption == false) {
srcstoretype == null) {
store = KeyStore.getInstance(srcksfile, srcstorePass);
srcstoretype = store.getType();
} else {
if (srcstoretype == null) {
srcstoretype = KeyStore.getDefaultType();
}
if (srcProviderName == null) {
store = KeyStore.getInstance(srcstoretype);
} else {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -476,10 +476,14 @@ static void prepAttributes(JNIEnv* env, struct stat64* buf, jobject attrs) {
(*env)->SetLongField(env, attrs, attrs_st_birthtime_sec, (jlong)buf->st_birthtime);
#endif
#if (_POSIX_C_SOURCE >= 200809L) || defined(__solaris__)
#ifndef MACOSX
(*env)->SetLongField(env, attrs, attrs_st_atime_nsec, (jlong)buf->st_atim.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_mtime_nsec, (jlong)buf->st_mtim.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_ctime_nsec, (jlong)buf->st_ctim.tv_nsec);
#else
(*env)->SetLongField(env, attrs, attrs_st_atime_nsec, (jlong)buf->st_atimespec.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_mtime_nsec, (jlong)buf->st_mtimespec.tv_nsec);
(*env)->SetLongField(env, attrs, attrs_st_ctime_nsec, (jlong)buf->st_ctimespec.tv_nsec);
#endif
}

@ -388,15 +388,23 @@ public class LogManager {
// create root logger before reading primordial
// configuration - to ensure that it will be added
// before the global logger, and not after.
owner.rootLogger = owner.new RootLogger();
final Logger root = owner.rootLogger = owner.new RootLogger();
// Read configuration.
owner.readPrimordialConfiguration();
// Create and retain Logger for the root of the namespace.
owner.addLogger(owner.rootLogger);
if (!owner.rootLogger.isLevelInitialized()) {
owner.rootLogger.setLevel(defaultLevel);
owner.addLogger(root);
// For backward compatibility: add any handlers configured using
// ".handlers"
owner.createLoggerHandlers("", ".handlers")
.stream()
.forEach(root::addHandler);
// Initialize level if not yet initialized
if (!root.isLevelInitialized()) {
root.setLevel(defaultLevel);
}
// Adding the global Logger.
@ -1708,7 +1716,7 @@ public class LogManager {
* @param k a property key in the configuration
* @param previous the old configuration
* @param next the new configuration (modified by this function)
* @param remappingFunction the mapping function.
* @param mappingFunction the mapping function.
*/
static void merge(String k, Properties previous, Properties next,
BiFunction<String, String, String> mappingFunction) {

@ -205,9 +205,8 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
return nextComponent;
}
return guardComponentWithRangeCheck(gicact, linkerServices,
callSiteDescriptor, nextComponent, new Binder(linkerServices, callSiteType, typedName),
isFixedKey ? NULL_GETTER_1 : NULL_GETTER_2);
return guardComponentWithRangeCheck(gicact, callSiteType, nextComponent,
new Binder(linkerServices, callSiteType, typedName), isFixedKey ? NULL_GETTER_1 : NULL_GETTER_2);
}
private static class GuardedInvocationComponentAndCollectionType {
@ -276,21 +275,19 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
}
private static GuardedInvocationComponent guardComponentWithRangeCheck(
final GuardedInvocationComponentAndCollectionType gicact, final LinkerServices linkerServices,
final CallSiteDescriptor callSiteDescriptor, final GuardedInvocationComponent nextComponent, final Binder binder,
final MethodHandle noOp) {
final MethodType callSiteType = callSiteDescriptor.getMethodType();
final GuardedInvocationComponentAndCollectionType gicact, final MethodType callSiteType,
final GuardedInvocationComponent nextComponent, final Binder binder, final MethodHandle noOp) {
final MethodHandle checkGuard;
switch(gicact.collectionType) {
case LIST:
checkGuard = convertArgToNumber(RANGE_CHECK_LIST, linkerServices, callSiteDescriptor);
checkGuard = binder.convertArgToNumber(RANGE_CHECK_LIST);
break;
case MAP:
checkGuard = linkerServices.filterInternalObjects(CONTAINS_MAP);
checkGuard = binder.linkerServices.filterInternalObjects(CONTAINS_MAP);
break;
case ARRAY:
checkGuard = convertArgToNumber(RANGE_CHECK_ARRAY, linkerServices, callSiteDescriptor);
checkGuard = binder.convertArgToNumber(RANGE_CHECK_ARRAY);
break;
default:
throw new AssertionError();
@ -301,7 +298,7 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
if (nextComponent != null) {
finalNextComponent = nextComponent;
} else {
finalNextComponent = createGuardedInvocationComponentAsType(noOp, callSiteType, linkerServices);
finalNextComponent = createGuardedInvocationComponentAsType(noOp, callSiteType, binder.linkerServices);
}
final GuardedInvocationComponent gic = gicact.gic;
@ -377,18 +374,6 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
return intIndex;
}
private static MethodHandle convertArgToNumber(final MethodHandle mh, final LinkerServices ls, final CallSiteDescriptor desc) {
final Class<?> sourceType = desc.getMethodType().parameterType(1);
if(TypeUtilities.isMethodInvocationConvertible(sourceType, Number.class)) {
return mh;
} else if(ls.canConvert(sourceType, Number.class)) {
final MethodHandle converter = ls.getTypeConverter(sourceType, Number.class);
return MethodHandles.filterArguments(mh, 1, converter.asType(converter.type().changeReturnType(
mh.type().parameterType(1))));
}
return mh;
}
/**
* Contains methods to adapt an item getter/setter method handle to the requested type, optionally binding it to a
* fixed key first.
@ -412,6 +397,18 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
return bindToFixedKey(Guards.asType(handle, methodType));
}
/*private*/ MethodHandle convertArgToNumber(final MethodHandle mh) {
final Class<?> sourceType = methodType.parameterType(1);
if(TypeUtilities.isMethodInvocationConvertible(sourceType, Number.class)) {
return mh;
} else if(linkerServices.canConvert(sourceType, Number.class)) {
final MethodHandle converter = linkerServices.getTypeConverter(sourceType, Number.class);
return MethodHandles.filterArguments(mh, 1, converter.asType(converter.type().changeReturnType(
mh.type().parameterType(1))));
}
return mh;
}
private MethodHandle bindToFixedKey(final MethodHandle handle) {
return fixedKey == null ? handle : MethodHandles.insertArguments(handle, 1, fixedKey);
}
@ -506,8 +503,7 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL
return gic.replaceInvocation(binder.bind(invocation));
}
return guardComponentWithRangeCheck(gicact, linkerServices, callSiteDescriptor,
nextComponent, binder, isFixedKey ? NO_OP_SETTER_2 : NO_OP_SETTER_3);
return guardComponentWithRangeCheck(gicact, callSiteType, nextComponent, binder, isFixedKey ? NO_OP_SETTER_2 : NO_OP_SETTER_3);
}
private static final MethodHandle GET_COLLECTION_LENGTH = Lookup.PUBLIC.findVirtual(Collection.class, "size",

@ -25,11 +25,8 @@
package jdk.javadoc.internal.doclets.toolkit.taglets;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import com.sun.source.doctree.DocTree;
import jdk.javadoc.internal.doclets.toolkit.BaseConfiguration;
@ -121,60 +118,26 @@ public class ValueTaglet extends BaseInlineTaglet {
}
/**
* Given the name of the field, return the corresponding VariableElement. Return null
* due to invalid use of value tag if the name is null or empty string and if
* the value tag is not used on a field.
* Returns the referenced field or a null if the value tag
* is empty or the reference is invalid.
*
* @param holder the element holding the tag
* @param config the current configuration of the doclet.
* @param holder the tag holder.
* @param config the configuration of the doclet.
* @param tag the value tag.
*
* @return the corresponding VariableElement. If the name is null or empty string,
* return field that the value tag was used in. Return null if the name is null
* or empty string and if the value tag is not used on a field.
* @return the referenced field or null.
*/
private VariableElement getVariableElement(Element holder, BaseConfiguration config, DocTree tag) {
Utils utils = config.utils;
CommentHelper ch = utils.getCommentHelper(holder);
CommentHelper ch = config.utils.getCommentHelper(holder);
String signature = ch.getReferencedSignature(tag);
if (signature == null) { // no reference
//Base case: no label.
if (utils.isVariableElement(holder)) {
return (VariableElement)(holder);
} else {
// If the value tag does not specify a parameter which is a valid field and
// it is not used within the comments of a valid field, return null.
return null;
}
}
Element e = signature == null
? holder
: ch.getReferencedMember(config, tag);
String[] sigValues = signature.split("#");
String memberName = null;
TypeElement te = null;
if (sigValues.length == 1) {
//Case 2: @value in same class.
if (utils.isExecutableElement(holder) || utils.isVariableElement(holder)) {
te = utils.getEnclosingTypeElement(holder);
} else if (utils.isTypeElement(holder)) {
te = utils.getTopMostContainingTypeElement(holder);
}
memberName = sigValues[0];
} else {
//Case 3: @value in different class.
Elements elements = config.docEnv.getElementUtils();
te = elements.getTypeElement(sigValues[0]);
memberName = sigValues[1];
}
if (te == null) {
return null;
}
for (Element field : utils.getFields(te)) {
if (utils.getSimpleName(field).equals(memberName)) {
return (VariableElement)field;
}
}
return null;
return (e != null && config.utils.isVariableElement(e))
? (VariableElement) e
: null;
}
/**

@ -290,7 +290,7 @@ public class Group {
groupList.add(defaultGroupName);
}
for (PackageElement pkg : packages) {
String pkgName = pkg.isUnnamed() ? null : configuration.utils.getPackageName(pkg);
String pkgName = configuration.utils.getPackageName(pkg);
String groupName = pkg.isUnnamed() ? null : elementNameGroupMap.get(pkgName);
// if this package is not explicitly assigned to a group,
// try matching it to group specified by regular expression

@ -2365,9 +2365,6 @@ public class Utils {
List<Element> getItems(Element e, boolean filter, ElementKind select) {
List<Element> elements = new ArrayList<>();
// maintain backward compatibility by returning a null list, see AnnotationDocType.methods().
if (configuration.backwardCompatibility && e.getKind() == ANNOTATION_TYPE)
return elements;
return new SimpleElementVisitor9<List<Element>, Void>() {
@Override

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -31,6 +31,10 @@
#include "shmemBase.h"
#include "jdwpTransport.h" /* for Packet, TransportCallback */
#if defined(_WIN32)
#define PRId64 "I64d"
#endif
#define MIN(x,y) ((x)<(y)?(x):(y))
/*
@ -537,7 +541,7 @@ openConnection(SharedMemoryTransport *transport, jlong otherPID,
return SYS_NOMEM;
}
sprintf(connection->name, "%s.%ld", transport->name, sysProcessGetID());
sprintf(connection->name, "%s.%" PRId64, transport->name, sysProcessGetID());
error = sysSharedMemOpen(connection->name, &connection->sharedMemory,
&connection->shared);
if (error != SYS_OK) {
@ -601,7 +605,7 @@ createConnection(SharedMemoryTransport *transport, jlong otherPID,
return SYS_NOMEM;
}
sprintf(connection->name, "%s.%ld", transport->name, otherPID);
sprintf(connection->name, "%s.%" PRId64, transport->name, otherPID);
error = sysSharedMemCreate(connection->name, sizeof(SharedMemory),
&connection->sharedMemory, &connection->shared);
if (error != SYS_OK) {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -30,13 +30,16 @@ import jdk.tools.jlink.plugin.ResourcePoolModule;
import jdk.tools.jlink.plugin.ResourcePoolModuleView;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Requires;
import java.lang.module.ModuleDescriptor.Requires.Modifier;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
@ -45,9 +48,8 @@ import java.util.stream.Stream;
* Helper class to sort modules in topological order
*/
public final class ModuleSorter {
private final Deque<ResourcePoolModule> nodes = new LinkedList<>();
private final Map<String, Set<ResourcePoolModule>> edges = new HashMap<>();
private final Deque<ResourcePoolModule> result = new LinkedList<>();
private final Map<ResourcePoolModule, Set<ResourcePoolModule>> graph = new HashMap<>();
private final List<ResourcePoolModule> result = new ArrayList<>();
private final ResourcePoolModuleView moduleView;
@ -69,11 +71,17 @@ public final class ModuleSorter {
private ModuleSorter addModule(ResourcePoolModule module) {
addNode(module);
readModuleDescriptor(module).requires().forEach(req -> {
// the module graph will be traversed in a stable order for
// the topological sort. So add the dependences in the module name order
readModuleDescriptor(module).requires()
.stream()
.sorted(Comparator.comparing(Requires::name))
.forEach(req ->
{
ResourcePoolModule dep = moduleView.findModule(req.name()).orElse(null);
if (dep != null) {
addNode(dep);
edges.get(module.name()).add(dep);
graph.get(module).add(dep);
} else if (!req.modifiers().contains(Modifier.STATIC)) {
throw new PluginException(req.name() + " not found");
}
@ -82,22 +90,23 @@ public final class ModuleSorter {
}
private void addNode(ResourcePoolModule module) {
nodes.add(module);
edges.computeIfAbsent(module.name(), _n -> new HashSet<>());
graph.computeIfAbsent(module, _n -> new LinkedHashSet<>());
}
/*
* The module graph will be traversed in a stable order
* (traversing the modules and their dependences in alphabetical order)
* so that it will produce the same result of a given module graph.
*/
private synchronized void build() {
if (!result.isEmpty() || nodes.isEmpty())
if (!result.isEmpty() || graph.isEmpty())
return;
Deque<ResourcePoolModule> visited = new LinkedList<>();
Deque<ResourcePoolModule> done = new LinkedList<>();
ResourcePoolModule node;
while ((node = nodes.poll()) != null) {
if (!visited.contains(node)) {
visit(node, visited, done);
}
}
Set<ResourcePoolModule> visited = new HashSet<>();
Set<ResourcePoolModule> done = new HashSet<>();
graph.keySet().stream()
.sorted(Comparator.comparing(ResourcePoolModule::name))
.forEach(node -> visit(node, visited, done));
}
public Stream<ResourcePoolModule> sorted() {
@ -106,19 +115,21 @@ public final class ModuleSorter {
}
private void visit(ResourcePoolModule node,
Deque<ResourcePoolModule> visited,
Deque<ResourcePoolModule> done) {
Set<ResourcePoolModule> visited,
Set<ResourcePoolModule> done) {
if (visited.contains(node)) {
if (!done.contains(node)) {
throw new IllegalArgumentException("Cyclic detected: " +
node + " " + edges.get(node.name()));
node + " " + graph.get(node));
}
return;
}
// traverse the dependences of the given module which are
// also sorted in alphabetical order
visited.add(node);
edges.get(node.name())
.forEach(x -> visit(x, visited, done));
graph.get(node).forEach(x -> visit(x, visited, done));
done.add(node);
result.addLast(node);
result.add(node);
}
}

@ -834,6 +834,8 @@ class Eval {
if (!toReplace.isEmpty()) {
replaced.addAll(toReplace);
replaced.stream().forEach(Unit::markForReplacement);
//ensure correct classnames are set in the snippets:
replaced.stream().forEach(u -> u.setWrap(ins, legit));
}
return toReplace.isEmpty() ? Result.SUCESS : Result.FAILURE;

@ -295,7 +295,7 @@ public class Shell implements PartialParser {
} catch (final IOException ioe) {
// ignore
}
if (l.startsWith("#!")) {
if (l != null && l.startsWith("#!")) {
shebangFilePos = i;
}
// We're only checking the first non-option argument. If it's not a shebang file, we're in normal

@ -0,0 +1,104 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @modules java.base/jdk.internal.module
* @run testng ClassFileVersionsTest
* @summary Test parsing of module-info.class with different class file versions
*/
import java.lang.module.InvalidModuleDescriptorException;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Requires.Modifier;
import java.nio.ByteBuffer;
import java.util.Set;
import static java.lang.module.ModuleDescriptor.Requires.Modifier.*;
import jdk.internal.module.ModuleInfoWriter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class ClassFileVersionsTest {
// major, minor, modifiers for requires java.base
@DataProvider(name = "supported")
public Object[][] supported() {
return new Object[][]{
{ 53, 0, Set.of() }, // JDK 9
{ 53, 0, Set.of(STATIC) },
{ 53, 0, Set.of(TRANSITIVE) },
{ 53, 0, Set.of(STATIC, TRANSITIVE) },
{ 54, 0, Set.of() }, // JDK 10
};
}
// major, minor, modifiers for requires java.base
@DataProvider(name = "unsupported")
public Object[][] unsupported() {
return new Object[][]{
{ 50, 0, Set.of()}, // JDK 6
{ 51, 0, Set.of()}, // JDK 7
{ 52, 0, Set.of()}, // JDK 8
{ 54, 0, Set.of(STATIC) }, // JDK 10
{ 54, 0, Set.of(TRANSITIVE) },
{ 54, 0, Set.of(STATIC, TRANSITIVE) },
{ 55, 0, Set.of()}, // JDK 11
};
}
@Test(dataProvider = "supported")
public void testSupported(int major, int minor, Set<Modifier> ms) {
ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo")
.requires(ms, "java.base")
.build();
ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
classFileVersion(bb, major, minor);
descriptor = ModuleDescriptor.read(bb);
assertEquals(descriptor.name(), "foo");
}
@Test(dataProvider = "unsupported",
expectedExceptions = InvalidModuleDescriptorException.class)
public void testUnsupported(int major, int minor, Set<Modifier> ms) {
ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo")
.requires(ms, "java.base")
.build();
ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
classFileVersion(bb, major, minor);
// throws InvalidModuleDescriptorException
ModuleDescriptor.read(bb);
}
private void classFileVersion(ByteBuffer bb, int major, int minor) {
bb.putShort(4, (short) minor);
bb.putShort(6, (short) major);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2017 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -21,6 +21,7 @@
* questions.
*/
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -36,7 +37,7 @@ import static org.testng.Assert.assertFalse;
/**
* @test
* @bug 4313887 8062949
* @bug 4313887 8062949 8191872
* @library ..
* @run testng SetLastModifiedTime
* @summary Unit test for Files.setLastModifiedTime
@ -114,5 +115,20 @@ public class SetLastModifiedTime {
assertTrue(false);
} catch (NullPointerException expected) { }
}
@Test
public void testCompare() throws Exception {
Path path = Files.createFile(testDir.resolve("path"));
long timeMillis = 1512520600195L;
FileTime fileTime = FileTime.fromMillis(timeMillis);
Files.setLastModifiedTime(path, fileTime);
File file = path.toFile();
long ioTime = file.lastModified();
long nioTime = Files.getLastModifiedTime(path).toMillis();
assertTrue(ioTime == timeMillis || ioTime == 1000*(timeMillis/1000),
"File.lastModified() not in {time, 1000*(time/1000)}");
assertEquals(nioTime, ioTime,
"File.lastModified() != Files.getLastModifiedTime().toMillis()");
}
}

@ -0,0 +1,180 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @test
* @bug 8191033
* @build custom.DotHandler custom.Handler
* @run main/othervm RootLoggerHandlers
* @author danielfuchs
*/
public class RootLoggerHandlers {
public static final Path SRC_DIR =
Paths.get(System.getProperty("test.src", "src"));
public static final Path USER_DIR =
Paths.get(System.getProperty("user.dir", "."));
public static final Path CONFIG_FILE = Paths.get("logging.properties");
// Uncomment this to run the test on Java 8. Java 8 does not have
// List.of(...)
// static final class List {
// static <T> java.util.List<T> of(T... items) {
// return Collections.unmodifiableList(Arrays.asList(items));
// }
// }
public static void main(String[] args) throws IOException {
Path initialProps = SRC_DIR.resolve(CONFIG_FILE);
Path loggingProps = USER_DIR.resolve(CONFIG_FILE);
System.setProperty("java.util.logging.config.file", loggingProps.toString());
Files.copy(initialProps, loggingProps);
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.INFO) {
throw new RuntimeException("Expected root level INFO, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have two handlers. One was configured with
// handlers=custom.Handler, the other with
// .handlers=custom.DotHandler
// Verify that exactly one of the two handlers is a custom.Handler
// Verify that exactly one of the two handlers is a custom.DotHandler
// Verify that the two handlers has an id of '1'
checkHandlers(Logger.getLogger("").getHandlers(),
1L,
custom.Handler.class,
custom.DotHandler.class);
// The log message "hi" should appear twice on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("hi");
// Change the root logger level to FINE in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINE"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINE) {
throw new RuntimeException("Expected root level FINE, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have now only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '2'
checkHandlers(Logger.getLogger("").getHandlers(),
2L,
custom.Handler.class);
// The log message "there" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("there!");
// Change the root logger level to FINER in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINER"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINER) {
throw new RuntimeException("Expected root level FINER, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '3'
checkHandlers(Logger.getLogger("").getHandlers(),
3L,
custom.Handler.class);
// The log message "done" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("done!");
}
static void checkHandlers(Handler[] handlers, Long expectedID, Class<?>... clz) {
// Verify that we have the expected number of handlers.
if (Stream.of(handlers).count() != clz.length) {
throw new RuntimeException("Expected " + clz.length + " handlers, got: "
+ List.of(Logger.getLogger("").getHandlers()));
}
for (Class<?> cl : clz) {
// Verify that the handlers are of the expected class.
// For each class, we should have exactly one handler
// of that class.
if (Stream.of(handlers)
.map(Object::getClass)
.filter(cl::equals)
.count() != 1) {
throw new RuntimeException("Expected one " + cl +", got: "
+ List.of(Logger.getLogger("").getHandlers()));
}
}
// Verify that all handlers have the expected ID
if (Stream.of(Logger.getLogger("").getHandlers())
.map(RootLoggerHandlers::getId)
.filter(expectedID::equals)
.count() != clz.length) {
throw new RuntimeException("Expected ids to be " + expectedID + ", got: "
+ List.of(Logger.getLogger("").getHandlers()));
}
}
static long getId(Handler h) {
if (h instanceof custom.Handler) {
return ((custom.Handler)h).id;
}
if (h instanceof custom.DotHandler) {
return ((custom.DotHandler)h).id;
}
return -1;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package custom;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author danielfuchs
*/
public class DotHandler extends java.util.logging.ConsoleHandler {
public static final AtomicLong IDS = new AtomicLong();
public final long id = IDS.incrementAndGet();
public DotHandler() {
System.out.println("DotHandler(" + id + ") created");
//new Exception("DotHandler").printStackTrace();
}
@Override
public void close() {
System.out.println("DotHandler(" + id + ") closed");
super.close();
}
@Override
public String toString() {
return this.getClass().getName() + '(' + id + ')';
}
}

@ -0,0 +1,49 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package custom;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author danielfuchs
*/
public class Handler extends java.util.logging.ConsoleHandler {
static final AtomicLong IDS = new AtomicLong();
public final long id = IDS.incrementAndGet();
public Handler() {
System.out.println("Handler(" + id + ") created");
}
@Override
public void close() {
System.out.println("Handler(" + id + ") closed");
super.close();
}
@Override
public String toString() {
return this.getClass().getName() + '(' + id + ')';
}
}

@ -0,0 +1,18 @@
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
#handlers= java.util.logging.ConsoleHandler
handlers= custom.Handler
.handlers= custom.DotHandler
# Default global logging level.
.level= INFO
# Other configuration
custom.Handler.level=ALL
custom.DotHandler.level=ALL
java.util.logging.SimpleFormatter.format=%4$s [%1$tc]: %2$s: %5$s%n

@ -0,0 +1,67 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8192987
* @summary keytool should remember real storetype if it is not provided
* @library /test/lib
* @build jdk.test.lib.SecurityTools
* jdk.test.lib.Utils
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.JDKToolLauncher
* jdk.test.lib.Platform
* jdk.test.lib.process.*
* @run main/othervm RealType
*/
import jdk.test.lib.SecurityTools;
import jdk.test.lib.process.OutputAnalyzer;
import java.nio.file.Files;
import java.nio.file.Paths;
public class RealType {
public static void main(String[] args) throws Throwable {
kt("-genkeypair -alias a -dname CN=A -keypass changeit -storetype jks")
.shouldHaveExitValue(0);
// -keypasswd command should be allowed on JKS
kt("-keypasswd -alias a -new t0ps3cr3t")
.shouldHaveExitValue(0);
Files.delete(Paths.get("ks"));
kt("-genkeypair -alias a -dname CN=A -keypass changeit -storetype pkcs12")
.shouldHaveExitValue(0);
// A pkcs12 keystore cannot be loaded as a JCEKS keystore
kt("-list -storetype jceks").shouldHaveExitValue(1);
}
static OutputAnalyzer kt(String arg) throws Exception {
return SecurityTools.keytool("-debug -keystore ks -storepass changeit " + arg);
}
}

@ -24,14 +24,17 @@
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
import java.util.spi.ToolProvider;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import tests.Helper;
import tests.JImageGenerator;
import tests.JImageGenerator.JLinkTask;
/*
* @test
@ -44,6 +47,9 @@ import tests.JImageGenerator;
* jdk.jlink/jdk.tools.jmod
* jdk.jlink/jdk.tools.jimage
* jdk.compiler
* jdk.scripting.nashorn
* jdk.scripting.nashorn.shell
*
* @build tests.*
* @run main ModuleNamesOrderTest
*/
@ -60,12 +66,18 @@ public class ModuleNamesOrderTest {
return;
}
Path outputDir = helper.createNewImageDir("image8168925");
JImageGenerator.getJLinkTask()
.modulePath(helper.defaultModulePath())
.output(outputDir)
.addMods("jdk.scripting.nashorn")
.call().assertSuccess();
testDependences(helper);
testModulesOrder(helper);
}
private static List<String> modulesProperty(Path outputDir, String modulePath, String... roots)
throws IOException
{
JLinkTask jlinkTask = JImageGenerator.getJLinkTask()
.modulePath(modulePath)
.output(outputDir);
Stream.of(roots).forEach(jlinkTask::addMods);
jlinkTask.call().assertSuccess();
File release = new File(outputDir.toString(), "release");
if (!release.exists()) {
@ -81,9 +93,21 @@ public class ModuleNamesOrderTest {
if (!modules.startsWith("\"java.base ")) {
throw new AssertionError("MODULES should start with 'java.base'");
}
if (modules.charAt(0) != '"' || modules.charAt(modules.length()-1) != '"') {
throw new AssertionError("MODULES value should be double quoted");
}
if (!modules.endsWith(" jdk.scripting.nashorn\"")) {
throw new AssertionError("MODULES end with 'jdk.scripting.nashorn'");
return Stream.of(modules.substring(1, modules.length()-1).split("\\s+"))
.collect(Collectors.toList());
}
private static void testDependences(Helper helper) throws IOException {
Path outputDir = helper.createNewImageDir("test");
List<String> modules = modulesProperty(outputDir, helper.defaultModulePath(),
"jdk.scripting.nashorn");
String last = modules.get(modules.size()-1);
if (!last.equals("jdk.scripting.nashorn")) {
throw new AssertionError("Unexpected MODULES value: " + modules);
}
checkDependency(modules, "java.logging", "java.base");
@ -94,7 +118,23 @@ public class ModuleNamesOrderTest {
checkDependency(modules, "jdk.scripting.nashorn", "java.scripting");
}
private static void checkDependency(String modules, String fromMod, String toMod) {
/*
* Verify the MODULES list must be the same for the same module graph
*/
private static void testModulesOrder(Helper helper) throws IOException {
Path image1 = helper.createNewImageDir("test1");
List<String> modules1 = modulesProperty(image1, helper.defaultModulePath(),
"jdk.scripting.nashorn", "jdk.scripting.nashorn.shell");
Path image2 = helper.createNewImageDir("test2");
List<String> modules2 = modulesProperty(image2, helper.defaultModulePath(),
"jdk.scripting.nashorn.shell", "jdk.scripting.nashorn");
if (!modules1.equals(modules2)) {
throw new AssertionError("MODULES should be a stable order: " +
modules1 + " vs " + modules2);
}
}
private static void checkDependency(List<String> modules, String fromMod, String toMod) {
int fromModIdx = modules.indexOf(fromMod);
if (fromModIdx == -1) {
throw new AssertionError(fromMod + " is missing in MODULES");

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -24,27 +24,52 @@
/*
* @test
* @bug 4691095 6306394
* @summary Test to make sure that Javadoc emits a useful warning
* when a bad package.html file is in the JAR.
* @summary Make sure that Javadoc emits a useful warning
* when a bad package.html exists in a JAR archive.
* @author jamieh
* @library ../lib
* @library /tools/lib ../lib
* @modules jdk.javadoc/jdk.javadoc.internal.tool
* @build JavadocTester
* @build JavadocTester toolbox.ToolBox toolbox.JarTask
* @run main TestBadPackageFileInJar
*/
import toolbox.JarTask;
import toolbox.Task.Result;
import toolbox.ToolBox;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestBadPackageFileInJar extends JavadocTester {
final ToolBox tb = new ToolBox();
public static void main(String... args) throws Exception {
TestBadPackageFileInJar tester = new TestBadPackageFileInJar();
tester.runTests();
}
@Test
void test() {
void test() throws IOException {
// create the file
Path pkgDir = Paths.get("pkg");
tb.createDirectories(pkgDir);
Path pkgfilePath = pkgDir.resolve("package.html");
tb.writeFile(pkgfilePath, "<html>\n\n</html>");
// create the jar file
Path jarFile = Paths.get("badPackageFileInJar.jar");
JarTask jar = new JarTask(tb, "badPackageFileInJar.jar");
jar.files(pkgDir.toString()).run();
// clean up to prevent accidental pick up
tb.cleanDirectory(pkgDir);
tb.deleteFiles(pkgDir.toString());
javadoc("-d", "out",
"-sourcepath", testSrc,
"-classpath", testSrc("badPackageFileInJar.jar"),
"-classpath", jarFile.toString(),
"pkg");
checkExit(Exit.OK);

@ -23,7 +23,8 @@
/*
* @test
* @bug 4927552 8026567 8071982 8162674 8175200 8175218 8183511 8186332 8169819 8074407
* @bug 4927552 8026567 8071982 8162674 8175200 8175218 8183511 8186332
* 8169819 8074407 8191030
* @summary test generated docs for deprecated items
* @author jamieh
* @library ../lib
@ -257,24 +258,30 @@ public class TestDeprecatedDocs extends JavadocTester {
+ "<td class=\"colLast\"></td>\n"
+ "</tr>\n"
+ "<tr class=\"rowColor\">\n"
+ "<th class=\"colDeprecatedItemName\" scope=\"row\"><a href=\"pkg/TestAnnotationType.html#field\">pkg.TestAnnotationType.field</a></th>\n"
+ "<td class=\"colLast\">\n"
+ "<div class=\"deprecationComment\">annotation_test4 passes.</div>\n"
+ "</td>\n"
+ "</tr>\n"
+ "<tr class=\"altColor\">\n"
+ "<th class=\"colDeprecatedItemName\" scope=\"row\"><a href=\"pkg/TestClass.html#field\">pkg.TestClass.field</a></th>\n"
+ "<td class=\"colLast\">\n"
+ "<div class=\"deprecationComment\">class_test2 passes. This is the second sentence of deprecated description for a field.</div>\n"
+ "</td>\n"
+ "</tr>\n"
+ "<tr class=\"altColor\">\n"
+ "<tr class=\"rowColor\">\n"
+ "<th class=\"colDeprecatedItemName\" scope=\"row\"><a href=\"pkg/TestError.html#field\">pkg.TestError.field</a></th>\n"
+ "<td class=\"colLast\">\n"
+ "<div class=\"deprecationComment\">error_test2 passes.</div>\n"
+ "</td>\n"
+ "</tr>\n"
+ "<tr class=\"rowColor\">\n"
+ "<tr class=\"altColor\">\n"
+ "<th class=\"colDeprecatedItemName\" scope=\"row\"><a href=\"pkg/TestException.html#field\">pkg.TestException.field</a></th>\n"
+ "<td class=\"colLast\">\n"
+ "<div class=\"deprecationComment\">exception_test2 passes.</div>\n"
+ "</td>\n"
+ "</tr>\n"
+ "<tr class=\"altColor\">\n"
+ "<tr class=\"rowColor\">\n"
+ "<th class=\"colDeprecatedItemName\" scope=\"row\"><a href=\"pkg/TestInterface.html#field\">pkg.TestInterface.field</a></th>\n"
+ "<td class=\"colLast\">\n"
+ "<div class=\"deprecationComment\">interface_test2 passes.</div>\n"

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -21,4 +21,4 @@
* questions.
*/
public class C {}
public class InUnnamedPackage {}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,9 +23,9 @@
/*
* @test
* @bug 4924383
* @summary Test to make sure the -group option does not cause a bad warning
* to be printed. Test for the group defined using patterns.
* @bug 4924383 8149402
* @summary Test to make sure the -group option works correctly
* with the given pattern usages.
* @author jamieh
* @library ../lib
* @modules jdk.javadoc/jdk.javadoc.internal.tool
@ -55,8 +55,7 @@ public class TestGroupOption extends JavadocTester {
"-group");
}
// @Test
// @ignore 8149402
@Test
// Make sure the "Other packages" section is printed and the header for empty section is not.
// Make sure that the headers of group that is defined using patterns are printed.
void test2() {
@ -66,7 +65,7 @@ public class TestGroupOption extends JavadocTester {
"-group", "Group abc*", "abc*",
"-group", "Empty group", "qwerty*",
"-group", "Group a*", "a*",
"pkg1", "pkg2", "pkg3", "abc1", "abc2", "abc3", "other", testSrc("C.java"));
"pkg1", "pkg2", "pkg3", "abc1", "abc2", "abc3", "other", testSrc("InUnnamedPackage.java"));
checkExit(Exit.OK);
checkOutput("overview-summary.html", true, "Group pkg*", "Group abc*", "Other Packages");

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,9 +23,9 @@
/*
* @test
* @bug 4764045 8004825 8026567
* @bug 4764045 8004825 8026567 8191030
* @summary This test ensures that the value tag works in all
* use cases. The explainations for each test case are written below.
* use cases, the tests are explained below.
* @author jamieh
* @library ../lib
* @modules jdk.javadoc/jdk.javadoc.internal.tool
@ -103,7 +103,7 @@ public class TestValueTag extends JavadocTester {
);
checkOutput("pkg1/Class1.html", false,
//Base case: using @value on a constant.
// Base case: using @value on a constant.
"Result: <a href=\"../pkg1/Class1.html#TEST_12_ERROR\">\"Test 12 "
+ "generates an error message\"</a>");
@ -119,23 +119,36 @@ public class TestValueTag extends JavadocTester {
"pkg1", "pkg2");
checkExit(Exit.OK);
checkOutput(Output.OUT, true,
//Test @value warning printed when used with non-constant.
// Test @value warning printed when used with non-constant.
"warning - @value tag (which references nonConstant) "
+ "can only be used in constants.",
"warning - @value tag (which references NULL) "
+ "can only be used in constants.",
"warning - @value tag (which references TEST_12_ERROR) "
+ "can only be used in constants."
// TODO: re-examine these.
// //Test warning printed for bad reference.
// "warning - UnknownClass#unknownConstant (referenced by "
// + "@value tag) is an unknown reference.",
// //Test warning printed for invalid use of @value.
// "warning - @value tag cannot be used here."
+ "can only be used in constants.",
// Test warning printed for bad reference.
"warning - {@value UnknownClass#unknownConstant}"
+ " (referenced by @value tag) is an unknown reference."
);
checkForException();
}
@Test()
void test3() {
javadoc("-d", "out3",
"-sourcepath", testSrc,
"pkg2", "pkg3");
checkExit(Exit.OK);
checkOrder("pkg3/RT.html",
"The value is <a href=\"../pkg3/RT.html#CONSTANT\">\"constant\"</a>.",
"The value1 is <a href=\"../pkg3/RT.html#CONSTANT\">\"constant\"</a>.",
"The value2 is <a href=\"../pkg3/RT.html#CONSTANT\">\"constant\"</a>.",
"The value3 is <a href=\"../pkg2/Class3.html#TEST_12_PASSES\">"
+ "\"Test 12 passes\"</a>.");
}
void checkForException() {
checkOutput(Output.STDERR, false, "DocletAbortException");
}

@ -0,0 +1,56 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pkg3;
public @interface RT {
/** The CONSTANT */
static String CONSTANT = "constant";
/**
* The value is {@value CONSTANT}.
* @return a value
*/
int value();
/**
* The value1 is {@value #CONSTANT}.
* @return a value
*/
int value1();
/**
* The value2 is {@value pkg3.RT#CONSTANT}.
* @return a value
*/
int value2();
/**
* The value3 is {@value pkg2.Class3#TEST_12_PASSES}.
* @return a value
*/
int value3();
}

@ -23,7 +23,7 @@
/*
* @test
* @bug 8145239 8129559 8080354
* @bug 8145239 8129559 8080354 8189248
* @summary Tests for EvaluationState.classes
* @build KullaTesting TestingInputStream ExpectedDiagnostic
* @run testng ClassesTest
@ -41,6 +41,7 @@ import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import jdk.jshell.Diag;
import jdk.jshell.Snippet.Status;
import static java.util.stream.Collectors.toList;
import static jdk.jshell.Snippet.Status.VALID;
import static jdk.jshell.Snippet.Status.RECOVERABLE_NOT_DEFINED;
@ -327,4 +328,24 @@ public class ClassesTest extends KullaTesting {
VarSnippet variableKey = varKey(assertEval("a.x;"));
assertEquals(variableKey.typeName(), "A.I1");
}
public void testCircular() {
assertEval("import java.util.function.Supplier;");
TypeDeclSnippet aClass =
classKey(assertEval("public class A<T> {\n" +
" private class SomeClass {}\n" +
" public Supplier<T> m() {\n" +
" return new B<>(this);\n" +
" }\n" +
"}",
added(RECOVERABLE_DEFINED)));
assertEval("public class B<T> implements Supplier<T> {\n" +
" public B(A<T> a) {}\n" +
" public T get() {return null;}\n" +
"}",
added(VALID),
ste(aClass, Status.RECOVERABLE_DEFINED, Status.VALID, true, null));
assertEval("new A()");
}
}

@ -1,73 +0,0 @@
/*
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 5090006
* @summary javac fails with assertion error
* @library /tools/lib
* @modules jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.main
* jdk.jdeps/com.sun.tools.javap
* @build toolbox.ToolBox toolbox.JavacTask
* @run main AssertionFailureTest
*/
import java.io.File;
import java.nio.file.Paths;
import toolbox.JavacTask;
import toolbox.ToolBox;
// Original test: test/tools/javac/T5090006/compiler.sh
public class AssertionFailureTest {
private static final String testSrc =
"import stub_tie_gen.wsdl_hello_lit.client.*;\n" +
"import junit.framework.*;\n" +
"import testutil.ClientServerTestUtil;\n" +
"\n" +
"public class Test {\n" +
"\n" +
" void getStub() throws Exception {\n" +
" Hello_PortType_Stub x = null;\n" +
" new ClientServerTestUtil().setTransport(x, null, null, null);\n" +
" }\n" +
"\n" +
" public static void main(String[] args) {\n" +
" System.out.println(\"FISK\");\n" +
" }\n" +
"}";
public static void main(String args[]) throws Exception {
ToolBox tb = new ToolBox();
String classpath = Paths.get(tb.testSrc, "broken.jar")
+ File.pathSeparator
+ ".";
new JavacTask(tb)
.classpath(classpath)
.sources(testSrc)
.run();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -31,13 +31,7 @@ import static javax.lang.model.SourceVersion.*;
* An abstract annotation processor tailored to {@code javac} regression testing.
*/
public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
private static final Set<String> allAnnotations;
static {
Set<String> tmp = new HashSet<>();
tmp.add("*");
allAnnotations = Collections.unmodifiableSet(tmp);
}
private static final Set<String> allAnnotations = Set.of("*");
protected Elements eltUtils;
protected Elements elements;
@ -116,7 +110,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
* corresponding platform visitor type.
*/
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static abstract class AbstractAnnotationValueVisitor<R, P> extends AbstractAnnotationValueVisitor9<R, P> {
/**
@ -127,7 +121,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static abstract class AbstractElementVisitor<R, P> extends AbstractElementVisitor9<R, P> {
/**
* Constructor for concrete subclasses to call.
@ -137,7 +131,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static abstract class AbstractTypeVisitor<R, P> extends AbstractTypeVisitor9<R, P> {
/**
* Constructor for concrete subclasses to call.
@ -147,7 +141,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class ElementKindVisitor<R, P> extends ElementKindVisitor9<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
@ -168,7 +162,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class ElementScanner<R, P> extends ElementScanner9<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
@ -187,7 +181,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class SimpleAnnotationValueVisitor<R, P> extends SimpleAnnotationValueVisitor9<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
@ -208,7 +202,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class SimpleElementVisitor<R, P> extends SimpleElementVisitor9<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
@ -229,7 +223,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class SimpleTypeVisitor<R, P> extends SimpleTypeVisitor9<R, P> {
/**
* Constructor for concrete subclasses; uses {@code null} for the
@ -250,7 +244,7 @@ public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
}
}
@SupportedSourceVersion(RELEASE_9)
@SupportedSourceVersion(RELEASE_10)
public static class TypeKindVisitor<R, P> extends TypeKindVisitor9<R, P> {
/**
* Constructor for concrete subclasses to call; uses {@code null}

@ -0,0 +1,59 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. 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.
*/
/**
* JDK-8193137 : Nashorn crashes when given an empty script file.
*
* @test
* @option -scripting
* @run
*/
var System = java.lang.System;
var File = java.io.File;
var javahome = System.getProperty("java.home");
var nashornJar = new File(System.getProperty("nashorn.jar"));
if (! nashornJar.isAbsolute()) {
nashornJar = new File(".", nashornJar);
}
// we want to use nashorn.jar passed and not the one that comes with JRE
var jjsCmd = javahome + "/../bin/jjs";
jjsCmd = jjsCmd.toString().replace(/\//g, File.separator);
if (! new File(jjsCmd).isFile()) {
jjsCmd = javahome + "/bin/jjs";
jjsCmd = jjsCmd.toString().replace(/\//g, File.separator);
}
jjsCmd += " -J--patch-module=jdk.scripting.nashorn=" + nashornJar;
$ENV.PWD=System.getProperty("user.dir")
var emptyFile = new File($ENV.PWD+File.separator+"empty.js");
emptyFile.createNewFile();
emptyFile.deleteOnExit();
$EXEC(jjsCmd + " empty.js");
if($ERR != "")
fail("jjs fails with empty script file");

@ -243,13 +243,56 @@ public class BeanLinkerTest {
Assert.assertEquals((int) cs.getTarget().invoke(list, 1), (int) list.get(1));
Assert.assertEquals((int) cs.getTarget().invoke(list, 2), (int) list.get(2));
try {
final int x = (int) cs.getTarget().invoke(list, -1);
cs.getTarget().invoke(list, -1);
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
try {
final int x = (int) cs.getTarget().invoke(list, list.size());
cs.getTarget().invoke(list, list.size());
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
}
private Object invokeWithFixedKey(boolean publicLookup, Operation op, Object name, MethodType mt, Object... args) throws Throwable {
return createCallSite(publicLookup, op.named(name), mt).getTarget().invokeWithArguments(args);
}
@Test(dataProvider = "flags")
public void getElementWithFixedKeyTest(final boolean publicLookup) throws Throwable {
final MethodType mt = MethodType.methodType(int.class, Object.class);
final int[] arr = {23, 42};
Assert.assertEquals((int) invokeWithFixedKey(publicLookup, GET_ELEMENT, 0, mt, arr), 23);
Assert.assertEquals((int) invokeWithFixedKey(publicLookup, GET_ELEMENT, 1, mt, arr), 42);
try {
invokeWithFixedKey(publicLookup, GET_ELEMENT, -1, mt, arr);
throw new RuntimeException("expected ArrayIndexOutOfBoundsException");
} catch (final ArrayIndexOutOfBoundsException ex) {
}
try {
invokeWithFixedKey(publicLookup, GET_ELEMENT, arr.length, mt, arr);
throw new RuntimeException("expected ArrayIndexOutOfBoundsException");
} catch (final ArrayIndexOutOfBoundsException ex) {
}
final List<Integer> list = new ArrayList<>();
list.add(23);
list.add(430);
list.add(-4354);
for (int i = 0; i < 3; ++i) {
Assert.assertEquals((int) invokeWithFixedKey(publicLookup, GET_ELEMENT, i, mt, list), (int) list.get(i));
}
try {
invokeWithFixedKey(publicLookup, GET_ELEMENT, -1, mt, list);
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
try {
invokeWithFixedKey(publicLookup, GET_ELEMENT, list.size(), mt, list);
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
@ -286,7 +329,9 @@ public class BeanLinkerTest {
cs.getTarget().invoke(list, 0, -list.get(0));
Assert.assertEquals((int) list.get(0), -23);
cs.getTarget().invoke(list, 1, -430);
Assert.assertEquals((int) list.get(1), -430);
cs.getTarget().invoke(list, 2, 4354);
Assert.assertEquals((int) list.get(2), 4354);
try {
cs.getTarget().invoke(list, -1, 343);
throw new RuntimeException("expected IndexOutOfBoundsException");
@ -300,6 +345,52 @@ public class BeanLinkerTest {
}
}
@Test(dataProvider = "flags")
public void setElementWithFixedKeyTest(final boolean publicLookup) throws Throwable {
final MethodType mt = MethodType.methodType(void.class, Object.class, int.class);
final int[] arr = {23, 42};
invokeWithFixedKey(publicLookup, SET_ELEMENT, 0, mt, arr, 0);
Assert.assertEquals(arr[0], 0);
invokeWithFixedKey(publicLookup, SET_ELEMENT, 1, mt, arr, -5);
Assert.assertEquals(arr[1], -5);
try {
invokeWithFixedKey(publicLookup, SET_ELEMENT, -1, mt, arr, 12);
throw new RuntimeException("expected ArrayIndexOutOfBoundsException");
} catch (final ArrayIndexOutOfBoundsException ex) {
}
try {
invokeWithFixedKey(publicLookup, SET_ELEMENT, arr.length, mt, arr, 20);
throw new RuntimeException("expected ArrayIndexOutOfBoundsException");
} catch (final ArrayIndexOutOfBoundsException ex) {
}
final List<Integer> list = new ArrayList<>();
list.add(23);
list.add(430);
list.add(-4354);
invokeWithFixedKey(publicLookup, SET_ELEMENT, 0, mt, list, -list.get(0));
Assert.assertEquals((int) list.get(0), -23);
invokeWithFixedKey(publicLookup, SET_ELEMENT, 1, mt, list, -430);
Assert.assertEquals((int) list.get(1), -430);
invokeWithFixedKey(publicLookup, SET_ELEMENT, 2, mt, list, 4354);
Assert.assertEquals((int) list.get(2), 4354);
try {
invokeWithFixedKey(publicLookup, SET_ELEMENT, -1, mt, list, 343);
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
try {
invokeWithFixedKey(publicLookup, SET_ELEMENT, list.size(), mt, list, 43543);
throw new RuntimeException("expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException ex) {
}
}
@Test(dataProvider = "flags")
public void newObjectTest(final boolean publicLookup) {
final MethodType mt = MethodType.methodType(Object.class, Object.class);