();
ats.add((AnnotationNode)atValue);
} else {
- throw new InvalidInjectionException(type + " annotation on " + this.method.name + " is missing 'at' value(s)");
+ throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
}
MemberInfo targetMember = MemberInfo.parse(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
- throw new InvalidInjectionException(type + " annotation on " + this.method.name + " specifies a target class '"
+ throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
this.findMethods(targetMember);
if (this.targets.size() == 0) {
- throw new InvalidInjectionException(type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'");
+ throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'");
}
for (AnnotationNode at : ats) {
@@ -178,6 +178,15 @@ public abstract class InjectionInfo {
}
}
+ /**
+ * Get the mixin target context for this injection
+ *
+ * @return the target context
+ */
+ public MixinTargetContext getContext() {
+ return this.mixin;
+ }
+
/**
* Get the annotation which this InjectionInfo was created from
*
@@ -236,12 +245,13 @@ public abstract class InjectionInfo {
}
@SuppressWarnings("unchecked")
- public static InjectionInfo parse(MixinData mixin, MethodNode method) {
+ public static InjectionInfo parse(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = null;
try {
annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class);
} catch (IllegalArgumentException ex) {
- throw new InvalidMixinException("Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": " + ex.getMessage());
+ throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": "
+ + ex.getMessage());
}
if (annotation == null) {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java
index 85378c98..c6b7f25e 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java
@@ -28,12 +28,12 @@ import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.ModifyArgInjector;
-import org.spongepowered.asm.mixin.transformer.MixinData;
+import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
public class ModifyArgInjectionInfo extends InjectionInfo {
- public ModifyArgInjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) {
+ public ModifyArgInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
super(mixin, method, annotation);
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java
index b39948ed..28f5375c 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java
@@ -28,11 +28,11 @@ import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector;
-import org.spongepowered.asm.mixin.transformer.MixinData;
+import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
public class RedirectInjectionInfo extends InjectionInfo {
- public RedirectInjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) {
+ public RedirectInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
super(mixin, method, annotation);
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index 9f86e2d7..3f73578c 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -35,17 +35,184 @@ import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
+import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
/**
* Information about a class, used as a way of keeping track of class hierarchy
- * information needed to support mixins with detached targets.
+ * information needed to support more complex mixin behaviour such as detached
+ * superclass and mixin inheritance.
*/
class ClassInfo extends TreeInfo {
+ /**
+ * To all intents and purposes, the "real" class hierarchy and the mixin
+ * class hierarchy exist in parallel, this means that for some hierarchy
+ * validation operations we need to walk across to the other
+ * hierarchy in order to allow meaningful validation to occur.
+ *
+ * This enum defines the type of traversal operations which are allowed
+ * for a particular lookup.
+ *
+ * Each traversal type has a next property which defines
+ * the traversal type to use on the next step of the hierarchy
+ * validation. For example, the type {@link #IMMEDIATE} which requires an
+ * immediate match falls through to {@link #NONE} on the next step, which
+ * prevents further traversals from occurring in the lookup.
+ */
+ static enum Traversal {
+
+ /**
+ * No traversals are allowed.
+ */
+ NONE(null, false),
+
+ /**
+ * Traversal is allowed at all stages.
+ */
+ ALL(null, true),
+
+ /**
+ * Traversal is allowed at the bottom of the hierarchy but no further.
+ */
+ IMMEDIATE(Traversal.NONE, true),
+
+ /**
+ * Traversal is allowed only on superclasses and not at the bottom of
+ * the hierarchy.
+ */
+ SUPER(Traversal.ALL, false);
+
+ private final Traversal next;
+
+ private final boolean traverse;
+
+ private Traversal(Traversal next, boolean traverse) {
+ this.next = next != null ? next : this;
+ this.traverse = true;
+ }
+
+ public Traversal next() {
+ return this.next;
+ }
+
+ public boolean canTraverse() {
+ return this.traverse;
+ }
+ }
+
+ /**
+ * Information about a method in this class
+ */
+ class Method {
+
+ /**
+ * The original name of the method
+ */
+ private final String methodName;
+
+ /**
+ * The method signature
+ */
+ private final String methodDesc;
+
+ /**
+ * True if this method was injected by a mixin, false if it was
+ * originally part of the class
+ */
+ private final boolean isInjected;
+
+ /**
+ * Current name of the method, may be different from {@link methodName}
+ * if the method has been renamed
+ */
+ private String currentName;
+
+ public Method(MethodNode method) {
+ this(method, false);
+ }
+
+ public Method(Method method) {
+ this(method.methodName, method.methodDesc, method.isInjected);
+ this.currentName = method.currentName;
+ }
+
+ public Method(MethodNode method, boolean injected) {
+ this(method.name, method.desc, injected);
+ }
+
+ public Method(String name, String desc) {
+ this(name, desc, false);
+ }
+
+ public Method(String name, String desc, boolean injected) {
+ this.methodName = name;
+ this.methodDesc = desc;
+ this.isInjected = injected;
+ this.currentName = name;
+ }
+
+ public String getOriginalName() {
+ return this.methodName;
+ }
+
+ public String getName() {
+ return this.currentName;
+ }
+
+ public String getDesc() {
+ return this.methodDesc;
+ }
+
+ public boolean isInjected() {
+ return this.isInjected;
+ }
+
+ public boolean isRenamed() {
+ return this.currentName != this.methodName;
+ }
+
+ public ClassInfo getOwner() {
+ return ClassInfo.this;
+ }
+
+ public void renameTo(String name) {
+ this.currentName = name;
+ }
+
+ public boolean equals(String name, String desc) {
+ return (this.methodName.equals(name)
+ || this.currentName.equals(name))
+ && this.methodDesc.equals(desc);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof Method)) {
+ return false;
+ }
+
+ Method other = (Method)obj;
+ return (other.methodName.equals(this.methodName)
+ || other.currentName.equals(this.currentName))
+ && other.methodDesc.equals(this.methodDesc);
+ }
+
+ @Override
+ public int hashCode() {
+ return this.toString().hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return this.methodName + this.methodDesc;
+ }
+ }
+
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
/**
@@ -83,7 +250,7 @@ class ClassInfo extends TreeInfo {
/**
* Public and protected methods (instance) methods in this class
*/
- private final List methods;
+ private final Set methods;
/**
* Public and protected fields in this class
@@ -95,6 +262,12 @@ class ClassInfo extends TreeInfo {
*/
private final Set mixins = new HashSet();
+ /**
+ * Map of mixin types to corresponding supertypes, to avoid repeated
+ * lookups
+ */
+ private final Map correspondingTypes = new HashMap();
+
/**
* Mixin info if this class is a mixin itself
*/
@@ -132,18 +305,18 @@ class ClassInfo extends TreeInfo {
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.outerName = null;
- this.methods = ImmutableList.of(
- "getClass()Ljava/lang/Class;",
- "hashCode()I",
- "equals(Ljava/lang/Object;)Z",
- "clone()Ljava/lang/Object;",
- "toString()Ljava/lang/String;",
- "notify()V",
- "notifyAll()V",
- "wait(J)V",
- "wait(JI)V",
- "wait()V",
- "finalize()V"
+ this.methods = ImmutableSet.of(
+ new Method("getClass", "()Ljava/lang/Class;"),
+ new Method("hashCode", "()I"),
+ new Method("equals", "(Ljava/lang/Object;)Z"),
+ new Method("clone", "()Ljava/lang/Object;"),
+ new Method("toString", "()Ljava/lang/String;"),
+ new Method("notify", "()V"),
+ new Method("notifyAll", "()V"),
+ new Method("wait", "(J)V"),
+ new Method("wait", "(JI)V"),
+ new Method("wait", "()V"),
+ new Method("finalize", "()V")
);
this.fields = Collections.emptyList();
this.isInterface = false;
@@ -161,7 +334,7 @@ class ClassInfo extends TreeInfo {
private ClassInfo(ClassNode classNode) {
this.name = classNode.name;
this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT;
- this.methods = new ArrayList();
+ this.methods = new HashSet();
this.fields = new ArrayList();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = Collections.unmodifiableList(classNode.interfaces);
@@ -170,11 +343,7 @@ class ClassInfo extends TreeInfo {
this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
for (MethodNode method : classNode.methods) {
- if (!method.name.startsWith("<")
- && (method.access & Opcodes.ACC_PRIVATE) == 0
- && (method.access & Opcodes.ACC_STATIC) == 0) {
- this.methods.add(method.name + method.desc);
- }
+ this.addMethod(method, false);
}
String outerName = classNode.outerClass;
@@ -195,11 +364,23 @@ class ClassInfo extends TreeInfo {
this.outerName = outerName;
}
+
+ void addMethod(MethodNode method) {
+ this.addMethod(method, true);
+ }
+
+ private void addMethod(MethodNode method, boolean injected) {
+ if (!method.name.startsWith("<")
+ && (method.access & Opcodes.ACC_PRIVATE) == 0
+ && (method.access & Opcodes.ACC_STATIC) == 0) {
+ this.methods.add(new Method(method, injected));
+ }
+ }
/**
* Add a mixin which targets this class
*/
- public void addMixin(MixinInfo mixin) {
+ void addMixin(MixinInfo mixin) {
if (this.isMixin) {
throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin");
}
@@ -213,6 +394,13 @@ class ClassInfo extends TreeInfo {
return Collections.unmodifiableSet(this.mixins);
}
+ /**
+ * Get whether this class is a mixin
+ */
+ public boolean isMixin() {
+ return this.isMixin;
+ }
+
/**
* Get whether this class has ACC_PUBLIC
*/
@@ -311,82 +499,267 @@ class ClassInfo extends TreeInfo {
/**
* Test whether this class has the specified superclass in its hierarchy
- *
+ *
+ * @param superClass Name of the superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(String superClass) {
+ return this.hasSuperClass(superClass, Traversal.NONE);
+ }
+
+ /**
+ * Test whether this class has the specified superclass in its hierarchy
+ *
+ * @param superClass Name of the superclass to search for in the hierarchy
+ * @param traversal Traversal type to allow during this lookup
+ * @return true if the specified class appears in the class's hierarchy
+ * anywhere
+ */
+ public boolean hasSuperClass(String superClass, Traversal traversal) {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
return true;
}
- return this.hasSuperClass0(superClass);
- }
-
- private boolean hasSuperClass0(String superClass) {
- ClassInfo superClassInfo = this.getSuperClass();
- if (superClassInfo != null) {
- if (superClass.equals(superClassInfo.getName())) {
- return true;
- }
-
- for (ClassInfo superTarget : superClassInfo.targets()) {
- if (superTarget.hasSuperClass0(superClass)) {
- return true;
- }
- }
- }
-
- return false;
+ return this.findSuperClass(superClass, traversal) != null;
}
- public boolean isAssignableFrom(ClassInfo superClass) {
+ /**
+ * Test whether this class has the specified superclass in its hierarchy
+ *
+ * @param superClass Superclass to search for in the hierarchy
+ * @return true if the specified class appears in the class's hierarchy
+ * anywhere
+ */
+ public boolean hasSuperClass(ClassInfo superClass) {
+ return this.hasSuperClass(superClass, Traversal.NONE);
+ }
+
+ /**
+ * Test whether this class has the specified superclass in its hierarchy
+ *
+ * @param superClass Superclass to search for in the hierarchy
+ * @param traversal Traversal type to allow during this lookup
+ * @return true if the specified class appears in the class's hierarchy
+ * anywhere
+ */
+ public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) {
if (ClassInfo.OBJECT == superClass) {
return true;
}
-
- return this.isAssignableFrom0(superClass);
+
+ return this.findSuperClass(superClass.name, traversal) != null;
}
- private boolean isAssignableFrom0(ClassInfo superClass) {
+ /**
+ * Search for the specified superclass in this class's hierarchy. If found
+ * returns the ClassInfo, otherwise returns null
+ *
+ * @param superClass Superclass name to search for
+ * @return Matched superclass or null if not found
+ */
+ public ClassInfo findSuperClass(String superClass) {
+ return this.findSuperClass(superClass, Traversal.NONE);
+ }
+
+ /**
+ * Search for the specified superclass in this class's hierarchy. If found
+ * returns the ClassInfo, otherwise returns null
+ *
+ * @param superClass Superclass name to search for
+ * @param traversal Traversal type to allow during this lookup
+ * @return Matched superclass or null if not found
+ */
+ public ClassInfo findSuperClass(String superClass, Traversal traversal) {
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
- if (superClass == superClassInfo) {
- return true;
- }
+ List targets = superClassInfo.targets();
+ for (ClassInfo superTarget : targets) {
+ if (superClass.equals(superTarget.getName())) {
+ return superClassInfo;
+ }
- for (ClassInfo superTarget : superClassInfo.targets()) {
- if (superTarget.isAssignableFrom0(superClass)) {
- return true;
+ ClassInfo found = superTarget.findSuperClass(superClass, traversal.next());
+ if (found != null) {
+ return found;
}
}
}
+
+ if (traversal.canTraverse()) {
+ for (MixinInfo mixin : this.mixins) {
+ ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal);
+ if (targetSuper != null) {
+ return targetSuper;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Walks up this class's hierarchy to find the first class targetted by the
+ * specified mixin. This is used during mixin application to translate a
+ * mixin reference to a "real class" reference in the context of this
+ * class.
+ *
+ * @param mixin Mixin class to search for
+ * @return corresponding (target) class for the specified mixin or null if
+ * no corresponding mixin was found
+ */
+ ClassInfo findCorrespondingType(ClassInfo mixin) {
+ if (mixin == null || !mixin.isMixin || this.isMixin) {
+ return null;
+ }
+
+ ClassInfo correspondingType = this.correspondingTypes.get(mixin);
+ if (correspondingType == null) {
+ correspondingType = this.findSuperTypeForMixin(mixin);
+ this.correspondingTypes.put(mixin, correspondingType);
+ }
+ return correspondingType;
+ }
+
+ /* (non-Javadoc)
+ * Only used by findCorrespondingType(), used as a convenience so that
+ * sanity checks and caching can be handled more elegantly
+ */
+ private ClassInfo findSuperTypeForMixin(ClassInfo mixin) {
+ ClassInfo superClass = this;
+
+ while (superClass != null && superClass != ClassInfo.OBJECT) {
+ for (MixinInfo minion : superClass.mixins) {
+ if (minion.getClassInfo().equals(mixin)) {
+ return superClass;
+ }
+ }
+
+ superClass = superClass.getSuperClass();
+ }
+
+ return null;
+ }
+
+ /**
+ * Find out whether this (mixin) class has another mixin in its superclass
+ * hierarchy. This method always returns false for non-mixin classes.
+ *
+ * @return true if and only if one or more mixins are found in the hierarchy
+ * of this mixin
+ */
+ public boolean hasMixinInHierarchy() {
+ if (!this.isMixin) {
+ return false;
+ }
+
+ ClassInfo superClass = this.getSuperClass();
+
+ while (superClass != null && superClass != ClassInfo.OBJECT) {
+ if (superClass.isMixin) {
+ return true;
+ }
+ superClass = superClass.getSuperClass();
+ }
+
+ return false;
+ }
+
+ /**
+ * Find out whether this (non-mixin) class has a mixin targetting
+ * any of its superclasses. This method always returns false for
+ * mixin classes.
+ *
+ * @return true if and only if one or more classes in this class's hierarchy
+ * are targetted by a mixin
+ */
+ public boolean hasMixinTargetInHierarchy() {
+ if (this.isMixin) {
+ return false;
+ }
+
+ ClassInfo superClass = this.getSuperClass();
+
+ while (superClass != null && superClass != ClassInfo.OBJECT) {
+ if (superClass.mixins.size() > 0) {
+ return true;
+ }
+ superClass = superClass.getSuperClass();
+ }
return false;
}
/**
- * Finds the owner of the specified private or protected method in this
- * class's hierarchy
+ * Finds the specified private or protected method in this class's hierarchy
+ *
+ * @param method Method to search for
+ * @param includeThisClass True to return this class if the method exists
+ * here, or false to search only superclasses
+ * @return the method object or null if the method could not be resolved
+ */
+ public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass) {
+ return this.findMethodInHierarchy(method.name, method.desc, includeThisClass);
+ }
+
+ /**
+ * Finds the specified public or protected method in this class's hierarchy
+ *
+ * @param method Method to search for
+ * @param includeThisClass True to return this class if the method exists
+ * here, or false to search only superclasses
+ * @return the method object or null if the method could not be resolved
+ */
+ public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) {
+ return this.findMethodInHierarchy(method.name, method.desc, includeThisClass);
+ }
+
+ /**
+ * Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
- * @return the name of the class which contains the specified method or null
- * if the method could not be resolved
+ * @return the method object or null if the method could not be resolved
*/
- public String findMethodInHierarchy(String name, String desc, boolean includeThisClass) {
- if (includeThisClass && this.hasMethod(name, desc)) {
- return this.name;
+ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass) {
+ return this.findMethodInHierarchy(name, desc, includeThisClass, Traversal.NONE);
+ }
+
+ /**
+ * Finds the specified public or protected method in this class's hierarchy
+ *
+ * @param name Method name to search for
+ * @param desc Method descriptor
+ * @param includeThisClass True to return this class if the method exists
+ * here, or false to search only superclasses
+ * @param traversal Traversal type to allow during this lookup
+ * @return the method object or null if the method could not be resolved
+ */
+ public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
+ if (includeThisClass) {
+ Method method = this.findMethod(name, desc);
+ if (method != null) {
+ return method;
+ }
+
+ if (traversal.canTraverse()) {
+ for (MixinInfo mixin : this.mixins) {
+ Method mixinMethod = mixin.getClassInfo().findMethod(name, desc);
+ if (mixinMethod != null) {
+ return new Method(mixinMethod);
+ }
+ }
+ }
}
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
for (ClassInfo superTarget : superClassInfo.targets()) {
- String owner = superTarget.findMethodInHierarchy(name, desc, true);
- if (owner != null) {
- return owner;
+ Method method = superTarget.findMethodInHierarchy(name, desc, true, traversal.next());
+ if (method != null) {
+ return method;
}
}
}
@@ -395,14 +768,40 @@ class ClassInfo extends TreeInfo {
}
/**
- * Get whether this class has a public or protected non-static method
+ * Finds the specified public or protected method in this class
*
- * @param name Method name to search for
- * @param desc Method descriptor
- * @return true if the method is defined in this class or false otherwise
+ * @param method Method to search for
+ * @return the method object or null if the method could not be resolved
*/
- public boolean hasMethod(String name, String desc) {
- return this.methods.contains(name + desc);
+ public Method findMethod(MethodNode method) {
+ return this.findMethod(method.name, method.desc);
+ }
+
+ /**
+ * Finds the specified public or protected method in this class
+ *
+ * @param method Method to search for
+ * @return the method object or null if the method could not be resolved
+ */
+ public Method findMethod(MethodInsnNode method) {
+ return this.findMethod(method.name, method.desc);
+ }
+
+ /**
+ * Finds the specified public or protected method in this class
+ *
+ * @param method Method name to search for
+ * @param desc Method signature to search for
+ * @return the method object or null if the method could not be resolved
+ */
+ public Method findMethod(String name, String desc) {
+ for (Method method : this.methods) {
+ if (method.equals(name, desc)) {
+ return method;
+ }
+ }
+
+ return null;
}
/* (non-Javadoc)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java
index 340c2880..b78452ae 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java
@@ -33,7 +33,6 @@ import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.Implements;
-import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
@@ -43,6 +42,11 @@ import org.spongepowered.asm.util.ASMHelper;
*/
public class InterfaceInfo extends TreeInfo {
+ /**
+ * Parent mixin
+ */
+ private final MixinInfo mixin;
+
/**
* Prefix for interface methods. Any methods using this prefix must exist in
* the target interface
@@ -62,14 +66,16 @@ public class InterfaceInfo extends TreeInfo {
/**
* Make with the new thing already
*
+ * @param mixin Parent mixin
* @param prefix Method prefix
* @param iface Interface to load
*/
- private InterfaceInfo(String prefix, Type iface) {
+ private InterfaceInfo(MixinInfo mixin, String prefix, Type iface) {
if (prefix == null || prefix.length() < 2 || !prefix.endsWith("$")) {
- throw new InvalidMixinException(String.format("Prefix %s for iface %s is not valid", prefix, iface.toString()));
+ throw new InvalidMixinException(mixin, String.format("Prefix %s for iface %s is not valid", prefix, iface.toString()));
}
+ this.mixin = mixin;
this.prefix = prefix;
this.iface = iface;
}
@@ -94,7 +100,7 @@ public class InterfaceInfo extends TreeInfo {
ClassReader classReader = new ClassReader(TreeInfo.loadClass(ifaceName, true));
classReader.accept(ifaceNode, 0);
} catch (Exception ex) {
- throw new InvalidMixinException("An error was encountered parsing the interface " + this.iface.toString());
+ throw new InvalidMixinException(this.mixin, "An error was encountered parsing the interface " + this.iface.toString());
}
for (MethodNode ifaceMethod : ifaceNode.methods) {
@@ -156,7 +162,7 @@ public class InterfaceInfo extends TreeInfo {
String realName = method.name.substring(this.prefix.length());
String signature = realName + method.desc;
if (!this.methods.contains(signature)) {
- throw new InvalidMixinException(String.format("%s does not exist in target interface %s", realName, this.iface.toString()));
+ throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.iface.toString()));
}
method.name = realName;
@@ -167,17 +173,18 @@ public class InterfaceInfo extends TreeInfo {
* Convert an {@link Interface} annotation node into an
* {@link InterfaceInfo}
*
+ * @param mixin Parent mixin
* @param node Annotation node to process
* @return parsed InterfaceInfo object
*/
- static InterfaceInfo fromAnnotation(AnnotationNode node) {
+ static InterfaceInfo fromAnnotation(MixinInfo mixin, AnnotationNode node) {
String prefix = ASMHelper.getAnnotationValue(node, "prefix");
Type iface = ASMHelper.getAnnotationValue(node, "iface");
if (prefix == null || iface == null) {
- throw new InvalidMixinException(String.format("@Interface annotation on is missing a required parameter"));
+ throw new InvalidMixinException(mixin, String.format("@Interface annotation on is missing a required parameter"));
}
- return new InterfaceInfo(prefix, iface);
+ return new InterfaceInfo(mixin, prefix, iface);
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java
new file mode 100644
index 00000000..e7d9ee98
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java
@@ -0,0 +1,66 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.mixin.transformer;
+
+public class InvalidMixinException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ private final MixinInfo mixin;
+
+ public InvalidMixinException(MixinInfo mixin, String message) {
+ super(message);
+ this.mixin = mixin;
+ }
+
+ public InvalidMixinException(MixinTargetContext mixin, String message) {
+ super(message);
+ this.mixin = mixin.getInfo();
+ }
+
+ public InvalidMixinException(MixinInfo mixin, Throwable message) {
+ super(message);
+ this.mixin = mixin;
+ }
+
+ public InvalidMixinException(MixinTargetContext mixin, Throwable message) {
+ super(message);
+ this.mixin = mixin.getInfo();
+ }
+
+ public InvalidMixinException(MixinInfo mixin, String message, Throwable cause) {
+ super(message, cause);
+ this.mixin = mixin;
+ }
+
+ public InvalidMixinException(MixinTargetContext mixin, String message, Throwable cause) {
+ super(message, cause);
+ this.mixin = mixin.getInfo();
+ }
+
+ public MixinInfo getMixin() {
+ return this.mixin;
+ }
+}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
index 8166fa8b..35d70acb 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
@@ -52,10 +52,10 @@ public class MixinClassWriter extends ClassWriter {
ClassInfo c = ClassInfo.forName(type1);
ClassInfo d = ClassInfo.forName(type2);
- if (c.isAssignableFrom(d)) {
+ if (c.hasSuperClass(d)) {
return type1;
}
- if (d.isAssignableFrom(c)) {
+ if (d.hasSuperClass(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
@@ -68,7 +68,7 @@ public class MixinClassWriter extends ClassWriter {
return MixinClassWriter.JAVA_LANG_OBJECT;
}
- } while (!c.isAssignableFrom(d));
+ } while (!c.hasSuperClass(d));
return c.getName();
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java
index 2e2803bf..d38e57c0 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java
@@ -28,17 +28,22 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.Launch;
+import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.helpers.Booleans;
+import org.spongepowered.asm.launch.MixinInitialisationError;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
+import org.spongepowered.asm.util.VersionNumber;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
@@ -69,6 +74,26 @@ class MixinConfig implements Comparable {
*/
private final transient Map> mixinMapping = new HashMap>();
+ /**
+ * All mixins loaded by this config
+ */
+ private final transient List mixins = new ArrayList();
+
+ /**
+ * Minimum version of the mixin subsystem required to correctly apply mixins
+ * in this configuration.
+ */
+ @SerializedName("minVersion")
+ private String version;
+
+ /**
+ * Determines whether failures in this mixin config are considered terminal
+ * errors. Use this setting to indicate that failing to apply a mixin in
+ * this config is a critical error and should cause the game to shutdown.
+ */
+ @SerializedName("required")
+ private boolean required;
+
/**
* Configuration priority
*/
@@ -114,6 +139,12 @@ class MixinConfig implements Comparable {
@SerializedName("refmap")
private String refMapperConfig;
+ /**
+ * True to output "mixing in" messages at INFO level rather than DEBUG
+ */
+ @SerializedName("verbose")
+ private boolean verboseLogging;
+
/**
* Intrinsic order (for sorting configurations with identical priority)
*/
@@ -151,11 +182,29 @@ class MixinConfig implements Comparable {
private MixinConfig() {}
/**
- * Called immediately after deserialisation
+ * Called immediately after deserialisation
+ *
+ * @param name Mixin config name
+ * @return true if the config was successfully initialised and should be
+ * returned, or false if initialisation failed and the config should
+ * be discarded
*/
- private void onLoad(String name) {
+ private boolean onLoad(String name) {
this.name = name;
+ VersionNumber minVersion = VersionNumber.parse(this.version);
+ VersionNumber curVersion = VersionNumber.parse(MixinEnvironment.getCurrentEnvironment().getVersion());
+ if (minVersion.compareTo(curVersion) > 0) {
+ this.logger.warn("Mixin config {} requires mixin subsystem version {} but {} was found. The mixin config will not be applied.",
+ this.name, minVersion, curVersion);
+
+ if (this.required) {
+ throw new MixinInitialisationError("Required mixin config " + this.name + " requires mixin subsystem version " + minVersion);
+ }
+
+ return false;
+ }
+
if (this.pluginClassName != null) {
try {
Class> pluginClass = Class.forName(this.pluginClassName, true, Launch.classLoader);
@@ -174,8 +223,6 @@ class MixinConfig implements Comparable {
this.mixinPackage += ".";
}
- Launch.classLoader.addClassLoaderExclusion(this.mixinPackage);
-
if (this.refMapperConfig == null) {
if (this.plugin != null) {
this.refMapperConfig = this.plugin.getRefMapperConfig();
@@ -187,6 +234,9 @@ class MixinConfig implements Comparable {
}
this.refMapper = ReferenceMapper.read(this.refMapperConfig);
+ this.verboseLogging |= Booleans.parseBoolean(System.getProperty("mixin.debug.verbose"), false) | MixinTransformer.DEBUG_ALL;
+
+ return true;
}
/**
@@ -230,6 +280,27 @@ class MixinConfig implements Comparable {
List pluginMixins = this.plugin.getMixins();
this.initialiseMixins(pluginMixins, true);
}
+
+ for (Iterator iter = this.mixins.iterator(); iter.hasNext();) {
+ MixinInfo mixin = iter.next();
+ try {
+ mixin.validate();
+ } catch (Exception ex) {
+ this.logger.error(ex.getMessage(), ex);
+ this.removeMixin(mixin);
+ iter.remove();
+ }
+ }
+ }
+
+ private void removeMixin(MixinInfo remove) {
+ for (List mixinsFor : this.mixinMapping.values()) {
+ for (Iterator iter = mixinsFor.iterator(); iter.hasNext();) {
+ if (remove == iter.next()) {
+ iter.remove();
+ }
+ }
+ }
}
private void initialiseMixins(List mixinClasses, boolean suppressPlugin) {
@@ -249,12 +320,21 @@ class MixinConfig implements Comparable {
for (String targetClass : mixin.getTargetClasses()) {
this.mixinsFor(targetClass.replace('/', '.')).add(mixin);
}
+ this.mixins.add(mixin);
}
} catch (Exception ex) {
this.logger.error(ex.getMessage(), ex);
}
}
}
+
+ /**
+ * True if this mixin is required (failure to apply a defined mixin
+ * is an error condition).
+ */
+ public boolean isRequired() {
+ return this.required;
+ }
/**
* Get the name of the file from which this configuration object was
@@ -306,6 +386,13 @@ class MixinConfig implements Comparable {
public Set getTargets() {
return this.mixinMapping.keySet();
}
+
+ /**
+ * Get the logging level for this config
+ */
+ public Level getLoggingLevel() {
+ return this.verboseLogging ? Level.INFO : Level.DEBUG;
+ }
/**
* Check whether this configuration bundle has a mixin for the specified
@@ -336,6 +423,11 @@ class MixinConfig implements Comparable {
}
return mixins;
}
+
+ @Override
+ public String toString() {
+ return this.name;
+ }
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
@@ -361,8 +453,10 @@ class MixinConfig implements Comparable {
static MixinConfig create(String configFile) {
try {
MixinConfig config = new Gson().fromJson(new InputStreamReader(Launch.classLoader.getResourceAsStream(configFile)), MixinConfig.class);
- config.onLoad(configFile);
- return config;
+ if (config.onLoad(configFile)) {
+ return config;
+ }
+ return null;
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException(String.format("The specified configuration file '%s' was invalid or could not be read", configFile));
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java
deleted file mode 100644
index bc464663..00000000
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * This file is part of Sponge, licensed under the MIT License (MIT).
- *
- * Copyright (c) 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.mixin.transformer;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.tree.AbstractInsnNode;
-import org.objectweb.asm.tree.AnnotationNode;
-import org.objectweb.asm.tree.ClassNode;
-import org.objectweb.asm.tree.MethodInsnNode;
-import org.objectweb.asm.tree.MethodNode;
-import org.spongepowered.asm.mixin.Implements;
-import org.spongepowered.asm.mixin.Shadow;
-import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
-import org.spongepowered.asm.mixin.injection.struct.Target;
-import org.spongepowered.asm.util.ASMHelper;
-
-
-/**
- * Data for applying a mixin. Keeps a copy of the mixin tree and also handles
- * any pre-transformations required by the mixin class itself such as method
- * renaming and any other pre-processing of the mixin bytecode.
- */
-public class MixinData implements IReferenceMapperContext {
-
- /**
- * Mixin info
- */
- private final MixinInfo info;
-
- /**
- * Tree
- */
- private final ClassNode classNode;
-
- /**
- *
- */
- private final ClassNode targetClass;
-
- /**
- * Methods we need to rename
- */
- private final Map renamedMethods = new HashMap();
-
- /**
- * Interfaces soft-implemented using {@link Implements}
- */
- private final List softImplements = new ArrayList();
-
- /**
- * All interfaces implemented by this mixin, including soft implementations
- */
- private final Set interfaces = new HashSet();
-
- /**
- * Information about methods in the target class, used to keep track of
- * transformations we apply
- */
- private final Map targetMethods = new HashMap();
-
- /**
- * ctor
- *
- * @param info Mixin information
- * @param target target class
- */
- MixinData(MixinInfo info, ClassNode target) {
- this.info = info;
- this.classNode = info.getClassNode(ClassReader.EXPAND_FRAMES);
- this.targetClass = target;
- this.prepare();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return String.format("%s:%s", this.info.getParent().getName(), this.info.getName());
- }
-
- /**
- * Get the mixin tree
- *
- * @return mixin tree
- */
- public ClassNode getClassNode() {
- return this.classNode;
- }
-
- /**
- * Get the mixin class name
- *
- * @return the mixin class name
- */
- public String getClassName() {
- return this.info.getClassName();
- }
-
- /* (non-Javadoc)
- * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext
- * #getClassRef()
- */
- @Override
- public String getClassRef() {
- return this.info.getClassRef();
- }
-
- /**
- * Get the target class reference
- *
- * @return the reference of the target class (only valid on single-target
- * mixins)
- */
- public String getTargetClassRef() {
- return this.targetClass.name;
- }
-
- /**
- * Get the target class
- *
- * @return the target class
- */
- public ClassNode getTargetClass() {
- return this.targetClass;
- }
-
- /**
- * Get a target method handle from the target class
- *
- * @param method method to get a target handle for
- * @return new or existing target handle for the supplied method
- */
- public Target getTargetMethod(MethodNode method) {
- if (!this.targetClass.methods.contains(method)) {
- throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()");
- }
-
- String targetName = method.name + method.desc;
- Target target = this.targetMethods.get(targetName);
- if (target == null) {
- target = new Target(method);
- this.targetMethods.put(targetName, target);
- }
- return target;
- }
-
- /**
- * Get the mixin priority
- *
- * @return the priority (only meaningful in relation to other mixins)
- */
- public int getPriority() {
- return this.info.getPriority();
- }
-
- /**
- * Get all interfaces for this mixin
- *
- * @return mixin interfaces
- */
- public Set getInterfaces() {
- return this.interfaces;
- }
-
- /**
- * Get whether to propogate the source file attribute from a mixin onto the
- * target class
- *
- * @return true if the sourcefile property should be set on the target class
- */
- public boolean shouldSetSourceFile() {
- return this.info.getParent().shouldSetSourceFile();
- }
-
- /* (non-Javadoc)
- * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext
- * #getReferenceMapper()
- */
- @Override
- public ReferenceMapper getReferenceMapper() {
- return this.info.getParent().getReferenceMapper();
- }
-
- /**
- * Prepare the mixin, applies any pre-processing transformations
- */
- private void prepare() {
- this.readImplementations();
- this.findRenamedMethods();
- this.transformMethods();
- }
-
- /**
- * Read and process any {@link Implements} annotations on the mixin
- */
- private void readImplementations() {
- this.interfaces.addAll(this.classNode.interfaces);
-
- AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(this.classNode, Implements.class);
- if (implementsAnnotation == null) {
- return;
- }
-
- List interfaces = ASMHelper.getAnnotationValue(implementsAnnotation);
- if (interfaces == null) {
- return;
- }
-
- for (AnnotationNode interfaceNode : interfaces) {
- InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(interfaceNode);
- this.softImplements.add(interfaceInfo);
- this.interfaces.add(interfaceInfo.getInternalName());
- }
- }
-
- /**
- * Let's do this
- */
- private void findRenamedMethods() {
- for (MethodNode mixinMethod : this.classNode.methods) {
- String oldSignature = mixinMethod.name + mixinMethod.desc;
- AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class);
- if (shadowAnnotation != null) {
- String prefix = MixinData.getAnnotationValue(shadowAnnotation, "prefix", Shadow.class);
- if (mixinMethod.name.startsWith(prefix)) {
- String newName = mixinMethod.name.substring(prefix.length());
- this.renamedMethods.put(oldSignature, newName);
- mixinMethod.name = newName;
- }
- }
-
- for (InterfaceInfo iface : this.softImplements) {
- if (iface.renameMethod(mixinMethod)) {
- this.renamedMethods.put(oldSignature, mixinMethod.name);
- }
- }
- }
- }
-
- /**
- * Apply discovered method renames to method invokations in the mixin
- */
- private void transformMethods() {
- for (MethodNode mixinMethod : this.classNode.methods) {
- for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
- AbstractInsnNode insn = iter.next();
- if (insn instanceof MethodInsnNode) {
- MethodInsnNode methodNode = (MethodInsnNode)insn;
- String newName = this.renamedMethods.get(methodNode.name + methodNode.desc);
- if (newName != null) {
- methodNode.name = newName;
- }
- }
- }
- }
- }
-
- /**
- * Gets an annotation value or returns the default if the annotation value
- * is not present
- *
- * @param annotation
- * @param key
- * @param annotationClass
- * @return Value of the specified annotation node, default value if not
- * specified, or null if no value or default
- */
- private static String getAnnotationValue(AnnotationNode annotation, String key, Class> annotationClass) {
- String value = ASMHelper.getAnnotationValue(annotation, key);
- if (value == null) {
- try {
- value = (String)annotationClass.getDeclaredMethod(key).getDefaultValue();
- } catch (NoSuchMethodException ex) {
- // Don't care
- }
- }
- return value;
- }
-
- /**
- * Called immediately before the mixin is applied to targetClass
- *
- * @param transformedName Target class's transformed name
- * @param targetClass Target class
- */
- public void preApply(String transformedName, ClassNode targetClass) {
- this.info.preApply(transformedName, targetClass);
- }
-
- /**
- * Called immediately after the mixin is applied to targetClass
- *
- * @param transformedName Target class's transformed name
- * @param targetClass Target class
- */
- public void postApply(String transformedName, ClassNode targetClass) {
- this.info.postApply(transformedName, targetClass);
- }
-}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
index e5357f67..507a5c9e 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
@@ -25,20 +25,36 @@
package org.spongepowered.asm.mixin.transformer;
import java.io.IOException;
+import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
+import java.util.Set;
+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.objectweb.asm.ClassReader;
+import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
+import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
-import org.spongepowered.asm.mixin.InvalidMixinException;
+import org.objectweb.asm.tree.FieldNode;
+import org.objectweb.asm.tree.MethodInsnNode;
+import org.objectweb.asm.tree.MethodNode;
+import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.Overwrite;
+import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
+import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Function;
@@ -56,6 +72,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
*/
static int mixinOrder = 0;
+ static final Set invalidClasses = MixinInfo.$getInvalidClassesSet();
+
/**
* Logger
*/
@@ -96,12 +114,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
*/
private final List targetClassNames;
- /**
- * True if the superclass of the mixin is not the direct superclass
- * of one or more targets
- */
- private final boolean detachedSuper;
-
/**
* Intrinsic order (for sorting mixins with identical priority)
*/
@@ -116,6 +128,28 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* Configuration plugin
*/
private final transient IMixinConfigPlugin plugin;
+
+ /**
+ * All interfaces implemented by this mixin, including soft implementations
+ */
+ private final transient Set interfaces = new HashSet();
+
+ /**
+ * Interfaces soft-implemented using {@link Implements}
+ */
+ private final transient List softImplements = new ArrayList();
+
+ /**
+ * Initial ClassNode created for mixin validation, not used for actual
+ * application
+ */
+ private ClassNode validationClassNode;
+
+ /**
+ * True if the superclass of the mixin is not the direct superclass
+ * of one or more targets
+ */
+ private boolean detachedSuper;
/**
* Internal ctor, called by {@link MixinConfig}
@@ -138,29 +172,19 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
this.mixinBytes = this.loadMixinClass(this.className, runTransformers);
ClassNode classNode = this.getClassNode(0);
- this.classInfo = this.readInfo(classNode);
+ this.classInfo = ClassInfo.fromClassNode(classNode);
this.priority = this.readPriority(classNode);
this.targetClasses = this.readTargetClasses(classNode, suppressPlugin);
this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction()));
- this.detachedSuper = this.validateTargetClasses(classNode);
+ this.validationClassNode = classNode;
}
-
- /**
- * Initialises the class info and performs some pre-flight checks on the
- * mixin
- *
- * @param classNode
- * @return
- */
- private ClassInfo readInfo(ClassNode classNode) {
- ClassInfo classInfo = ClassInfo.fromClassNode(classNode);
-
- // isInner (shouldn't) return true for static inner classes
- if (classInfo.isInner()) {
- throw new InvalidMixinException("Inner class mixin must be declared static");
- }
-
- return classInfo;
+
+ void validate() {
+ this.detachedSuper = this.validateTargetClasses(this.validationClassNode);
+ this.validateMixin(this.validationClassNode);
+ this.readImplementations(this.validationClassNode);
+ this.prepare(this.validationClassNode);
+ this.validationClassNode = null;
}
/**
@@ -173,7 +197,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
private List readTargetClasses(ClassNode classNode, boolean suppressPlugin) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
- throw new InvalidMixinException(String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
+ throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
List targets = new ArrayList();
@@ -205,10 +229,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetClassName, this.className)) {
ClassInfo targetInfo = ClassInfo.forName(targetClassName);
if (targetInfo.isInterface()) {
- throw new InvalidMixinException("@Mixin target " + targetClassName + " is an interface in " + this);
+ throw new InvalidMixinException(this, "@Mixin target " + targetClassName + " is an interface in " + this);
}
if (checkPublic && targetInfo.isPublic()) {
- throw new InvalidMixinException("@Mixin target " + targetClassName + " is public in " + this + " and must be specified in value");
+ throw new InvalidMixinException(this, "@Mixin target " + targetClassName + " is public in " + this
+ + " and must be specified in value");
}
if (!outTargets.contains(targetInfo)) {
outTargets.add(targetInfo);
@@ -227,13 +252,13 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
private int readPriority(ClassNode classNode) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
- throw new InvalidMixinException(String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
+ throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
Integer priority = ASMHelper.getAnnotationValue(mixin, "priority");
return priority == null ? 1000 : priority.intValue();
}
-
+
private boolean validateTargetClasses(ClassNode classNode) {
boolean detached = false;
@@ -243,8 +268,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
continue;
}
- if (!targetClass.hasSuperClass(classNode.superName)) {
- throw new InvalidMixinException("Super class '" + classNode.superName.replace('/', '.') + "' of " + this.name
+ if (!targetClass.hasSuperClass(classNode.superName, ClassInfo.Traversal.NONE)) {
+ throw new InvalidMixinException(this, "Super class '" + classNode.superName.replace('/', '.') + "' of " + this.name
+ " was not found in the hierarchy of target class '" + targetClass + "'");
}
@@ -254,6 +279,119 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
return detached;
}
+ /**
+ * Performs pre-flight checks on the mixin
+ *
+ * @param classNode
+ */
+ private void validateMixin(ClassNode classNode) {
+ // isInner (shouldn't) return true for static inner classes
+ if (this.classInfo.isInner()) {
+ throw new InvalidMixinException(this, "Inner class mixin must be declared static");
+ }
+
+ // 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 : classNode.fields) {
+ this.checkRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class));
+ }
+
+ for (MethodNode method : 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)) {
+ throw new InvalidMixinException(this, "Found @Overwrite annotation on " + method.name + " in " + this);
+ }
+ }
+ }
+ }
+
+ private void checkRemappable(Class annotationClass, String name, AnnotationNode annotation) {
+ if (annotation != null && ASMHelper.getAnnotationValue(annotation, "remap", Boolean.TRUE)) {
+ throw new InvalidMixinException(this, "Found a remappable @" + annotationClass.getSimpleName() + " annotation on " + name
+ + " in " + this);
+ }
+ }
+
+ /**
+ * Prepare the mixin, applies any pre-processing transformations
+ */
+ private ClassNode prepare(ClassNode classNode) {
+ this.findRenamedMethods(classNode);
+ this.transformMethods(classNode);
+ return classNode;
+ }
+
+ /**
+ * Read and process any {@link Implements} annotations on the mixin
+ */
+ private void readImplementations(ClassNode classNode) {
+ this.interfaces.addAll(classNode.interfaces);
+
+ AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(classNode, Implements.class);
+ if (implementsAnnotation == null) {
+ return;
+ }
+
+ List interfaces = ASMHelper.getAnnotationValue(implementsAnnotation);
+ if (interfaces == null) {
+ return;
+ }
+
+ for (AnnotationNode interfaceNode : interfaces) {
+ InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(this, interfaceNode);
+ this.softImplements.add(interfaceInfo);
+ this.interfaces.add(interfaceInfo.getInternalName());
+ }
+ }
+
+ /**
+ * Let's do this
+ */
+ private void findRenamedMethods(ClassNode classNode) {
+ for (MethodNode mixinMethod : classNode.methods) {
+ Method method = this.classInfo.findMethod(mixinMethod);
+
+ AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class);
+ if (shadowAnnotation != null) {
+ String prefix = ASMHelper.getAnnotationValue(shadowAnnotation, "prefix", Shadow.class);
+ if (mixinMethod.name.startsWith(prefix)) {
+ String newName = mixinMethod.name.substring(prefix.length());
+ method.renameTo(newName);
+ mixinMethod.name = newName;
+ }
+ }
+
+ for (InterfaceInfo iface : this.softImplements) {
+ if (iface.renameMethod(mixinMethod)) {
+ method.renameTo(mixinMethod.name);
+ }
+ }
+ }
+ }
+
+ /**
+ * Apply discovered method renames to method invokations in the mixin
+ */
+ private void transformMethods(ClassNode classNode) {
+ for (MethodNode mixinMethod : classNode.methods) {
+ for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
+ AbstractInsnNode insn = iter.next();
+ if (insn instanceof MethodInsnNode) {
+ MethodInsnNode methodNode = (MethodInsnNode)insn;
+ Method method = this.classInfo.findMethodInHierarchy(methodNode, true);
+ if (method != null && method.isRenamed()) {
+ methodNode.name = method.getName();
+ }
+ }
+ }
+ }
+ }
+
+ ClassInfo getClassInfo() {
+ return this.classInfo;
+ }
+
/**
* Get the parent config which declares this mixin
*/
@@ -302,6 +440,13 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
return this.detachedSuper;
}
+ /**
+ * Get the logging level for this mixin
+ */
+ public Level getLoggingLevel() {
+ return this.parent.getLoggingLevel();
+ }
+
/**
* Get a new tree for the class bytecode
*/
@@ -335,15 +480,25 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
public int getPriority() {
return this.priority;
}
-
+
/**
- * Get a new mixin data container for this info
+ * Get all interfaces for this mixin
+ *
+ * @return mixin interfaces
+ */
+ public Set getInterfaces() {
+ return this.interfaces;
+ }
+
+ /**
+ * Get a new mixin target context object for the specified target
*
* @param target
* @return
*/
- public MixinData createData(ClassNode target) {
- return new MixinData(this, target);
+ public MixinTargetContext createContextForTarget(ClassNode target) {
+ ClassNode classNode = this.getClassNode(ClassReader.EXPAND_FRAMES);
+ return new MixinTargetContext(this, this.prepare(classNode), target);
}
/**
@@ -361,7 +516,14 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
throw new ClassNotFoundException(String.format("The specified mixin '%s' was not found", mixinClassName));
} catch (IOException ex) {
this.logger.warn("Failed to load mixin %s, the specified mixin will not be applied", mixinClassName);
- throw new InvalidMixinException("An error was encountered whilst loading the mixin class", ex);
+ throw new InvalidMixinException(this, "An error was encountered whilst loading the mixin class", ex);
+ }
+
+ // Inject the mixin class name into the LaunchClassLoader's invalid
+ // classes set so that any classes referencing the mixin directly will
+ // cause the game to crash
+ if (MixinInfo.invalidClasses != null) {
+ MixinInfo.invalidClasses.add(mixinClassName);
}
return mixinBytes;
@@ -398,4 +560,24 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
this.plugin.postApply(transformedName, targetClass, this.className, this);
}
}
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return String.format("%s:%s", this.parent.getName(), this.name);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Set $getInvalidClassesSet() {
+ try {
+ Field invalidClasses = LaunchClassLoader.class.getDeclaredField("invalidClasses");
+ invalidClasses.setAccessible(true);
+ return (Set)invalidClasses.get(Launch.classLoader);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ return null;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
new file mode 100644
index 00000000..70bb9be1
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -0,0 +1,548 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.mixin.transformer;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+import org.objectweb.asm.tree.AbstractInsnNode;
+import org.objectweb.asm.tree.ClassNode;
+import org.objectweb.asm.tree.FieldInsnNode;
+import org.objectweb.asm.tree.FieldNode;
+import org.objectweb.asm.tree.MethodInsnNode;
+import org.objectweb.asm.tree.MethodNode;
+import org.objectweb.asm.tree.TypeInsnNode;
+import org.spongepowered.asm.mixin.SoftOverride;
+import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
+import org.spongepowered.asm.mixin.injection.struct.Target;
+import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
+import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
+import org.spongepowered.asm.util.ASMHelper;
+
+
+/**
+ * This object keeps track of data for applying a mixin to a specific target
+ * class during a mixin application. This is a single-use object which
+ * acts as both a handle information we need when applying the mixin (such as
+ * the actual mixin ClassNode and the target ClassNode) and a gateway to
+ * context-sensitive operations such as re-targetting method and field accesses
+ * in the mixin to the appropriate members in the target class hierarchy.
+ */
+public class MixinTargetContext implements IReferenceMapperContext {
+
+ private static final String INIT = "";
+ private static final String IMAGINARY_SUPER = "super$";
+
+ /**
+ * Mixin info
+ */
+ private final MixinInfo mixin;
+
+ /**
+ * Tree
+ */
+ private final ClassNode classNode;
+
+ /**
+ *
+ */
+ private final ClassNode targetClass;
+
+ /**
+ * Target ClassInfo
+ */
+ private final ClassInfo targetClassInfo;
+
+ /**
+ * Information about methods in the target class, used to keep track of
+ * transformations we apply
+ */
+ private final Map targetMethods = new HashMap();
+
+ /**
+ * True if this mixin inherits from a mixin at any point in its hierarchy
+ */
+ private final boolean inheritsFromMixin;
+
+ /**
+ * True if this mixin's superclass is detached from the target superclass
+ */
+ private final boolean detachedSuper;
+
+ /**
+ * ctor
+ *
+ * @param info Mixin information
+ * @param mixin Mixin classnode
+ * @param target target class
+ */
+ MixinTargetContext(MixinInfo info, ClassNode mixin, ClassNode target) {
+ this.mixin = info;
+ this.classNode = mixin;
+ this.targetClass = target;
+ this.targetClassInfo = ClassInfo.forName(target.name);
+ this.inheritsFromMixin = info.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy();
+ this.detachedSuper = !this.getClassNode().superName.equals(this.targetClass.superName);
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return this.mixin.toString();
+ }
+
+ /**
+ * Get the mixin tree
+ *
+ * @return mixin tree
+ */
+ public ClassNode getClassNode() {
+ return this.classNode;
+ }
+
+ /**
+ * Get the mixin class name
+ *
+ * @return the mixin class name
+ */
+ public String getClassName() {
+ return this.mixin.getClassName();
+ }
+
+ /* (non-Javadoc)
+ * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext
+ * #getClassRef()
+ */
+ @Override
+ public String getClassRef() {
+ return this.mixin.getClassRef();
+ }
+
+ /**
+ * Get the target class reference
+ *
+ * @return the reference of the target class (only valid on single-target
+ * mixins)
+ */
+ public String getTargetClassRef() {
+ return this.targetClass.name;
+ }
+
+ /**
+ * Get the target class
+ *
+ * @return the target class
+ */
+ public ClassNode getTargetClass() {
+ return this.targetClass;
+ }
+
+ /**
+ * Get the target classinfo
+ *
+ * @return the target class info
+ */
+ public ClassInfo getTargetClassInfo() {
+ return this.targetClassInfo;
+ }
+
+ /**
+ * Find the corresponding class type for the supplied mixin class in this
+ * mixin target's hierarchy
+ *
+ * @param mixin Mixin class to discover
+ * @return Transformed
+ */
+ public ClassInfo findRealType(ClassInfo mixin) {
+ if (mixin == this.mixin.getClassInfo()) {
+ return this.targetClassInfo;
+ }
+
+ ClassInfo type = this.targetClassInfo.findCorrespondingType(mixin);
+ if (type == null) {
+ throw new InvalidMixinException(this, "Resolution error: unable to find corresponding type for "
+ + mixin + " in hierarchy of " + this.targetClassInfo);
+ }
+
+ return type;
+ }
+
+ /**
+ * Transforms field descriptors which contain mixin types to their
+ * appropriate target type
+ *
+ * @param field Field to transform
+ * @return true if the field should be processed further, false to remove it
+ */
+ public boolean transformField(FieldNode field) {
+ if (MixinTargetContext.IMAGINARY_SUPER.equals(field.name)) {
+ if (field.access != Opcodes.ACC_PRIVATE) {
+ throw new InvalidMixinException(this, "Imaginary super field " + field.name + " must be private and non-final");
+ }
+ if (!field.desc.equals("L" + this.mixin.getClassRef() + ";")) {
+ throw new InvalidMixinException(this, "Imaginary super field " + field.name + " must have the same type as the parent mixin");
+ }
+ return false;
+ }
+
+ this.transformDescriptor(field);
+ return true;
+ }
+
+ /**
+ * Handles "re-parenting" the method supplied, changes all references to the
+ * mixin class to refer to the target class (for field accesses and method
+ * invokations) and also handles fixing up the targets of INVOKESPECIAL
+ * opcodes for mixins with detached targets.
+ *
+ * @param method Method to transform
+ */
+ public void transformMethod(MethodNode method) {
+ // Any method tagged with @SoftOverride must have an implementation visible from
+ if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) != null) {
+ Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER);
+ if (superMethod == null || !superMethod.isInjected()) {
+ throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no "
+ + "valid method was found in superclasses of " + this.targetClass.name);
+ }
+ }
+
+ this.transformDescriptor(method);
+
+ Iterator iter = method.instructions.iterator();
+ while (iter.hasNext()) {
+ AbstractInsnNode insn = iter.next();
+
+ if (insn instanceof MethodInsnNode) {
+ MethodInsnNode methodInsn = (MethodInsnNode)insn;
+ this.transformDescriptor(methodInsn);
+ if (methodInsn.owner.equals(this.getClassRef())) {
+ methodInsn.owner = this.targetClass.name;
+ } else if ((this.detachedSuper || this.inheritsFromMixin)) {
+ if (methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) {
+ this.updateStaticBinding(method, methodInsn);
+ } else if (methodInsn.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodInsn.owner).isMixin()) {
+ this.updateDynamicBinding(method, methodInsn);
+ }
+ }
+ } else if (insn instanceof FieldInsnNode) {
+ FieldInsnNode fieldInsn = (FieldInsnNode)insn;
+ if (MixinTargetContext.IMAGINARY_SUPER.equals(fieldInsn.name)) {
+ this.processImaginarySuper(method, fieldInsn);
+ iter.remove();
+ }
+ this.transformDescriptor(fieldInsn);
+ if (fieldInsn.owner.equals(this.getClassRef())) {
+ fieldInsn.owner = this.targetClass.name;
+ }
+ } else if (insn instanceof TypeInsnNode) {
+ TypeInsnNode typeInsn = (TypeInsnNode)insn;
+ if (typeInsn.desc.equals(this.getClassRef())) {
+ typeInsn.desc = this.targetClass.name;
+ }
+ this.transformDescriptor(typeInsn);
+ }
+ }
+ }
+
+ /**
+ * Handle "imaginary super" invokations, these are invokations in
+ * non-derived mixins for accessing methods known to exist in a supermixin
+ * which is not directly inherited by this mixix. The method can only call
+ * its own super-implmentation and the methd must also be tagged with
+ * {@link SoftOverride} to indicate that the method must exist in a super
+ * class.
+ *
+ * @param method Method being processed
+ * @param fieldInsn the GETFIELD insn which access the pseudo-field which is
+ * used as a handle to the superclass
+ */
+ private void processImaginarySuper(MethodNode method, FieldInsnNode fieldInsn) {
+ if (fieldInsn.getOpcode() != Opcodes.GETFIELD) {
+ if (MixinTargetContext.INIT.equals(method.name)) {
+ throw new InvalidMixinException(this, "Illegal imaginary super declaration: field " + fieldInsn.name
+ + " must not specify an initialiser");
+ }
+
+ throw new InvalidMixinException(this, "Illegal imaginary super access: found " + ASMHelper.getOpcodeName(fieldInsn.getOpcode())
+ + " opcode in " + method.name + method.desc);
+ }
+
+ if ((method.access & Opcodes.ACC_PRIVATE) != 0 || (method.access & Opcodes.ACC_STATIC) != 0) {
+ throw new InvalidMixinException(this, "Illegal imaginary super access: method " + method.name + method.desc
+ + " is private or static");
+ }
+
+ if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) == null) {
+ throw new InvalidMixinException(this, "Illegal imaginary super access: method " + method.name + method.desc
+ + " is not decorated with @SoftOverride");
+ }
+
+ for (Iterator methodIter = method.instructions.iterator(method.instructions.indexOf(fieldInsn)); methodIter.hasNext();) {
+ AbstractInsnNode insn = methodIter.next();
+ if (insn instanceof MethodInsnNode) {
+ MethodInsnNode methodNode = (MethodInsnNode)insn;
+ if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) {
+ methodNode.setOpcode(Opcodes.INVOKESPECIAL);
+ this.updateStaticBinding(method, methodNode);
+ return;
+ }
+ }
+ }
+
+ throw new InvalidMixinException(this, "Illegal imaginary super access: could not find INVOKE for " + method.name + method.desc);
+ }
+
+ /**
+ * Update INVOKESPECIAL opcodes to target the topmost class in the hierarchy
+ * which contains the specified method.
+ *
+ * @param method Method containing the instruction
+ * @param insn INVOKE instruction node
+ */
+ private void updateStaticBinding(MethodNode method, MethodInsnNode insn) {
+ this.updateBinding(method, insn, Traversal.SUPER);
+ }
+
+ /**
+ * Update INVOKEVIRTUAL opcodes to target the topmost class in the hierarchy
+ * which contains the specified method.
+ *
+ * @param method Method containing the instruction
+ * @param insn INVOKE instruction node
+ */
+ private void updateDynamicBinding(MethodNode method, MethodInsnNode insn) {
+ this.updateBinding(method, insn, Traversal.ALL);
+ }
+
+ private void updateBinding(MethodNode method, MethodInsnNode insn, Traversal traversal) {
+ if (INIT.equals(method.name) || insn.owner.equals(this.targetClass.name) || this.targetClass.name.startsWith("<")) {
+ return;
+ }
+
+ Method superMethod = this.targetClassInfo.findMethodInHierarchy(insn.name, insn.desc, traversal == Traversal.ALL, traversal);
+ if (superMethod != null) {
+ if (superMethod.getOwner().isMixin()) {
+ throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(insn) + " in " + this + " resolved " + insn.owner
+ + " -> " + superMethod.getOwner() + " for " + insn.name + insn.desc);
+ }
+ insn.owner = superMethod.getOwner().getName();
+ } else if (ClassInfo.forName(insn.owner).isMixin()) {
+ throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(insn) + " target for " + insn.owner + "." + insn.name
+ + " in " + this);
+ }
+ }
+
+ /**
+ * Transforms a field descriptor in the context of this mixin target
+ *
+ * @param field Field node to transform
+ */
+ public void transformDescriptor(FieldNode field) {
+ if (!this.inheritsFromMixin) {
+ return;
+ }
+ field.desc = this.transformSingleDescriptor(field.desc, false);
+ }
+
+ /**
+ * Transforms a field insn descriptor in the context of this mixin target
+ *
+ * @param field Field instruction node to transform
+ */
+ public void transformDescriptor(FieldInsnNode field) {
+ if (!this.inheritsFromMixin) {
+ return;
+ }
+ field.desc = this.transformSingleDescriptor(field.desc, false);
+ }
+
+ /**
+ * Transforms a method descriptor in the context of this mixin target
+ *
+ * @param method Method node to transform
+ */
+ public void transformDescriptor(MethodNode method) {
+ if (!this.inheritsFromMixin) {
+ return;
+ }
+ method.desc = this.transformMethodDescriptor(method.desc);
+ }
+
+ /**
+ * Transforms a method insn descriptor in the context of this mixin target
+ *
+ * @param method Method instruction node to transform
+ */
+ public void transformDescriptor(MethodInsnNode method) {
+ if (!this.inheritsFromMixin) {
+ return;
+ }
+ method.desc = this.transformMethodDescriptor(method.desc);
+ }
+
+ /**
+ * Transforms a type insn descriptor in the context of this mixin target
+ *
+ * @param typeInsn Type instruction node to transform
+ */
+ public void transformDescriptor(TypeInsnNode typeInsn) {
+ if (!this.inheritsFromMixin) {
+ return;
+ }
+ typeInsn.desc = this.transformSingleDescriptor(typeInsn.desc, true);
+ }
+
+ private String transformSingleDescriptor(Type type) {
+ if (type.getSort() < Type.ARRAY) {
+ return type.toString();
+ }
+
+ return this.transformSingleDescriptor(type.toString(), false);
+ }
+
+ private String transformSingleDescriptor(String desc, boolean isObject) {
+ String type = desc;
+ while (type.startsWith("[") || type.startsWith("L")) {
+ if (type.startsWith("[")) {
+ type = type.substring(1);
+ continue;
+ }
+ type = type.substring(1, type.indexOf(";"));
+ isObject = true;
+ }
+
+ if (!isObject) {
+ return desc;
+ }
+
+ ClassInfo typeInfo = ClassInfo.forName(type);
+
+ if (!typeInfo.isMixin()) {
+ return desc;
+ }
+
+ return desc.replace(type, this.findRealType(typeInfo).toString());
+ }
+
+ private String transformMethodDescriptor(String desc) {
+ StringBuilder newDesc = new StringBuilder();
+ newDesc.append('(');
+ for (Type arg : Type.getArgumentTypes(desc)) {
+ newDesc.append(this.transformSingleDescriptor(arg));
+ }
+ return newDesc.append(')').append(this.transformSingleDescriptor(Type.getReturnType(desc))).toString();
+ }
+
+ /**
+ * Get a target method handle from the target class
+ *
+ * @param method method to get a target handle for
+ * @return new or existing target handle for the supplied method
+ */
+ public Target getTargetMethod(MethodNode method) {
+ if (!this.targetClass.methods.contains(method)) {
+ throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()");
+ }
+
+ String targetName = method.name + method.desc;
+ Target target = this.targetMethods.get(targetName);
+ if (target == null) {
+ target = new Target(method);
+ this.targetMethods.put(targetName, target);
+ }
+ return target;
+ }
+
+ /**
+ * Get the mixin info for this mixin
+ */
+ MixinInfo getInfo() {
+ return this.mixin;
+ }
+
+ /**
+ * Get the mixin priority
+ *
+ * @return the priority (only meaningful in relation to other mixins)
+ */
+ public int getPriority() {
+ return this.mixin.getPriority();
+ }
+
+ /**
+ * Get all interfaces for this mixin
+ *
+ * @return mixin interfaces
+ */
+ public Set getInterfaces() {
+ return this.mixin.getInterfaces();
+ }
+
+ /**
+ * Get whether to propogate the source file attribute from a mixin onto the
+ * target class
+ *
+ * @return true if the sourcefile property should be set on the target class
+ */
+ public boolean shouldSetSourceFile() {
+ return this.mixin.getParent().shouldSetSourceFile();
+ }
+
+ /* (non-Javadoc)
+ * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext
+ * #getReferenceMapper()
+ */
+ @Override
+ public ReferenceMapper getReferenceMapper() {
+ return this.mixin.getParent().getReferenceMapper();
+ }
+
+ /**
+ * Called immediately before the mixin is applied to targetClass
+ *
+ * @param transformedName Target class's transformed name
+ * @param targetClass Target class
+ */
+ public void preApply(String transformedName, ClassNode targetClass) {
+ this.mixin.preApply(transformedName, targetClass);
+ }
+
+ /**
+ * Called immediately after the mixin is applied to targetClass
+ *
+ * @param transformedName Target class's transformed name
+ * @param targetClass Target class
+ */
+ public void postApply(String transformedName, ClassNode targetClass) {
+ this.mixin.postApply(transformedName, targetClass);
+ }
+}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
index 24c7b9b2..555b3655 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
@@ -40,22 +40,24 @@ import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.FileUtils;
+import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.helpers.Booleans;
+import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
-import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
-import org.spongepowered.asm.mixin.InvalidMixinException;
+import org.objectweb.asm.util.CheckClassAdapter;
+import org.spongepowered.asm.mixin.MixinApplyError;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@@ -158,7 +160,9 @@ public class MixinTransformer extends TreeTransformer {
Opcodes.SASTORE
};
- private static final boolean DEBUG_EXPORT = Booleans.parseBoolean(System.getProperty("mixin.debug.export"), false);
+ public static final boolean DEBUG_ALL = Booleans.parseBoolean(System.getProperty("mixin.debug"), false);
+ private static final boolean DEBUG_EXPORT = Booleans.parseBoolean(System.getProperty("mixin.debug.export"), false) | MixinTransformer.DEBUG_ALL;
+ private static final boolean DEBUG_VERIFY = Booleans.parseBoolean(System.getProperty("mixin.debug.verify"), false) | MixinTransformer.DEBUG_ALL;
/**
* Log all the things
@@ -210,7 +214,10 @@ public class MixinTransformer extends TreeTransformer {
if (configs != null) {
for (String configFile : configs) {
try {
- this.configs.add(MixinConfig.create(configFile));
+ MixinConfig config = MixinConfig.create(configFile);
+ if (config != null) {
+ this.configs.add(config);
+ }
} catch (Exception ex) {
this.logger.warn(String.format("Failed to load mixin config: %s", configFile), ex);
}
@@ -246,7 +253,7 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.configs) {
if (transformedName != null && transformedName.startsWith(config.getMixinPackage())) {
- throw new RuntimeException(String.format("%s is a mixin class and cannot be referenced directly", transformedName));
+ throw new NoClassDefFoundError(String.format("%s is a mixin class and cannot be referenced directly", transformedName));
}
if (config.hasMixinsFor(transformedName)) {
@@ -263,12 +270,21 @@ public class MixinTransformer extends TreeTransformer {
try {
basicClass = this.applyMixins(transformedName, basicClass, mixins);
} catch (InvalidMixinException th) {
- this.logger.warn(String.format("Class mixin failed: %s %s", th.getClass().getName(), th.getMessage()), th);
+ MixinConfig config = th.getMixin().getParent();
+ this.logger.log(config.isRequired() ? Level.FATAL : Level.WARN, String.format("Mixin failed applying %s -> %s: %s %s",
+ th.getMixin(), transformedName, th.getClass().getName(), th.getMessage()), th);
+
+ if (config.isRequired()) {
+ throw new MixinApplyError("Mixin [" + th.getMixin() + "] FAILED for REQUIRED config [" + config + "]", th);
+ }
+
th.printStackTrace();
}
}
return basicClass;
+ } catch (Exception ex) {
+ throw new MixinTransformerError("An unexpected critical error was encountered", ex);
} finally {
this.reEntranceCheck--;
}
@@ -346,13 +362,18 @@ public class MixinTransformer extends TreeTransformer {
ClassNode targetClass = this.readClass(basicClass, true);
for (MixinInfo mixin : mixins) {
- this.logger.info("Mixing {} into {}", mixin.getName(), transformedName);
- this.applyMixin(transformedName, targetClass, mixin.createData(targetClass));
+ this.logger.log(mixin.getLoggingLevel(), "Mixing {} into {}", mixin.getName(), transformedName);
+ this.applyMixin(transformedName, targetClass, mixin.createContextForTarget(targetClass));
}
// Extension point
this.postTransform(transformedName, targetClass, mixins);
+ // Run CheckClassAdapter on the mixin bytecode if debug option is enabled
+ if (MixinTransformer.DEBUG_VERIFY) {
+ targetClass.accept(new CheckClassAdapter(new ClassWriter(ClassWriter.COMPUTE_FRAMES)));
+ }
+
// Collapse tree to bytes
byte[] bytes = this.writeClass(targetClass);
@@ -384,7 +405,7 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass Target class
* @param mixin Mixin to apply
*/
- protected void applyMixin(String transformedName, ClassNode targetClass, MixinData mixin) {
+ protected void applyMixin(String transformedName, ClassNode targetClass, MixinTargetContext mixin) {
try {
mixin.preApply(transformedName, targetClass);
this.applyMixinInterfaces(targetClass, mixin);
@@ -394,8 +415,10 @@ public class MixinTransformer extends TreeTransformer {
this.applyInitialisers(targetClass, mixin);
this.applyInjections(targetClass, mixin);
mixin.postApply(transformedName, targetClass);
+ } catch (InvalidMixinException ex) {
+ throw ex;
} catch (Exception ex) {
- throw new InvalidMixinException("Unexpecteded error whilst applying the mixin class", ex);
+ throw new InvalidMixinException(mixin, "Unexpecteded error whilst applying the mixin class", ex);
}
}
@@ -405,7 +428,7 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass
* @param mixin
*/
- private void applyMixinInterfaces(ClassNode targetClass, MixinData mixin) {
+ private void applyMixinInterfaces(ClassNode targetClass, MixinTargetContext mixin) {
for (String interfaceName : mixin.getInterfaces()) {
if (!targetClass.interfaces.contains(interfaceName)) {
targetClass.interfaces.add(interfaceName);
@@ -419,7 +442,7 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass
* @param mixin
*/
- private void applyMixinAttributes(ClassNode targetClass, MixinData mixin) {
+ private void applyMixinAttributes(ClassNode targetClass, MixinTargetContext mixin) {
if (mixin.shouldSetSourceFile()) {
targetClass.sourceFile = mixin.getClassNode().sourceFile;
}
@@ -434,19 +457,21 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass
* @param mixin
*/
- private void applyMixinFields(ClassNode targetClass, MixinData mixin) {
- for (FieldNode field : mixin.getClassNode().fields) {
- // Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition
- if (MixinTransformer.hasFlag(field, Opcodes.ACC_STATIC) && !MixinTransformer.hasFlag(field, Opcodes.ACC_PRIVATE)) {
- throw new InvalidMixinException(String.format("Mixin classes cannot contain visible static methods or fields, found %s", field.name));
+ private void applyMixinFields(ClassNode targetClass, MixinTargetContext mixin) {
+ for (Iterator iter = mixin.getClassNode().fields.iterator(); iter.hasNext();) {
+ FieldNode field = iter.next();
+ AnnotationNode shadow = ASMHelper.getVisibleAnnotation(field, Shadow.class);
+ this.validateField(mixin, field, shadow);
+ if (!mixin.transformField(field)) {
+ iter.remove();
+ continue;
}
-
+
FieldNode target = this.findTargetField(targetClass, field);
if (target == null) {
// If this field is a shadow field but is NOT found in the target class, that's bad, mmkay
- boolean isShadow = ASMHelper.getVisibleAnnotation(field, Shadow.class) != null;
- if (isShadow) {
- throw new InvalidMixinException(String.format("Shadow field %s was not located in the target class", field.name));
+ if (shadow != null) {
+ throw new InvalidMixinException(mixin, String.format("Shadow field %s was not located in the target class", field.name));
}
// This is just a local field, so add it
@@ -454,22 +479,43 @@ public class MixinTransformer extends TreeTransformer {
} else {
// Check that the shadow field has a matching descriptor
if (!target.desc.equals(field.desc)) {
- throw new InvalidMixinException(String.format("The field %s in the target class has a conflicting signature", field.name));
+ throw new InvalidMixinException(mixin, String.format("The field %s in the target class has a conflicting signature", field.name));
}
}
}
}
+ /**
+ * Field sanity checks
+ * @param mixin
+ * @param field
+ * @param shadow
+ */
+ private void validateField(MixinTargetContext mixin, FieldNode field, AnnotationNode shadow) {
+ // Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition
+ if (MixinTransformer.hasFlag(field, Opcodes.ACC_STATIC) && !MixinTransformer.hasFlag(field, Opcodes.ACC_PRIVATE)) {
+ throw new InvalidMixinException(mixin, String.format("Mixin classes cannot contain visible static methods or fields, found %s",
+ field.name));
+ }
+
+ // Shadow fields can't have prefixes, it's meaningless for them anyway
+ String prefix = ASMHelper.getAnnotationValue(shadow, "prefix", Shadow.class);
+ if (field.name.startsWith(prefix)) {
+ throw new InvalidMixinException(mixin, String.format("Shadow field %s in %s has a shadow prefix. This is not allowed.",
+ field.name, mixin));
+ }
+ }
+
/**
* Mixin methods from the mixin class into the target class
*
* @param targetClass
* @param mixin
*/
- private void applyMixinMethods(ClassNode targetClass, MixinData mixin) {
+ private void applyMixinMethods(ClassNode targetClass, MixinTargetContext mixin) {
for (MethodNode mixinMethod : mixin.getClassNode().methods) {
// Reparent all mixin methods into the target class
- this.transformMethod(mixin, targetClass, mixinMethod);
+ mixin.transformMethod(mixinMethod);
boolean isShadow = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class) != null;
boolean isOverwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class) != null;
@@ -479,17 +525,17 @@ public class MixinTransformer extends TreeTransformer {
// For shadow (and abstract, which can be used as a shorthand for Shadow) methods, we just check they're present
MethodNode target = this.findTargetMethod(targetClass, mixinMethod);
if (target == null) {
- throw new InvalidMixinException(String.format("Shadow method %s was not located in the target class", mixinMethod.name));
+ throw new InvalidMixinException(mixin, String.format("Shadow method %s was not located in the target class", mixinMethod.name));
}
} else if (!mixinMethod.name.startsWith("<")) {
if (MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
&& !MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE)
&& !MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)
&& !isOverwrite) {
- throw new InvalidMixinException(
+ throw new InvalidMixinException(mixin,
String.format("Mixin classes cannot contain visible static methods or fields, found %s", mixinMethod.name));
}
-
+
this.mergeMethod(targetClass, mixin, mixinMethod, isOverwrite);
} else if (MixinTransformer.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
@@ -498,61 +544,6 @@ public class MixinTransformer extends TreeTransformer {
}
}
- /**
- * Handles "re-parenting" the method supplied, changes all references to the
- * mixin class to refer to the target class (for field accesses and method
- * invokations) and also handles fixing up the targets of INVOKESPECIAL
- * opcodes for mixins with detached targets.
- *
- * @param mixin
- * @param target
- * @param method
- */
- private void transformMethod(MixinData mixin, ClassNode target, MethodNode method) {
- String fromClass = mixin.getClassRef();
- boolean detached = !mixin.getClassNode().superName.equals(target.superName);
-
- Iterator iter = method.instructions.iterator();
- while (iter.hasNext()) {
- AbstractInsnNode insn = iter.next();
-
- if (insn instanceof MethodInsnNode) {
- MethodInsnNode methodInsn = (MethodInsnNode) insn;
- if (methodInsn.owner.equals(fromClass)) {
- methodInsn.owner = target.name;
- } else if (detached && methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) {
- this.updateStaticBindings(mixin, target, method, methodInsn);
- }
- } else if (insn instanceof FieldInsnNode) {
- FieldInsnNode fieldInsn = (FieldInsnNode) insn;
- if (fieldInsn.owner.equals(fromClass)) {
- fieldInsn.owner = target.name;
- }
- }
- }
- }
-
- /**
- * Update INVOKESPECIAL opcodes to target the topmost class in the hierarchy
- * which contains the specified method.
- *
- * @param mixin
- * @param target
- * @param method
- * @param insn
- */
- private void updateStaticBindings(IReferenceMapperContext mixin, ClassNode target, MethodNode method, MethodInsnNode insn) {
- if (INIT.equals(method.name) || insn.owner.equals(target.name) || target.name.startsWith("<")) {
- return;
- }
-
- ClassInfo targetClass = ClassInfo.forName(target.name);
- String newOwner = targetClass.findMethodInHierarchy(insn.name, insn.desc, false);
- if (newOwner != null) {
- insn.owner = newOwner;
- }
- }
-
/**
* Attempts to merge the supplied method into the target class
*
@@ -562,7 +553,7 @@ public class MixinTransformer extends TreeTransformer {
* @param isOverwrite true if the method is annotated with an
* {@link Overwrite} annotation
*/
- private void mergeMethod(ClassNode targetClass, MixinData mixin, MethodNode method, boolean isOverwrite) {
+ private void mergeMethod(ClassNode targetClass, MixinTargetContext mixin, MethodNode method, boolean isOverwrite) {
MethodNode target = this.findTargetMethod(targetClass, method);
if (target != null) {
@@ -585,10 +576,11 @@ public class MixinTransformer extends TreeTransformer {
targetClass.methods.remove(target);
} else if (isOverwrite) {
- throw new InvalidMixinException(String.format("Overwrite target %s was not located in the target class", method.name));
+ throw new InvalidMixinException(mixin, String.format("Overwrite target %s was not located in the target class", method.name));
}
targetClass.methods.add(method);
+ mixin.getTargetClassInfo().addMethod(method);
ASMHelper.setVisibleAnnotation(method, MixinMerged.class,
"mixin", mixin.getClassName(),
@@ -650,7 +642,7 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass
* @param mixin
*/
- private void applyInitialisers(ClassNode targetClass, MixinData mixin) {
+ private void applyInitialisers(ClassNode targetClass, MixinTargetContext mixin) {
// Try to find a suitable constructor, we need a constructor with line numbers in order to extract the initialiser
MethodNode ctor = this.getConstructor(mixin);
if (ctor == null) {
@@ -658,7 +650,7 @@ public class MixinTransformer extends TreeTransformer {
}
// Find the initialiser instructions in the candidate ctor
- InsnList initialiser = this.getInitialiser(ctor);
+ InsnList initialiser = this.getInitialiser(mixin, ctor);
if (initialiser == null || initialiser.size() == 0) {
return;
}
@@ -666,6 +658,7 @@ public class MixinTransformer extends TreeTransformer {
// Patch the initialiser into the target class ctors
for (MethodNode method : targetClass.methods) {
if (MixinTransformer.INIT.equals(method.name)) {
+ method.maxStack = Math.max(method.maxStack, ctor.maxStack);
this.injectInitialiser(method, initialiser);
}
}
@@ -674,7 +667,7 @@ public class MixinTransformer extends TreeTransformer {
/**
* Finds a suitable ctor for reading the instance initialiser bytecode
*/
- private MethodNode getConstructor(MixinData mixin) {
+ private MethodNode getConstructor(MixinTargetContext mixin) {
MethodNode ctor = null;
for (MethodNode mixinMethod : mixin.getClassNode().methods) {
@@ -738,7 +731,7 @@ public class MixinTransformer extends TreeTransformer {
* @return initialiser bytecode extracted from the supplied constructor, or
* null if the constructor range could not be parsed
*/
- private InsnList getInitialiser(MethodNode ctor) {
+ private InsnList getInitialiser(MixinTargetContext mixin, MethodNode ctor) {
// Find the range of line numbers which corresponds to the constructor body
Range init = this.getConstructorRange(ctor);
if (!init.isValid()) {
@@ -749,12 +742,20 @@ public class MixinTransformer extends TreeTransformer {
int line = 0;
InsnList initialiser = new InsnList();
boolean gatherNodes = false;
+ int trimAtOpcode = -1;
LabelNode optionalInsn = null;
for (Iterator iter = ctor.instructions.iterator(init.marker); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof LineNumberNode) {
line = ((LineNumberNode)insn).line;
- gatherNodes = init.excludes(line);
+ AbstractInsnNode next = ctor.instructions.get(ctor.instructions.indexOf(insn) + 1);
+ if (line == init.end && next.getOpcode() != Opcodes.RETURN) {
+ gatherNodes = true;
+ trimAtOpcode = Opcodes.RETURN;
+ } else {
+ gatherNodes = init.excludes(line);
+ trimAtOpcode = -1;
+ }
} else if (gatherNodes) {
if (optionalInsn != null) {
initialiser.add(optionalInsn);
@@ -765,11 +766,16 @@ public class MixinTransformer extends TreeTransformer {
optionalInsn = (LabelNode)insn;
} else {
int opcode = insn.getOpcode();
+ if (opcode == trimAtOpcode) {
+ trimAtOpcode = -1;
+ continue;
+ }
for (int ivalidOp : MixinTransformer.INITIALISER_OPCODE_BLACKLIST) {
if (opcode == ivalidOp) {
// At the moment I don't handle any transient locals because I haven't seen any in the wild, but let's avoid writing
// code which will likely break things and fix it if a real test case ever appears
- throw new InvalidMixinException("Cannot handle opcode 0x" + Integer.toHexString(opcode) + " in class initialiser");
+ throw new InvalidMixinException(mixin, "Cannot handle " + ASMHelper.getOpcodeName(opcode) + " opcode (0x"
+ + Integer.toHexString(opcode).toUpperCase() + ") in class initialiser");
}
}
@@ -782,7 +788,8 @@ public class MixinTransformer extends TreeTransformer {
AbstractInsnNode last = initialiser.getLast();
if (last != null) {
if (last.getOpcode() != Opcodes.PUTFIELD) {
- throw new InvalidMixinException("Could not parse initialiser, expected 0xB5, found 0x" + Integer.toHexString(last.getOpcode()));
+ throw new InvalidMixinException(mixin, "Could not parse initialiser, expected 0xB5, found 0x"
+ + Integer.toHexString(last.getOpcode()));
}
}
@@ -811,7 +818,7 @@ public class MixinTransformer extends TreeTransformer {
* @param targetClass
* @param mixin
*/
- private void applyInjections(ClassNode targetClass, MixinData mixin) {
+ private void applyInjections(ClassNode targetClass, MixinTargetContext mixin) {
for (MethodNode method : targetClass.methods) {
InjectionInfo injectInfo = InjectionInfo.parse(mixin, method);
if (injectInfo == null) {
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java
new file mode 100644
index 00000000..bc3ea3d4
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java
@@ -0,0 +1,47 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.mixin.transformer;
+
+
+/**
+ * Error to throw for things which really shouldn't happen
+ */
+public class MixinTransformerError extends Error {
+
+ private static final long serialVersionUID = 1L;
+
+ public MixinTransformerError(String message) {
+ super(message);
+ }
+
+ public MixinTransformerError(Throwable cause) {
+ super(cause);
+ }
+
+ public MixinTransformerError(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java
index 4beec5d1..1a432c3d 100644
--- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java
+++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java
@@ -36,17 +36,7 @@ import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
-import org.objectweb.asm.tree.AbstractInsnNode;
-import org.objectweb.asm.tree.AnnotationNode;
-import org.objectweb.asm.tree.ClassNode;
-import org.objectweb.asm.tree.FieldNode;
-import org.objectweb.asm.tree.InsnList;
-import org.objectweb.asm.tree.InsnNode;
-import org.objectweb.asm.tree.IntInsnNode;
-import org.objectweb.asm.tree.LdcInsnNode;
-import org.objectweb.asm.tree.MethodInsnNode;
-import org.objectweb.asm.tree.MethodNode;
-import org.objectweb.asm.tree.VarInsnNode;
+import org.objectweb.asm.tree.*;
import org.objectweb.asm.util.CheckClassAdapter;
public class ASMHelper {
@@ -65,7 +55,7 @@ public class ASMHelper {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()Z", null, null);
InsnList code = method.instructions;
- code.add(pushIntConstant(retval ? 1 : 0));
+ code.add(ASMHelper.pushIntConstant(retval ? 1 : 0));
code.add(new InsnNode(Opcodes.IRETURN));
clazz.methods.add(method);
@@ -82,7 +72,7 @@ public class ASMHelper {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()I", null, null);
InsnList code = method.instructions;
- code.add(pushIntConstant(retval));
+ code.add(ASMHelper.pushIntConstant(retval));
code.add(new InsnNode(Opcodes.IRETURN));
clazz.methods.add(method);
@@ -101,7 +91,7 @@ public class ASMHelper {
MethodNode method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
- populateSelfForwardingMethod(method, forwardname, rettype, Type.getObjectType(clazz.name));
+ ASMHelper.populateSelfForwardingMethod(method, forwardname, rettype, Type.getObjectType(clazz.name));
clazz.methods.add(method);
}
@@ -121,7 +111,7 @@ public class ASMHelper {
Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
"()" + rettype.getDescriptor(), null, null);
- populateSelfForwardingMethod(method, forwardname, rettype, argtype);
+ ASMHelper.populateSelfForwardingMethod(method, forwardname, rettype, argtype);
clazz.methods.add(method);
}
@@ -140,7 +130,7 @@ public class ASMHelper {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
"()" + rettype.getDescriptor(), null, null);
- populateForwardingToStaticMethod(method, forwardname, rettype, Type.getObjectType(clazz.name), fowardtype);
+ ASMHelper.populateForwardingToStaticMethod(method, forwardname, rettype, Type.getObjectType(clazz.name), fowardtype);
clazz.methods.add(method);
}
@@ -162,7 +152,7 @@ public class ASMHelper {
method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
- populateForwardingToStaticMethod(method, forwardname, rettype, thistype, fowardtype);
+ ASMHelper.populateForwardingToStaticMethod(method, forwardname, rettype, thistype, fowardtype);
clazz.methods.add(method);
}
@@ -181,7 +171,7 @@ public class ASMHelper {
method.instructions.clear();
- populateSelfForwardingMethod(method, forwardname, methodType.getReturnType(), thistype);
+ ASMHelper.populateSelfForwardingMethod(method, forwardname, methodType.getReturnType(), thistype);
}
/**
@@ -199,7 +189,7 @@ public class ASMHelper {
method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
- populateForwardingMethod(method, forwardname, rettype, argtype, Type.getObjectType(clazz.name));
+ ASMHelper.populateForwardingMethod(method, forwardname, rettype, argtype, Type.getObjectType(clazz.name));
clazz.methods.add(method);
}
@@ -217,7 +207,7 @@ public class ASMHelper {
method.instructions.clear();
- populateForwardingMethod(method, forwardname, methodType.getReturnType(), methodType.getArgumentTypes()[0], thistype);
+ ASMHelper.populateForwardingMethod(method, forwardname, methodType.getReturnType(), methodType.getArgumentTypes()[0], thistype);
}
/**
@@ -323,7 +313,7 @@ public class ASMHelper {
* @param method the method to add
*/
public static void addAndReplaceMethod(ClassNode clazz, MethodNode method) {
- MethodNode m = findMethod(clazz, method.name, method.desc);
+ MethodNode m = ASMHelper.findMethod(clazz, method.name, method.desc);
if (m != null) {
clazz.methods.remove(m);
}
@@ -338,7 +328,7 @@ public class ASMHelper {
public static void dumpClass(ClassNode classNode) {
ClassWriter cw = new ClassWriter(COMPUTE_MAXS | COMPUTE_FRAMES);
classNode.accept(cw);
- dumpClass(cw.toByteArray());
+ ASMHelper.dumpClass(cw.toByteArray());
}
/**
@@ -351,6 +341,93 @@ public class ASMHelper {
CheckClassAdapter.verify(cr, true, new PrintWriter(System.out));
}
+ /**
+ * Prints a representation of a method's instructions to stderr
+ *
+ * @param method Method to print
+ */
+ public static void printMethod(MethodNode method) {
+ System.err.printf("%s%s\n", method.name, method.desc);
+ for (Iterator iter = method.instructions.iterator(); iter.hasNext();) {
+ System.err.print(" ");
+ ASMHelper.printNode(iter.next());
+ }
+ }
+
+ /**
+ * Prints a representation of the specified insn node to stderr
+ *
+ * @param node Node to print
+ */
+ public static void printNode(AbstractInsnNode node) {
+ System.err.printf("%s ", node.getClass().getSimpleName());
+ if (node instanceof LabelNode) {
+ System.err.printf("[%s]", ((LabelNode)node).getLabel());
+ } else if (node instanceof JumpInsnNode) {
+ System.err.printf("[%s]", ((JumpInsnNode)node).label.getLabel());
+ } else if (node instanceof VarInsnNode) {
+ System.err.printf("[%s] %d", ASMHelper.getOpcodeName(node), ((VarInsnNode)node).var);
+ } else if (node instanceof MethodInsnNode) {
+ MethodInsnNode mth = (MethodInsnNode)node;
+ System.err.printf("[%s] %s %s %s", ASMHelper.getOpcodeName(node), mth.owner, mth.name, mth.desc);
+ } else if (node instanceof FieldInsnNode) {
+ FieldInsnNode fld = (FieldInsnNode)node;
+ System.err.printf("[%s] %s %s %s", ASMHelper.getOpcodeName(node), fld.owner, fld.name, fld.desc);
+ } else if (node instanceof LineNumberNode) {
+ LineNumberNode ln = (LineNumberNode)node;
+ System.err.printf("LINE=%d LABEL=[%s]", ln.line, ln.start.getLabel());
+ } else if (node instanceof LdcInsnNode) {
+ System.err.print(((LdcInsnNode)node).cst);
+ } else if (node instanceof IntInsnNode) {
+ System.err.print(((IntInsnNode)node).operand);
+ } else {
+ System.err.printf("[%s] ", ASMHelper.getOpcodeName(node));
+ }
+ System.err.print("\n");
+ }
+
+ /**
+ * Uses reflection to find an approximate constant name match for the
+ * supplied node's opcode
+ *
+ * @param node Node to query for opcode
+ * @return Approximate opcode name (approximate because some constants in
+ * the {@link Opcodes} class have the same value as opcodes
+ */
+ public static String getOpcodeName(AbstractInsnNode node) {
+ return ASMHelper.getOpcodeName(node.getOpcode());
+ }
+
+ /**
+ * Uses reflection to find an approximate constant name match for the
+ * supplied opcode
+ *
+ * @param opcode Opcode to look up
+ * @return Approximate opcode name (approximate because some constants in
+ * the {@link Opcodes} class have the same value as opcodes
+ */
+ public static String getOpcodeName(int opcode) {
+ if (opcode > 0) {
+ boolean found = false;
+
+ try {
+ for (java.lang.reflect.Field f : Opcodes.class.getDeclaredFields()) {
+ if (!found && f.getName() != "UNINITIALIZED_THIS") {
+ continue;
+ }
+ found = true;
+ if (f.getType() == Integer.TYPE && f.getInt(null) == opcode) {
+ return f.getName();
+ }
+ }
+ } catch (Exception ex) {
+ // derp
+ }
+ }
+
+ return String.valueOf(opcode);
+ }
+
/**
* Set a runtime-visible annotation of the specified class on the supplied
* field node
@@ -597,7 +674,32 @@ public class ASMHelper {
T returnValue = ASMHelper.getAnnotationValue(annotation, key);
return returnValue != null ? returnValue : defaultValue;
}
-
+
+ /**
+ * Gets an annotation value or returns the default value of the annotation
+ * if the annotation value is not present
+ *
+ * @param duck type
+ * @param annotation Annotation node to query
+ * @param key Key to search for
+ * @param annotationClass Annotation class to query reflectively for the
+ * default value
+ * @return Value of the specified annotation node, default value if not
+ * specified, or null if no value or default
+ */
+ @SuppressWarnings("unchecked")
+ public static T getAnnotationValue(AnnotationNode annotation, String key, Class> annotationClass) {
+ T value = ASMHelper.getAnnotationValue(annotation, key);
+ if (value == null) {
+ try {
+ value = (T)annotationClass.getDeclaredMethod(key).getDefaultValue();
+ } catch (NoSuchMethodException ex) {
+ // Don't care
+ }
+ }
+ return value;
+ }
+
/**
* Get the value of an annotation node and do pseudo-duck-typing via Java's
* crappy generics
@@ -612,7 +714,7 @@ public class ASMHelper {
public static T getAnnotationValue(AnnotationNode annotation, String key) {
boolean getNextValue = false;
- if (annotation.values == null) {
+ if (annotation == null || annotation.values == null) {
return null;
}
diff --git a/src/main/java/org/spongepowered/asm/util/VersionNumber.java b/src/main/java/org/spongepowered/asm/util/VersionNumber.java
new file mode 100644
index 00000000..bc9d66a2
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/util/VersionNumber.java
@@ -0,0 +1,213 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.io.Serializable;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+/**
+ * Represents a software version number in major.minor.revision.build
+ * format as a sequence of four shorts packed into a long. This is to
+ * facilitate meaningful comparison between version numbers.
+ */
+public class VersionNumber implements Comparable, Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Represents no version number or a version number which could not be
+ * parsed
+ */
+ public static final VersionNumber NONE = new VersionNumber();
+
+ /**
+ * Regex for matching a version number specified as a string
+ */
+ private static final Pattern versionNumberPattern =
+ Pattern.compile("^(\\d{1,5})(?:\\.(\\d{1,5})(?:\\.(\\d{1,5})(?:\\.(\\d{1,5}))?)?)?(-[a-zA-Z0-9_\\-]+)?$");
+
+ /**
+ * The version number, packed as four shorts into a long
+ */
+ private final long value;
+
+ /**
+ * suffix such as -BETA or -SNAPSHOT, must be prefixed with "-" to be
+ * matched
+ */
+ private final String suffix;
+
+ private VersionNumber() {
+ this.value = 0;
+ this.suffix = "";
+ }
+
+ private VersionNumber(short[] parts) {
+ this(parts, null);
+ }
+
+ private VersionNumber(short[] parts, String suffix) {
+ this.value = VersionNumber.pack(parts);
+ this.suffix = suffix != null ? suffix : "";
+ }
+
+ private VersionNumber(short major, short minor, short revision, short build) {
+ this(major, minor, revision, build, null);
+ }
+
+ private VersionNumber(short major, short minor, short revision, short build, String suffix) {
+ this.value = VersionNumber.pack(major, minor, revision, build);
+ this.suffix = suffix != null ? suffix : "";
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ short[] parts = VersionNumber.unpack(this.value);
+
+ return String.format("%d.%d%3$s%4$s%5$s",
+ parts[0],
+ parts[1],
+ (this.value & Integer.MAX_VALUE) > 0 ? String.format(".%d", parts[2]) : "",
+ (this.value & Short.MAX_VALUE) > 0 ? String.format(".%d", parts[3]) : "",
+ this.suffix);
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ @Override
+ public int compareTo(VersionNumber other) {
+ if (other == null) {
+ return 1;
+ }
+ long delta = this.value - other.value;
+ return delta > 0 ? 1 : delta < 0 ? -1 : 0;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof VersionNumber)) {
+ return false;
+ }
+
+ return ((VersionNumber)other).value == this.value;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ return (int)(this.value >> 32) ^ (int)(this.value & 0xFFFFFFFF);
+ }
+
+ /**
+ * Packs the supplied array of shorts into a long
+ *
+ * @param shorts short values to pack
+ * @return supplied shorts packed into a long
+ */
+ private static long pack(short... shorts) {
+ return (long)shorts[0] << 48 | (long)shorts[1] << 32 | shorts[2] << 16 | shorts[3];
+ }
+
+ /**
+ * Unpacks a long into an array of four shorts
+ *
+ * @param along Long to unpack
+ * @return Unpacked array of four shorts
+ */
+ private static short[] unpack(long along) {
+ return new short[] {
+ (short)(along >> 48),
+ (short)(along >> 32 & Short.MAX_VALUE),
+ (short)(along >> 16 & Short.MAX_VALUE),
+ (short)(along & Short.MAX_VALUE)
+ };
+ }
+
+ /**
+ * Parse a version number specified as a string
+ *
+ * @param version Version number to parse
+ * @return Version number
+ */
+ public static final VersionNumber parse(String version) {
+ return VersionNumber.parse(version, VersionNumber.NONE);
+ }
+
+ /**
+ * Parse a version number specified as a string and return default if
+ * parsing fails
+ *
+ * @param version Version number to parse
+ * @param defaultVersion Version number to return if parse fails
+ * @return Version number
+ */
+ public static VersionNumber parse(String version, String defaultVersion) {
+ return VersionNumber.parse(version, VersionNumber.parse(defaultVersion));
+ }
+
+ /**
+ * Parse a version number specified as a string and return default if
+ * parsing fails
+ *
+ * @param version Version number to parse
+ * @param defaultVersion Version number to return if parse fails
+ * @return Version number
+ */
+ private static VersionNumber parse(String version, VersionNumber defaultVersion) {
+ if (version == null) {
+ return defaultVersion;
+ }
+
+ Matcher versionNumberPatternMatcher = VersionNumber.versionNumberPattern.matcher(version);
+ if (!versionNumberPatternMatcher.matches()) {
+ return defaultVersion;
+ }
+
+ short[] parts = new short[4];
+ for (int pos = 0; pos < 4; pos++) {
+ String part = versionNumberPatternMatcher.group(pos + 1);
+ if (part != null) {
+ int value = Integer.parseInt(part);
+ if (value > Short.MAX_VALUE) {
+ throw new IllegalArgumentException("Version parts cannot exceed " + Short.MAX_VALUE + ", found " + value);
+ }
+ parts[pos] = (short)value;
+ }
+ }
+
+ return new VersionNumber(parts, versionNumberPatternMatcher.group(5));
+ }
+}