Begin compatibility level support, java 8 must now be explicitly enabled

This commit is contained in:
Mumfrey committed 2015-11-17 15:53:31 +00:00
1 parent 13ac04cc88
commit 7eb61bc53a
9 files changed
+258 -51

No files matched your search

@@ -37,6 +37,7 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
protected static final String MFATT_MIXINCONFIGS = "MixinConfigs";
protected static final String MFATT_TOKENPROVIDERS = "MixinTokenProviders";
protected static final String MFATT_MAINCLASS = "Main-Class";
protected static final String MFATT_COMPATIBILITY = "MixinCompatibilityLevel";
public MixinLaunchAgentDefault(URI uri) {
super(uri);
@@ -44,6 +45,11 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
@Override
public void prepare() {
String compatibilityLevel = this.attributes.get(MixinLaunchAgentDefault.MFATT_COMPATIBILITY);
if (compatibilityLevel != null) {
MixinTweaker.setCompatibilityLevel(compatibilityLevel);
}
String mixinConfigs = this.attributes.get(MixinLaunchAgentDefault.MFATT_MIXINCONFIGS);
if (mixinConfigs != null) {
for (String config : mixinConfigs.split(",")) {
@@ -39,6 +39,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
@@ -195,6 +196,22 @@ public class MixinTweaker implements ITweaker {
public String[] getLaunchArguments() {
return new String[]{};
}
/**
* Set the desired compatibility level as a string, used by agents to set
* compatibility level from jar manifest
*
* @param level compatibility level as a string
*/
static void setCompatibilityLevel(String level) {
try {
CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase());
MixinTweaker.logger.debug("Setting mixin compatibility level: {}", value);
MixinEnvironment.setCompatibilityLevel(value);
} catch (IllegalArgumentException ex) {
MixinTweaker.logger.warn("Invalid compatibility level specified: {}", level);
}
}
/**
* Add a config from a jar manifest source or the command line. Supports
@@ -24,27 +24,6 @@
*/
package org.spongepowered.asm.mixin;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.PrettyPrinter;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
@@ -57,6 +36,31 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.PrettyPrinter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
/**
* The mixin environment manages global state information for the mixin
@@ -339,6 +343,58 @@ public class MixinEnvironment implements ITokenProvider {
}
}
/**
* Operational compatibility level for the mixin subsystem
*/
public static enum CompatibilityLevel {
JAVA_6(Opcodes.V1_6, false),
JAVA_7(Opcodes.V1_7, false) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.7;
}
},
JAVA_8(Opcodes.V1_8, true) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.8;
}
};
private final int classVersion;
private final boolean resolveMethodsInInterfaces;
private CompatibilityLevel(int classVersion, boolean resolveMethodsInInterfaces) {
this.classVersion = classVersion;
this.resolveMethodsInInterfaces = resolveMethodsInInterfaces;
}
boolean isSupported() {
return true;
}
public int classVersion() {
return this.classVersion;
}
public boolean resolveMethodsInInterfaces() {
return this.resolveMethodsInInterfaces;
}
public boolean isAtLeast(CompatibilityLevel level) {
return this.ordinal() >= level.ordinal();
}
}
/**
* Tweaker used to notify the environment when we transition from preinit to
* default
@@ -461,6 +517,11 @@ public class MixinEnvironment implements ITokenProvider {
*/
private static Phase currentPhase = Phase.NOT_INITIALISED;
/**
* Current compatibility level
*/
private static CompatibilityLevel compatibility = CompatibilityLevel.JAVA_6;
/**
* Show debug header info on first environment construction
*/
@@ -469,7 +530,7 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Logger
*/
private final Logger logger = LogManager.getLogger("mixin");
private static final Logger logger = LogManager.getLogger("mixin");
/**
* The phase for this environment
@@ -553,13 +614,14 @@ public class MixinEnvironment implements ITokenProvider {
private void printHeader(Object version) {
Side side = this.getSide();
String codeSource = this.getCodeSource();
this.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
if (this.getOption(Option.DEBUG_VERBOSE)) {
PrettyPrinter printer = new PrettyPrinter(32);
printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr();
printer.add("%25s : %s", "Code source", codeSource);
printer.add("%25s : %s", "Internal Version", version).hr();
printer.add("%25s : %s", "Internal Version", version);
printer.add("%25s : %s", "Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr();
for (Option option : Option.values()) {
printer.add("%25s : %s%s", option.property, option.parent == null ? "" : " - ", this.getOption(option));
}
@@ -640,7 +702,7 @@ public class MixinEnvironment implements ITokenProvider {
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
this.logger.error("Error instantiating " + providerName, th);
MixinEnvironment.logger.error("Error instantiating " + providerName, th);
}
}
return this;
@@ -656,7 +718,7 @@ public class MixinEnvironment implements ITokenProvider {
if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) {
String providerName = provider.getClass().getName();
TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this);
this.logger.info("Adding new token provider {} to {}", providerName, this);
MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this);
this.tokenProviders.add(wrapper);
this.tokenProviderClasses.add(providerName);
Collections.sort(this.tokenProviders);
@@ -847,7 +909,7 @@ public class MixinEnvironment implements ITokenProvider {
* list just once per environment and cache the result.
*/
private void buildTransformerDelegationList() {
this.logger.debug("Rebuilding transformer delegation list:");
MixinEnvironment.logger.debug("Rebuilding transformer delegation list:");
this.transformers = new ArrayList<IClassTransformer>();
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
String transformerName = transformer.getClass().getName();
@@ -859,18 +921,18 @@ public class MixinEnvironment implements ITokenProvider {
}
}
if (include && !transformerName.contains(MixinTransformer.class.getName())) {
this.logger.debug(" Adding: {}", transformerName);
MixinEnvironment.logger.debug(" Adding: {}", transformerName);
this.transformers.add(transformer);
} else {
this.logger.debug(" Excluding: {}", transformerName);
MixinEnvironment.logger.debug(" Excluding: {}", transformerName);
}
}
this.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
this.logger.debug("Found name transformer: {}", transformer.getClass().getName());
MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName());
this.nameTransformer = (IClassNameTransformer) transformer;
}
}
@@ -904,7 +966,9 @@ public class MixinEnvironment implements ITokenProvider {
if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) {
MixinEnvironment.currentPhase = phase;
MixinEnvironment.getEnvironment(phase);
new MixinLogger();
@SuppressWarnings("unused")
MixinLogger logSpy = new MixinLogger();
}
}
@@ -943,6 +1007,30 @@ public class MixinEnvironment implements ITokenProvider {
return MixinEnvironment.currentEnvironment;
}
/**
* Get the current compatibility level
*/
public static CompatibilityLevel getCompatibilityLevel() {
return MixinEnvironment.compatibility;
}
/**
* Set desired compatibility level for the entire environment
*
* @param level Level to set, ignored if less than the current level
* @throws IllegalArgumentException if the specified level is not supported
*/
public static void setCompatibilityLevel(CompatibilityLevel level) throws IllegalArgumentException {
if (level != MixinEnvironment.compatibility && level.isAtLeast(MixinEnvironment.compatibility)) {
if (!level.isSupported()) {
throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported");
}
MixinEnvironment.compatibility = level;
MixinEnvironment.logger.info("Compatibility level set to {}", level);
}
}
/**
* Internal callback
*
@@ -237,6 +237,7 @@ public class MixinApplicator {
if (mixin.shouldSetSourceFile()) {
this.targetClass.sourceFile = mixin.getSourceFile();
}
this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion());
}
/**
@@ -676,9 +677,9 @@ public class MixinApplicator {
if (node instanceof JumpInsnNode) {
throw new InvalidMixinException(mixin, "Unsupported opcode in initialiser");
}
AbstractInsnNode iThinkWereACloneNow = node.clone(labels);
ctor.instructions.insert(insn, iThinkWereACloneNow);
insn = iThinkWereACloneNow;
AbstractInsnNode imACloneNow = node.clone(labels);
ctor.instructions.insert(insn, imACloneNow);
insn = imACloneNow;
}
return;
}
@@ -107,18 +107,18 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* Initial ClassNode created for mixin validation, not used for actual
* application
*/
ClassNode validationClassNode;
ClassNode classNode;
ValidationState(byte[] mixinBytes, ClassInfo classInfo) {
this.mixinBytes = mixinBytes;
this.validationClassNode = this.getClassNode(0);
this.classNode = this.getClassNode(0);
this.classInfo = classInfo;
}
ValidationState(byte[] mixinBytes) {
this.mixinBytes = mixinBytes;
this.validationClassNode = this.getClassNode(0);
this.classInfo = ClassInfo.fromClassNode(this.validationClassNode);
this.classNode = this.getClassNode(0);
this.classInfo = ClassInfo.fromClassNode(this.classNode);
}
/**
@@ -161,11 +161,11 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
if (!new HashSet<InterfaceInfo>(this.softImplements).equals(new HashSet<InterfaceInfo>(this.previous.softImplements))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces");
}
List<ClassInfo> targets = MixinInfo.this.readTargetClasses(this.validationClassNode, true);
List<ClassInfo> targets = MixinInfo.this.readTargetClasses(this.classNode, true);
if (!new HashSet<ClassInfo>(targets).equals(new HashSet<ClassInfo>(MixinInfo.this.getTargets0()))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change target classes");
}
int priority = MixinInfo.this.readPriority(this.validationClassNode);
int priority = MixinInfo.this.readPriority(this.classNode);
if (priority != MixinInfo.this.getPriority()) {
throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority");
}
@@ -270,7 +270,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
void validate() {
try {
ClassNode classNode = this.uninitialisedState.validationClassNode;
ClassNode classNode = this.uninitialisedState.classNode;
this.uninitialisedState.detachedSuper = this.validateTargetClasses(classNode);
this.validateMixin(this.uninitialisedState);
this.readImplementations(this.uninitialisedState);
@@ -280,7 +280,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
} else {
new MixinPreProcessor(this, classNode).prepare();
}
this.uninitialisedState.validationClassNode = null;
this.uninitialisedState.classNode = null;
// the state is now fully initialised and validated
this.validationState = this.uninitialisedState;
} finally {
@@ -392,14 +392,18 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
if (!state.classInfo.isProbablyStatic()) {
throw new InvalidMixinException(this, "Inner class mixin must be declared static");
}
if (state.classNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) {
throw new InvalidMixinException(this, "Unsupported mixin class version " + state.classNode.version);
}
// Can't have remappable fields or methods on a multi-target mixin, because after obfuscation the fields will remap to conflicting names
if (this.targetClasses.size() > 1) {
for (FieldNode field : state.validationClassNode.fields) {
for (FieldNode field : state.classNode.fields) {
this.checkRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class));
}
for (MethodNode method : state.validationClassNode.methods) {
for (MethodNode method : state.classNode.methods) {
this.checkRemappable(Shadow.class, method.name, ASMHelper.getVisibleAnnotation(method, Shadow.class));
AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class);
if (overwrite != null && ((method.access & Opcodes.ACC_STATIC) == 0 || (method.access & Opcodes.ACC_PUBLIC) == 0)) {
@@ -420,9 +424,9 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* Read and process any {@link Implements} annotations on the mixin
*/
private void readImplementations(ValidationState state) {
state.interfaces.addAll(state.validationClassNode.interfaces);
state.interfaces.addAll(state.classNode.interfaces);
AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(state.validationClassNode, Implements.class);
AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(state.classNode, Implements.class);
if (implementsAnnotation == null) {
return;
}
@@ -449,11 +453,11 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* config.
*/
private void readInnerClasses(ValidationState state) {
for (InnerClassNode inner : state.validationClassNode.innerClasses) {
for (InnerClassNode inner : state.classNode.innerClasses) {
ClassInfo innerClass = ClassInfo.forName(inner.name);
if (innerClass.isSynthetic() && innerClass.isProbablyStatic()) {
if ((inner.outerName != null && inner.outerName.equals(state.classInfo.getName()))
|| inner.name.startsWith(state.validationClassNode.name + "$")) {
|| inner.name.startsWith(state.classNode.name + "$")) {
state.syntheticInnerClasses.add(inner.name);
} else {
throw new InvalidMixinException(this, "Unhandled synthetic inner class found: " + inner.name);
@@ -130,7 +130,6 @@ class MixinPreProcessor {
MixinTargetContext createContextFor(ClassNode target) {
this.prepare();
MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target);
target.version = Math.max(this.classNode.version, target.version);
this.attach(context);
return context;
}
@@ -36,6 +36,8 @@ import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.injection.struct.Target;
@@ -99,6 +101,12 @@ public class MixinTargetContext implements IReferenceMapperContext {
* True if this mixin's superclass is detached from the target superclass
*/
private final boolean detachedSuper;
/**
* Minimum class version required to apply this mixin, target class will be
* upgraded if the version is below this value
*/
private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion();
/**
* ctor
@@ -114,6 +122,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.targetClassInfo = ClassInfo.forName(target.name);
this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy();
this.detachedSuper = !this.classNode.superName.equals(this.targetClass.superName);
this.requireVersion(classNode.version);
}
/**
@@ -192,6 +201,13 @@ public class MixinTargetContext implements IReferenceMapperContext {
public ClassInfo getTargetClassInfo() {
return this.targetClassInfo;
}
/**
* Get the minimum required class version for this mixin
*/
public int getMinRequiredClassVersion() {
return this.minRequiredClassVersion;
}
/**
* Find the corresponding class type for the supplied mixin class in this
@@ -352,6 +368,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param dynInsn Insn to transform
*/
private void transformInvokeDynamicNode(MethodNode method, Iterator<AbstractInsnNode> iter, InvokeDynamicInsnNode dynInsn) {
this.requireVersion(Opcodes.V1_7);
dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
for (int i = 0; i < dynInsn.bsmArgs.length; i++) {
@@ -608,6 +625,23 @@ public class MixinTargetContext implements IReferenceMapperContext {
return target;
}
/**
* Mark this mixin as requiring the specified class version in the context
* of the current target
*
* @param version version to require
*/
protected void requireVersion(int version) {
this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version);
// This validation is done on the mixin beforehand, however it's still
// possible that an upstream transformer can inject java 7 instructions
// without updating the class version.
if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) {
throw new InvalidMixinException(this, "Unsupported mixin class version " + version);
}
}
/**
* Get the mixin info for this mixin
*/
@@ -725,4 +759,5 @@ public class MixinTargetContext implements IReferenceMapperContext {
public void postApply(String transformedName, ClassNode targetClass) {
this.mixin.postApply(transformedName, targetClass);
}
}
@@ -0,0 +1,55 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Small helper to resolve the current java version
*/
public abstract class JavaVersion {
private static double current = 0.0;
private JavaVersion() {}
public static double current() {
if (JavaVersion.current == 0.0) {
JavaVersion.current = JavaVersion.resolveCurrentVersion();
}
return JavaVersion.current;
}
private static double resolveCurrentVersion() {
String version = System.getProperty("java.version");
Matcher matcher = Pattern.compile("[0-9]+\\.[0-9]+").matcher(version);
if (matcher.find()) {
return Double.parseDouble(matcher.group());
}
return 1.6;
}
}