From b5299bfebc623b95bae98e9019491e9a5d49499a Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 2 May 2020 12:34:55 +0100 Subject: [PATCH 01/42] Aggressively resolve soft targets containing '$' and other minor fixes Fixes #390 --- .../tools/obfuscation/AnnotatedMixin.java | 4 ++ .../AnnotatedMixinElementHandlerAccessor.java | 12 ++-- .../tools/obfuscation/AnnotatedMixins.java | 62 ++++++++++++++++++- .../tools/obfuscation/SuppressedBy.java | 7 +++ .../asm/mixin/struct/AnnotatedMethodInfo.java | 12 ++-- 5 files changed, 82 insertions(+), 15 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 09fcc44f..15405303 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -225,6 +225,10 @@ class AnnotatedMixin { } else if (type == null) { this.printMessage(Kind.ERROR, "Mixin target " + softTarget + " could not be found", this); return null; + } else if (type.isImaginary()) { + this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " could not be fully resolved.", this, + SuppressedBy.UNRESOLVABLE_TARGET); + return null; } else if (type.isPublic()) { SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : SuppressedBy.PUBLIC_TARGET; this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " is public and must be specified in value", this, suppressedBy); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index dce6143c..b65d3a9e 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -105,12 +105,12 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH return TypeUtils.getTypeName(this.getTargetType()); } - public String getAccessorDesc() { + public String getTargetDesc() { return TypeUtils.getInternalName(this.getTargetType()); } public ITargetSelectorRemappable getContext() { - return new MemberInfo(this.getTargetName(), null, this.getAccessorDesc()); + return new MemberInfo(this.getTargetName(), null, this.getTargetDesc()); } public AccessorType getAccessorType() { @@ -186,8 +186,8 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } @Override - public String getAccessorDesc() { - return TypeUtils.getDescriptor(this.getElement()); + public String getTargetDesc() { + return this.getDesc(); } @Override @@ -294,7 +294,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH return; } - targetField = new FieldHandle(target.getName(), elem.getTargetName(), elem.getDesc()); + targetField = new FieldHandle(target.getName(), elem.getTargetName(), elem.getTargetDesc()); } if (!elem.shouldRemap()) { @@ -326,7 +326,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH return; } - targetMethod = new MethodHandle(target, elem.getTargetName(), elem.getDesc()); + targetMethod = new MethodHandle(target, elem.getTargetName(), elem.getTargetDesc()); } if (!elem.shouldRemap()) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index cfd9eb66..d4845674 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -624,7 +624,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider name = name.replace('/', '.'); Elements elements = this.processingEnv.getElementUtils(); - TypeElement element = elements.getTypeElement(name); + TypeElement element = this.getTypeElement(name, elements); if (element != null) { try { return new TypeHandle(element); @@ -645,6 +645,66 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return null; } + /** + * Get a TypeElement representing another type in the current processing + * environment. This method attempts substitution of '$' symbols appearing + * in the class name when requesting TypeElements from the processing env. + */ + public TypeElement getTypeElement(String name) { + return this.getTypeElement(name.replace('/', '.'), this.processingEnv.getElementUtils()); + } + + private TypeElement getTypeElement(String name, Elements elements) { + // Try fetching directly first + TypeElement element = elements.getTypeElement(name); + if (element != null || name.indexOf('$') < 0) { + return element; + } + + int lastDotPos = name.lastIndexOf('.'); + String pkg = lastDotPos > -1 ? name.substring(0, lastDotPos) : ""; + name = name.substring(pkg.length()); + + // Name has '$' in it, try naive replacement first, this will work for + // most cases where there is a single '$' symbol + element = elements.getTypeElement(pkg + name.replace('$', '.')); + if (element != null) { + return element; + } + + char[] source = name.toCharArray(); + char[] dest = new char[source.length]; + int occurs = 0; + + for (int offset = 0; offset < source.length; offset++) { + if (source[offset] == '$') { + occurs++; + } + } + + // Ok someone is trolling if there are more than 10 '$' symbols in a + // name! 10 is an arbitary number, we could do more but the loop below + // is expensive and something horrible is probably happening if there + // are that many '$' signs. We can also skip here if occurs < 2 because + // we already tested that case above when we replaced "all" + if (occurs > 10 || occurs < 2) { + return null; + } + + // Try all possible combinations of replacing '$' with '.' starting at + // the end of the string. Not really ideal but if we haven't resolved + // the class name by replacing all '$' with '.' then this is our only + // remaining approach. + for (int mask = 1; mask < 1 << occurs && element == null; mask++) { + for (int offset = source.length - 1, index = 0; offset >= 0; offset--) { + dest[offset] = (source[offset] == '$' && (mask & (1 << index++)) != 0) ? '.' : source[offset]; + } + element = elements.getTypeElement(pkg + new String(dest)); + } + + return element; + } + /** * Returns a simulated TypeHandle for a non-existing type */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java index 022c63e7..70ecf4f6 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -70,6 +70,13 @@ public enum SuppressedBy { */ PUBLIC_TARGET("public-target"), + /** + * Suppress warning when a mixin target is resolved by the AP as imaginary + * (unresolvable via Mirror at compile time). For example for anonymous + * inner classes or other synthetic member classes. + */ + UNRESOLVABLE_TARGET("unresolvable-target"), + /** * The default java "raw types" suppressions */ diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index 3fac92c6..e60da758 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -24,24 +24,20 @@ */ package org.spongepowered.asm.mixin.struct; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import javax.tools.Diagnostic.Kind; + import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.logging.MessageRouter; /** * Data bundle for an annotated method in a mixin */ public class AnnotatedMethodInfo implements IInjectionPointContext { - /** - * Log more things - */ - protected static final Logger logger = LogManager.getLogger("mixin"); - /** * Mixin context */ @@ -100,7 +96,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { @Override public void addMessage(String format, Object... args) { if (this.context.getOption(Option.DEBUG_VERBOSE)) { - AnnotatedMethodInfo.logger.warn(String.format(format, args)); + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format(format, args)); } } From 0177c2d3940495c7552e94dcb0dea7d2aeba33a2 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 17 Oct 2020 22:10:10 +0100 Subject: [PATCH 02/42] Fixes for several locals-related issues, fix #398, fix #402, fix #405 --- .../injection/callback/CallbackInjector.java | 18 ++++++++++-------- .../modify/LocalVariableDiscriminator.java | 11 +++++++---- .../org/spongepowered/asm/util/Locals.java | 17 +++++++++++------ 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index d36ed952..9827cfb1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -529,13 +529,15 @@ public class CallbackInjector extends Injector { */ private String generateBadLVTMessage(final Callback callback) { int position = callback.target.indexOf(callback.node); - List expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1); - List found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0)); + int targetArgc = callback.target.arguments.length + 1; + List expected = CallbackInjector.summariseLocals(this.methodNode.desc, targetArgc, 255); + List found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, expected.size()); if (expected.equals(found)) { return String.format("Invalid descriptor on %s! Expected %s but found %s", this.info, callback.getDescriptor(), this.methodNode.desc); } - return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s", - callback.target, position, this, expected, found); + List available = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, 255); + return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\n Expected: %s\n Found: %s\nAvailable: %s", + callback.target, position, this.info, expected, found, available); } /** @@ -783,14 +785,14 @@ public class CallbackInjector extends Injector { return this.isStatic; } - private static List summariseLocals(String desc, int pos) { - return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos); + private static List summariseLocals(String desc, int pos, int count) { + return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos, count); } - private static List summariseLocals(Type[] locals, int pos) { + private static List summariseLocals(Type[] locals, int pos, int count) { List list = new ArrayList(); if (locals != null) { - for (; pos < locals.length; pos++) { + for (; pos < locals.length && list.size() < count; pos++) { if (locals[pos] != null) { list.add(locals[pos].toString()); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java index b5c5ad87..544e5184 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -145,13 +145,16 @@ public class LocalVariableDiscriminator { } } - Local[] lvt = new Local[this.baseArgIndex + target.arguments.length]; + Local[] lvt = new Local[this.baseArgIndex + Bytecode.getArgsSize(target.arguments)]; if (!this.isStatic) { lvt[0] = new Local("this", Type.getObjectType(target.classNode.name)); } - for (int local = this.baseArgIndex; local < lvt.length; local++) { - Type arg = target.arguments[local - this.baseArgIndex]; - lvt[local] = new Local("arg" + local, arg); + for (int local = this.baseArgIndex, arg = 0; local < lvt.length; local++) { + Type argType = target.arguments[arg++]; + lvt[local] = new Local("arg" + local, argType); + if (argType.getSize() == 2) { + lvt[++local] = null; + } } return lvt; } diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 733b57f2..e3cb05d8 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -137,7 +137,7 @@ public final class Locals { for (int i = 0; i < 3 && (node instanceof LabelNode || node instanceof LineNumberNode); i++) { node = Locals.nextNode(method.instructions, node); } - + ClassInfo classInfo = ClassInfo.forName(classNode.name); if (classInfo == null) { throw new LVTGeneratorError("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); @@ -195,7 +195,7 @@ public final class Locals { frameSize = Locals.getAdjustedFrameSize(frameSize, frameNode); } - if (frameNode.type == Opcodes.F_CHOP) { + if (frameNode.type == Opcodes.F_CHOP || frameNode.type == Opcodes.F_NEW) { for (int framePos = frameSize; framePos < frame.length; framePos++) { frame[framePos] = null; } @@ -223,7 +223,7 @@ public final class Locals { frame[framePos] = null; } else if (is32bitValue || is64bitValue) { frame[framePos] = Locals.getLocalVariableAt(classNode, method, insn, framePos); - + if (is64bitValue) { framePos++; frame[framePos] = null; // TOP @@ -435,7 +435,7 @@ public final class Locals { labels[i] = label = new LabelNode(); } } - + if (local == null && locals[j] != null) { localVariables.add(localNodes[j]); localNodes[j].end = label; @@ -447,7 +447,12 @@ public final class Locals { localNodes[j] = null; } - String desc = (local.getType() != null) ? local.getType().getDescriptor() : lastKnownType[j]; + String desc = lastKnownType[j]; + Type localType = local.getType(); + if (localType != null) { + desc = "null".equals(localType.getInternalName()) ? Constants.OBJECT_DESC : localType.getDescriptor(); + } + localNodes[j] = new LocalVariableNode("var" + j, desc, null, label, null, j); if (desc != null) { lastKnownType[j] = desc; @@ -497,7 +502,7 @@ public final class Locals { } return insn; } - + /** * Compute a new frame size based on the supplied frame type and the size of * locals contained in the frame (this may differ from the number of actual From a77b39022e9814a27691d3162002f566b06aed4a Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 18 Oct 2020 14:29:28 +0100 Subject: [PATCH 03/42] Propagate slice to context-sensitive injection points, fixes #429 --- .../asm/mixin/injection/code/Injector.java | 7 ++++--- .../mixin/injection/modify/BeforeLoadLocal.java | 5 +++-- .../injection/modify/ModifyVariableInjector.java | 14 ++++++++------ 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 197189a6..9bf02d2a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -295,7 +295,7 @@ public abstract class Injector { injectorTarget, injectorTarget.getMergedBy(), injectorTarget.getMergedPriority())); } - if (this.findTargetNodes(method, injectionPoint, injectorTarget.getSlice(injectionPoint), nodes)) { + if (this.findTargetNodes(method, injectionPoint, injectorTarget, nodes)) { for (AbstractInsnNode insn : nodes) { Integer key = method.instructions.indexOf(insn); TargetNode targetNode = targetNodes.get(key); @@ -311,8 +311,9 @@ public abstract class Injector { return targetNodes.values(); } - protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { - return injectionPoint.find(into.desc, insns, nodes); + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget, + Collection nodes) { + return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes); } protected void sanityCheck(Target target, List injectionPoints) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java index 1d2156ff..609fb55c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java @@ -30,6 +30,7 @@ import java.util.ListIterator; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.ModifyVariable; @@ -199,10 +200,10 @@ public class BeforeLoadLocal extends LocalVariableInjectionPoint { } @Override - boolean find(InjectionInfo info, Target target, Collection nodes) { + boolean find(InjectionInfo info, InsnList insns, Collection nodes, Target target) { SearchState state = new SearchState(); - ListIterator iter = target.method.instructions.iterator(); + ListIterator iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (state.isPendingCheck()) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 7e2916af..16d5abd1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -37,9 +37,10 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; -import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.Target.Extension; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -88,7 +89,7 @@ public class ModifyVariableInjector extends Injector { throw new InvalidInjectionException(this.mixin, this.getAtCode() + " injection point must be used in conjunction with @ModifyVariable"); } - abstract boolean find(InjectionInfo info, Target target, Collection nodes); + abstract boolean find(InjectionInfo info, InsnList insns, Collection nodes, Target target); } @@ -107,12 +108,13 @@ public class ModifyVariableInjector extends Injector { } @Override - protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget, + Collection nodes) { if (injectionPoint instanceof LocalVariableInjectionPoint) { - Target target = this.info.getContext().getTargetMethod(into); - return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, target, nodes); + return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, injectorTarget.getSlice(injectionPoint), nodes, + injectorTarget.getTarget()); } - return injectionPoint.find(into.desc, insns, nodes); + return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes); } /* (non-Javadoc) From 4f51eb55710706a3dbd941d5af1c9b4be9948d27 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 18 Oct 2020 16:15:46 +0100 Subject: [PATCH 04/42] Strip out-of-bounds shifts from injection point results, fixes #409 --- .../asm/mixin/injection/InjectionPoint.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 5d13cda3..33ecc1b0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -36,6 +36,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.ListIterator; import java.util.Map; import org.apache.logging.log4j.LogManager; @@ -454,9 +455,23 @@ public abstract class InjectionPoint { List list = (nodes instanceof List) ? (List) nodes : new ArrayList(nodes); this.input.find(desc, insns, nodes); - - for (int i = 0; i < list.size(); i++) { - list.set(i, insns.get(insns.indexOf(list.get(i)) + this.shift)); + + for (ListIterator iter = list.listIterator(); iter.hasNext();) { + int sourceIndex = insns.indexOf(iter.next()); + int newIndex = sourceIndex + this.shift; + if (newIndex >= 0 && newIndex < insns.size()) { + iter.set(insns.get(newIndex)); + } else { + // Shifted beyond the start or end of the insnlist, into the dark void + iter.remove(); + + // Decorate the injector with the info in case it fails + int absShift = Math.abs(this.shift); + char operator = absShift != this.shift ? '-' : '+'; + this.input.addMessage( + "@At.shift offset outside the target bounds: Index (index(%d) %s offset(%d) = %d) is outside the allowed range (0-%d)", + sourceIndex, operator, absShift, newIndex, insns.size()); + } } if (nodes != list) { From e8dd9239e07de7dd17fab32529d08286f273b778 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 23 Dec 2020 18:34:39 +0000 Subject: [PATCH 05/42] Ensure that all accessor annotations are correctly decorated, fixes #430 --- .../java/org/spongepowered/asm/mixin/gen/AccessorInfo.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index fd650c01..3e9000df 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -302,6 +302,7 @@ public class AccessorInfo extends SpecialMethodInfo { this.type = this.initType(); this.targetFieldType = this.initTargetFieldType(); this.target = this.initTarget(); + this.annotation.visit("target", this.target.toString()); } protected AccessorType initType() { @@ -331,9 +332,7 @@ public class AccessorInfo extends SpecialMethodInfo { } protected ITargetSelector initTarget() { - MemberInfo target = new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor()); - this.annotation.visit("target", target.toString()); - return target; + return new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor()); } protected String getTargetName(String name) { From 3ccc611e5eaf6c6dad458b83e623ba6d3146dca1 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 23 Dec 2020 18:47:37 +0000 Subject: [PATCH 06/42] Use full annotation class names when resolving injectors, fixes #443 --- .../mixin/injection/struct/InjectionInfo.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 7fea5525..646e6f73 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -117,19 +117,19 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC final Class annotationType; - final Class type; + final Class injectorType; final Constructor ctor; - final String simpleName; + final String annotationDesc; final String prefix; InjectorEntry(Class annotationType, Class type) throws NoSuchMethodException { this.annotationType = annotationType; - this.type = type; + this.injectorType = type; this.ctor = type.getDeclaredConstructor(MixinTargetContext.class, MethodNode.class, AnnotationNode.class); - this.simpleName = annotationType.getSimpleName() + ";"; + this.annotationDesc = Type.getDescriptor(annotationType); HandlerPrefix handlerPrefix = type.getAnnotation(HandlerPrefix.class); this.prefix = handlerPrefix != null ? handlerPrefix.value() : InjectionInfo.DEFAULT_PREFIX; @@ -144,9 +144,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC throw (MixinException)cause; } Throwable ex = cause != null ? cause : itex; - throw new MixinError("Error initialising injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex); + throw new MixinError("Error initialising injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex); } catch (ReflectiveOperationException ex) { - throw new MixinError("Failed to instantiate injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex); + throw new MixinError("Failed to instantiate injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex); } } } @@ -620,7 +620,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } for (InjectorEntry injector : InjectionInfo.registry.values()) { - if (annotation.desc.endsWith(injector.simpleName)) { + if (annotation.desc.equals(injector.annotationDesc)) { return injector.create(mixin, method, annotation); } } @@ -660,7 +660,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } for (InjectorEntry injector : InjectionInfo.registry.values()) { - if (annotation.desc.endsWith(injector.simpleName)) { + if (annotation.desc.endsWith(injector.annotationDesc)) { return injector.prefix; } } @@ -713,16 +713,16 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } catch (NoSuchMethodException ex) { throw new MixinError("InjectionInfo class " + type.getName() + " is missing a valid constructor"); } - InjectorEntry existing = InjectionInfo.registry.get(entry.simpleName); + InjectorEntry existing = InjectionInfo.registry.get(entry.annotationDesc); if (existing != null) { // && !existing.type.equals(type)) { MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding InjectionInfo for @%s with %s (previously %s)", - annotationType.value().getSimpleName(), type.getName(), existing.type.getName())); + annotationType.value().getSimpleName(), type.getName(), existing.injectorType.getName())); } else { MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new injector for @%s with %s", annotationType.value().getSimpleName(), type.getName())); } - InjectionInfo.registry.put(entry.simpleName, entry); + InjectionInfo.registry.put(entry.annotationDesc, entry); ArrayList> annotations = new ArrayList>(); for (InjectorEntry injector : InjectionInfo.registry.values()) { From f87008208c6e26e6783d546bfbb4e136299473eb Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 23 Dec 2020 19:22:15 +0000 Subject: [PATCH 07/42] Use staticness of invoker for arg offset, fixes #444 --- .../asm/mixin/gen/AccessorGeneratorMethodProxy.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java index c8504c76..c91baece 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java @@ -74,7 +74,7 @@ public class AccessorGeneratorMethodProxy extends AccessorGenerator { if (!this.targetIsStatic) { method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); } - Bytecode.loadArgs(this.argTypes, method.instructions, this.targetIsStatic ? 0 : 1); + Bytecode.loadArgs(this.argTypes, method.instructions, this.info.isStatic ? 0 : 1); boolean isPrivate = Bytecode.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE); int opcode = this.targetIsStatic ? Opcodes.INVOKESTATIC : (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL); method.instructions.add(new MethodInsnNode(opcode, this.info.getClassNode().name, this.targetMethod.name, this.targetMethod.desc, false)); From 922eacb35743edc93e12aa156745a6a4c56a2c1e Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 23 Dec 2020 19:50:08 +0000 Subject: [PATCH 08/42] Fix unexpected AIOOBE with empty handler signatures, fixes #411 --- .../org/spongepowered/asm/mixin/injection/code/Injector.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 9bf02d2a..9d04b89d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -574,12 +574,13 @@ public abstract class Injector { * if coercion is required for the argument */ protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) { - Type fromType = index < 0 ? this.returnType : this.methodArgs[index]; if (index >= this.methodArgs.length) { throw new InvalidInjectionException(this.info, String.format( "%s has an invalid signature. Not enough arguments: expected argument type %s at index %d", description, SignaturePrinter.getTypeName(toType), index)); } + + Type fromType = index < 0 ? this.returnType : this.methodArgs[index]; AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index); boolean isReturn = index < 0; From 08d6c7067dc9723f08c10646828850316094aa45 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 23 Jan 2021 21:19:13 +0000 Subject: [PATCH 09/42] Add support for dynamic and pattern target selectors --- .../tools/obfuscation/AnnotatedMixin.java | 87 +++++- .../AnnotatedMixinElementHandler.java | 46 +++ .../AnnotatedMixinElementHandlerAccessor.java | 69 +---- .../AnnotatedMixinElementHandlerInjector.java | 47 ++- ...atedMixinElementHandlerSoftImplements.java | 6 +- .../obfuscation/mirror/AnnotationHandle.java | 15 +- .../asm/mixin/gen/AccessorGenerator.java | 2 +- .../gen/AccessorGeneratorFieldSetter.java | 4 +- .../gen/AccessorGeneratorObjectFactory.java | 2 +- .../asm/mixin/gen/AccessorInfo.java | 10 +- .../throwables/InvalidAccessorException.java | 6 +- .../injection/IInjectionPointContext.java | 19 +- .../asm/mixin/injection/InjectionPoint.java | 85 ++++-- .../asm/mixin/injection/code/Injector.java | 8 +- .../asm/mixin/injection/code/MethodSlice.java | 16 +- .../injection/invoke/ModifyArgsInjector.java | 4 +- .../invoke/ModifyConstantInjector.java | 2 +- .../injection/invoke/RedirectInjector.java | 4 +- .../modify/ModifyVariableInjector.java | 2 +- .../injection/points/BeforeConstant.java | 4 +- .../injection/points/BeforeFinalReturn.java | 2 +- .../mixin/injection/points/BeforeInvoke.java | 2 +- .../asm/mixin/injection/points/BeforeNew.java | 2 +- .../injection/selectors/ISelectorContext.java | 83 ++++++ .../injection/selectors/ITargetSelector.java | 44 ++- .../selectors/ITargetSelectorDynamic.java | 62 ++++ .../injection/selectors/InvalidSelector.java | 96 +++++++ .../injection/selectors/TargetSelector.java | 191 +++++++++++-- .../dynamic/DynamicSelectorAbstract.java | 57 ++++ .../mixin/injection/struct/InjectionInfo.java | 2 +- .../InjectionPointAnnotationContext.java | 88 ++++++ .../injection/struct/InjectionPointData.java | 32 ++- .../mixin/injection/struct/MemberInfo.java | 16 +- .../mixin/injection/struct/MemberMatcher.java | 267 ++++++++++++++++++ .../struct/ModifyConstantInjectionInfo.java | 2 +- .../struct/SelectorAnnotationContext.java | 130 +++++++++ .../throwables/InvalidInjectionException.java | 12 +- .../throwables/InvalidSliceException.java | 6 +- .../asm/mixin/struct/AnnotatedMethodInfo.java | 47 ++- .../asm/mixin/transformer/MixinConfig.java | 86 ++++-- .../org/spongepowered/asm/util/Locals.java | 6 +- .../asm/util/asm/IAnnotationHandle.java | 38 +++ 42 files changed, 1472 insertions(+), 237 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java create mode 100644 src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 15405303..5713f306 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -36,11 +36,21 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.struct.SelectorAnnotationContext; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementAccessor; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementInvoker; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementSliceInjectionPoint; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite; import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible; @@ -55,10 +65,12 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle; import org.spongepowered.tools.obfuscation.mirror.TypeUtils; import org.spongepowered.tools.obfuscation.struct.InjectorRemap; +import com.google.common.base.Strings; + /** * Information about a mixin stored during processing */ -class AnnotatedMixin { +class AnnotatedMixin implements IMixinContext { /** * Mixin annotation @@ -289,7 +301,7 @@ class AnnotatedMixin { /** * Get the mixin class */ - public TypeElement getMixin() { + public TypeElement getMixinElement() { return this.mixin; } @@ -303,6 +315,7 @@ class AnnotatedMixin { /** * Get the mixin class reference */ + @Override public String getClassRef() { return this.classRef; } @@ -368,46 +381,100 @@ class AnnotatedMixin { } public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) { + System.err.printf(">>> %s\n", method); this.methods.remove(method); - this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, remap)); + AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap); + this.injectors.registerInjector(injectorElement); List ats = inject.getAnnotationList("at"); for (AnnotationHandle at : ats) { - this.registerInjectionPoint(method, inject, at, remap, "@At(%s)"); + this.registerInjectionPoint(method, inject, "at", at, remap, "@At(%s)"); } List slices = inject.getAnnotationList("slice"); for (AnnotationHandle slice : slices) { String id = slice.getValue("id", ""); + String coord = "slice"; + if (!Strings.isNullOrEmpty(id)) { + coord += "." + id; + } + SelectorAnnotationContext sliceContext = new SelectorAnnotationContext(injectorElement, slice, coord); AnnotationHandle from = slice.getAnnotation("from"); if (from != null) { - this.registerInjectionPoint(method, inject, from, remap, "@Slice[" + id + "](from=@At(%s))"); + this.registerSliceInjectionPoint(method, inject, "from", from, remap, "@Slice[" + id + "](from=@At(%s))", sliceContext); } AnnotationHandle to = slice.getAnnotation("to"); if (to != null) { - this.registerInjectionPoint(method, inject, to, remap, "@Slice[" + id + "](to=@At(%s))"); + this.registerSliceInjectionPoint(method, inject, "to", to, remap, "@Slice[" + id + "](to=@At(%s))", sliceContext); } } } - public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap remap, String format) { - this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at, remap), format); + public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at, + InjectorRemap remap, String format) { + this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, this, selectorCoordinate, at, remap), format); } + public void registerSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at, + InjectorRemap remap, String format, ISelectorContext parentContext) { + this.injectors.registerInjectionPoint(new AnnotatedElementSliceInjectionPoint(element, inject, this, selectorCoordinate, at, remap, + parentContext), format); + } + public void registerAccessor(ExecutableElement element, AnnotationHandle accessor, boolean shouldRemap) { this.methods.remove(element); - this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, shouldRemap)); + this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, this, shouldRemap)); } public void registerInvoker(ExecutableElement element, AnnotationHandle invoker, boolean shouldRemap) { this.methods.remove(element); - this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, shouldRemap)); + this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, this, shouldRemap)); } public void registerSoftImplements(AnnotationHandle implementsAnnotation) { this.softImplements.process(implementsAnnotation); } + @Override + public ReferenceMapper getReferenceMapper() { + return null; + } + + @Override + public String getClassName() { + return this.getClassRef().replace('/', '.'); + } + + @Override + public String getTargetClassRef() { + throw new UnsupportedOperationException("Target class not available at compile time"); + } + + @Override + public IMixinInfo getMixin() { + throw new UnsupportedOperationException("MixinInfo not available at compile time"); + } + + @Override + public Extensions getExtensions() { + throw new UnsupportedOperationException("Mixin Extensions not available at compile time"); + } + + @Override + public boolean getOption(Option option) { + throw new UnsupportedOperationException("Options not available at compile time"); + } + + @Override + public int getPriority() { + throw new UnsupportedOperationException("Priority not available at compile time"); + } + + @Override + public Target getTargetMethod(MethodNode into) { + throw new UnsupportedOperationException("Target not available at compile time"); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 6517e6c1..433fba93 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -33,8 +33,10 @@ import javax.lang.model.element.VariableElement; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -104,6 +106,50 @@ abstract class AnnotatedMixinElementHandler { } + abstract static class AnnotatedElementExecutable extends AnnotatedElement implements ISelectorContext { + + private final IMixinContext context; + + private final String selectorCoordinate; + + public AnnotatedElementExecutable(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, String selectorCoordinate) { + super(element, annotation); + this.context = context; + this.selectorCoordinate = selectorCoordinate; + } + + @Override + public ISelectorContext getParent() { + return null; + } + + @Override + public IMixinContext getMixin() { + return this.context; + } + + @Override + public Object getMethod() { + return this.getElement(); + } + + @Override + public Object getSelectorAnnotation() { + return this.getAnnotation(); + } + + @Override + public String getSelectorCoordinate() { + return this.selectorCoordinate; + } + + @Override + public String remap(String reference) { + return reference; + } + + } + /** * A name of an element which may have aliases */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index b65d3a9e..e3e75e19 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -30,18 +30,12 @@ import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; -import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.AccessorInfo; import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorName; import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorType; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.ReferenceMapper; -import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.Constants; @@ -60,21 +54,21 @@ import com.google.common.base.Strings; /** * A module for {@link AnnotatedMixin} which handles accessors */ -public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler implements IMixinContext { +public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler { /** * Accessor element */ - static class AnnotatedElementAccessor extends AnnotatedElement { + static class AnnotatedElementAccessor extends AnnotatedElementExecutable { protected final boolean shouldRemap; - + protected final TypeMirror returnType; protected String targetName; - public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { - super(element, annotation); + public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) { + super(element, annotation, context, "value"); this.shouldRemap = shouldRemap; this.returnType = this.getElement().getReturnType(); } @@ -147,8 +141,8 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH private AccessorType type = AccessorType.METHOD_PROXY; - public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { - super(element, annotation, shouldRemap); + public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) { + super(element, annotation, context, shouldRemap); } @Override @@ -201,56 +195,11 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } } - + public AnnotatedMixinElementHandlerAccessor(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } - @Override - public ReferenceMapper getReferenceMapper() { - return null; - } - - @Override - public String getClassName() { - return this.mixin.getClassRef().replace('/', '.'); - } - - @Override - public String getClassRef() { - return this.mixin.getClassRef(); - } - - @Override - public String getTargetClassRef() { - throw new UnsupportedOperationException("Target class not available at compile time"); - } - - @Override - public IMixinInfo getMixin() { - throw new UnsupportedOperationException("MixinInfo not available at compile time"); - } - - @Override - public Extensions getExtensions() { - throw new UnsupportedOperationException("Mixin Extensions not available at compile time"); - } - - @Override - public boolean getOption(Option option) { - throw new UnsupportedOperationException("Options not available at compile time"); - } - - @Override - public int getPriority() { - throw new UnsupportedOperationException("Priority not available at compile time"); - } - - @Override - public Target getTargetMethod(MethodNode into) { - throw new UnsupportedOperationException("Target not available at compile time"); - } - /** * Register a new accessor * @@ -387,7 +336,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } private String inflectAccessorTarget(AnnotatedElementAccessor elem) { - return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", this, false); + return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", elem, false); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index afd76ceb..fdd02a6c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -35,6 +35,7 @@ import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; @@ -42,6 +43,7 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; @@ -61,12 +63,12 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler /** * Injector element */ - static class AnnotatedElementInjector extends AnnotatedElement { + static class AnnotatedElementInjector extends AnnotatedElementExecutable { private final InjectorRemap state; - public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, InjectorRemap shouldRemap) { - super(element, annotation); + public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, InjectorRemap shouldRemap) { + super(element, annotation, context, "method"); this.state = shouldRemap; } @@ -100,7 +102,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler /** * Injection point element */ - static class AnnotatedElementInjectionPoint extends AnnotatedElement { + static class AnnotatedElementInjectionPoint extends AnnotatedElementExecutable { private final AnnotationHandle at; @@ -108,8 +110,9 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler private final InjectorRemap state; - public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap state) { - super(element, inject); + public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context, String selectorCoordinate, + AnnotationHandle at, InjectorRemap state) { + super(element, inject, context, selectorCoordinate); this.at = at; this.state = state; } @@ -122,6 +125,11 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return this.at; } + @Override + public Object getSelectorAnnotation() { + return this.getAt(); + } + public String getAtArg(String key) { if (this.args == null) { this.args = new HashMap(); @@ -147,6 +155,23 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } + static class AnnotatedElementSliceInjectionPoint extends AnnotatedElementInjectionPoint { + + private final ISelectorContext parentContext; + + public AnnotatedElementSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context, + String selectorCoordinate, AnnotationHandle at, InjectorRemap state, ISelectorContext parentContext) { + super(element, inject, context, selectorCoordinate, at, state); + this.parentContext = parentContext; + } + + @Override + public ISelectorContext getParent() { + return this.parentContext; + } + + } + AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } @@ -157,7 +182,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } for (String reference : elem.getAnnotation().getList("method")) { - ITargetSelector targetSelector = TargetSelector.parse(reference); + ITargetSelector targetSelector = TargetSelector.parse(reference, elem); try { targetSelector.validate(); @@ -231,8 +256,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String conflictType = this.mixin.isMultiTarget() ? "Multi-target" : "Target"; if (elem.hasCoerceArgument() && targetMember.getOwner() == null && targetMember.getDesc() == null) { - ITargetSelector oldMember = TargetSelector.parse(ex.getOld()); - ITargetSelector newMember = TargetSelector.parse(ex.getNew()); + ITargetSelector oldMember = TargetSelector.parse(ex.getOld(), elem); + ITargetSelector newMember = TargetSelector.parse(ex.getNew(), elem); String oldName = oldMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)oldMember).getName() : oldMember.toString(); String newName = newMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)newMember).getName() : newMember.toString(); if (oldName != null && oldName.equals(newName)) { @@ -284,7 +309,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return; } - ITargetSelector selector = TargetSelector.parse(reference); + ITargetSelector selector = TargetSelector.parse(reference, elem); if (selector instanceof ITargetSelectorConstructor) { ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; String target = member.toCtorType(); @@ -321,7 +346,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return; } - ITargetSelector targetSelector = TargetSelector.parse(reference); + ITargetSelector targetSelector = TargetSelector.parse(reference, elem); if (!(targetSelector instanceof ITargetSelectorRemappable)) { return; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java index 537da970..330494ed 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java @@ -67,7 +67,7 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl // Derp? if (interfaces.size() < 1) { - this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixin(), implementsAnnotation.asMirror()); + this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixinElement(), implementsAnnotation.asMirror()); return; } @@ -82,8 +82,8 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl String prefix = interfaceAnnotation.getValue("prefix"); this.processSoftImplements(remap, iface, prefix); } catch (Exception ex) { - this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), this.mixin.getMixin(), - interfaceAnnotation.asMirror()); + this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), + this.mixin.getMixinElement(), interfaceAnnotation.asMirror()); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index 71afb97d..469226cf 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -36,13 +36,15 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + import com.google.common.collect.ImmutableList; /** * A wrapper for {@link AnnotationMirror} which provides a more convenient way * to access annotation values. */ -public final class AnnotationHandle { +public final class AnnotationHandle implements IAnnotationHandle { public static final AnnotationHandle MISSING = new AnnotationHandle(null); @@ -79,6 +81,17 @@ public final class AnnotationHandle { return this.annotation != null; } + /* (non-Javadoc) + * @see org.spongepowered.asm.util.asm.IAnnotationHandle#getDesc() + */ + @Override + public String getDesc() { + if (this.annotation == null) { + return "java/lang/Annotation"; + } + return TypeUtils.getInternalName(this.annotation.getAnnotationType()); + } + @Override public String toString() { if (this.annotation == null) { diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java index e11bded5..deee0838 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -55,7 +55,7 @@ public abstract class AccessorGenerator { protected void checkModifiers() { if (this.info.isStatic() && !this.targetIsStatic) { - IMixinContext context = this.info.getContext(); + IMixinContext context = this.info.getMixin(); throw new InvalidInjectionException(context, String.format("%s is invalid. Accessor method is%s static but the target is not.", this.info, this.info.isStatic() ? "" : " not")); } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java index cee3d330..0dad09c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java @@ -60,9 +60,9 @@ public class AccessorGeneratorFieldSetter extends AccessorGeneratorField { return; } - if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { LogManager.getLogger("mixin").warn("{} for final field {}::{} is not @Mutable", this.info, - ((MixinTargetContext)this.info.getContext()).getTarget(), this.targetField.name); + ((MixinTargetContext)this.info.getMixin()).getTarget(), this.targetField.name); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java index 5c09ad4f..bcbc16ff 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java @@ -41,7 +41,7 @@ public class AccessorGeneratorObjectFactory extends AccessorGeneratorMethodProxy public AccessorGeneratorObjectFactory(AccessorInfo info) { super(info, true); if (!info.isStatic()) { - throw new InvalidInjectionException(info.getContext(), String.format("%s is invalid. Factory method must be static.", this.info)); + throw new InvalidInjectionException(info.getMixin(), String.format("%s is invalid. Factory method must be static.", this.info)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index 3e9000df..32dee538 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -39,11 +39,11 @@ import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; @@ -344,7 +344,7 @@ public class AccessorInfo extends SpecialMethodInfo { } return inflectedTarget; } - return TargetSelector.parseName(name, this.mixin); + return TargetSelector.parseName(name, this); } /** @@ -354,7 +354,7 @@ public class AccessorInfo extends SpecialMethodInfo { * foo for example. */ protected String inflectTarget() { - return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin, + return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this, this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE)); } @@ -375,7 +375,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return inflected target member name or null if name cannot be * inflected */ - public static String inflectTarget(String name, AccessorType type, String description, IMixinContext context, boolean verbose) { + public static String inflectTarget(String name, AccessorType type, String description, ISelectorContext context, boolean verbose) { return AccessorInfo.inflectTarget(AccessorName.of(name), type, description, context, verbose); } @@ -396,7 +396,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return inflected target member name or null if name cannot be * inflected */ - public static String inflectTarget(AccessorName name, AccessorType type, String description, IMixinContext context, boolean verbose) { + public static String inflectTarget(AccessorName name, AccessorType type, String description, ISelectorContext context, boolean verbose) { if (name != null) { if (!type.isExpectedPrefix(name.prefix) && verbose) { LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", description, name.prefix, diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java index 85d48c85..e7541e74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java @@ -43,7 +43,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, String message) { - super(info.getContext(), message); + super(info.getMixin(), message); this.info = info; } @@ -53,7 +53,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, Throwable cause) { - super(info.getContext(), cause); + super(info.getMixin(), cause); this.info = info; } @@ -63,7 +63,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) { - super(info.getContext(), message, cause); + super(info.getMixin(), message, cause); this.info = info; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java index b98dcad7..f13199f5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java @@ -26,28 +26,31 @@ package org.spongepowered.asm.mixin.injection; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.util.IMessageSink; /** * Context for an injection point, used to access the mixin as well as the owner * method and annotation for the injection point */ -public interface IInjectionPointContext extends IMessageSink { - - /** - * Get the mixin context for this injection - */ - public abstract IMixinContext getContext(); +public interface IInjectionPointContext extends IMessageSink, ISelectorContext { /** * Get the injection handler method */ + @Override public abstract MethodNode getMethod(); /** * Get the parent annotation (eg. the @Inject annotation) */ + @Override public abstract AnnotationNode getAnnotation(); - + + /** + * Get the selector annotation (eg. the @At annotation) + */ + @Override + public abstract AnnotationNode getSelectorAnnotation(); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 33ecc1b0..e30de0af 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -30,6 +30,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -50,6 +51,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; import org.spongepowered.asm.mixin.injection.points.*; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -60,6 +62,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.IMessageSink; import com.google.common.base.Joiner; +import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; @@ -92,9 +95,17 @@ public abstract class InjectionPoint { @Target(ElementType.TYPE) public @interface AtCode { + /** + * Namespace for this code. Final selectors will be specified as + * <namespace>:<code> in order to avoid overlaps + * between consumer-provided injection points. + */ + public String namespace() default ""; + /** * The string code used to specify the annotated injection point in At - * annotations + * annotations, prefixed with namespace from the annotation or from the + * declaring configuration. */ public String value(); @@ -200,18 +211,18 @@ public abstract class InjectionPoint { static { // Standard Injection Points - InjectionPoint.register(BeforeFieldAccess.class); - InjectionPoint.register(BeforeInvoke.class); - InjectionPoint.register(BeforeNew.class); - InjectionPoint.register(BeforeReturn.class); - InjectionPoint.register(BeforeStringInvoke.class); - InjectionPoint.register(JumpInsnPoint.class); - InjectionPoint.register(MethodHead.class); - InjectionPoint.register(AfterInvoke.class); - InjectionPoint.register(BeforeLoadLocal.class); - InjectionPoint.register(AfterStoreLocal.class); - InjectionPoint.register(BeforeFinalReturn.class); - InjectionPoint.register(BeforeConstant.class); + InjectionPoint.registerBuiltIn(BeforeFieldAccess.class); + InjectionPoint.registerBuiltIn(BeforeInvoke.class); + InjectionPoint.registerBuiltIn(BeforeNew.class); + InjectionPoint.registerBuiltIn(BeforeReturn.class); + InjectionPoint.registerBuiltIn(BeforeStringInvoke.class); + InjectionPoint.registerBuiltIn(JumpInsnPoint.class); + InjectionPoint.registerBuiltIn(MethodHead.class); + InjectionPoint.registerBuiltIn(AfterInvoke.class); + InjectionPoint.registerBuiltIn(BeforeLoadLocal.class); + InjectionPoint.registerBuiltIn(AfterStoreLocal.class); + InjectionPoint.registerBuiltIn(BeforeFinalReturn.class); + InjectionPoint.registerBuiltIn(BeforeConstant.class); } private final String slice; @@ -568,7 +579,7 @@ public abstract class InjectionPoint { public static List parse(IInjectionPointContext context, List ats) { Builder injectionPoints = ImmutableList.builder(); for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(context, at); + InjectionPoint injectionPoint = InjectionPoint.parse(new InjectionPointAnnotationContext(context, at, "at"), at); if (injectionPoint != null) { injectionPoints.add(injectionPoint); } @@ -619,7 +630,7 @@ public abstract class InjectionPoint { * failed */ public static InjectionPoint parse(IMixinContext context, MethodNode method, AnnotationNode parent, AnnotationNode at) { - return InjectionPoint.parse(new AnnotatedMethodInfo(context, method, parent), at); + return InjectionPoint.parse(new InjectionPointAnnotationContext(new AnnotatedMethodInfo(context, method, parent), at, "at"), at); } /** @@ -696,8 +707,8 @@ public abstract class InjectionPoint { public static InjectionPoint parse(IInjectionPointContext context, String at, At.Shift shift, int by, List args, String target, String slice, int ordinal, int opcode, String id) { InjectionPointData data = new InjectionPointData(context, at, args, target, slice, ordinal, opcode, id); - Class ipClass = findClass(context.getContext(), data); - InjectionPoint point = InjectionPoint.create(context.getContext(), data, ipClass); + Class ipClass = InjectionPoint.findClass(context.getMixin(), data); + InjectionPoint point = InjectionPoint.create(context.getMixin(), data, ipClass); return InjectionPoint.shift(context, point, shift, by); } @@ -732,6 +743,8 @@ public abstract class InjectionPoint { InjectionPoint point = null; try { point = ipCtor.newInstance(data); + } catch (InvocationTargetException ex) { + throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex.getCause()); } catch (Exception ex) { throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex); } @@ -748,7 +761,7 @@ public abstract class InjectionPoint { } else if (shift == At.Shift.AFTER) { return InjectionPoint.after(point); } else if (shift == At.Shift.BY) { - InjectionPoint.validateByValue(context.getContext(), context.getMethod(), context.getAnnotation(), point, by); + InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotation(), point, by); return InjectionPoint.shift(point, by); } } @@ -802,19 +815,53 @@ public abstract class InjectionPoint { * * @param type injection point type to register */ + @Deprecated public static void register(Class type) { + } + + /** + * Register an injection point class. The supplied class must be decorated + * with an {@link AtCode} annotation for registration purposes. + * + * @param type injection point type to register + * @param namespace namespace for AtCode + */ + public static void register(Class type, String namespace) { AtCode code = type.getAnnotation(AtCode.class); if (code == null) { throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode"); } + String annotationNamespace = code.namespace(); + if (!Strings.isNullOrEmpty(annotationNamespace)) { + namespace = annotationNamespace; + } + Class existing = InjectionPoint.types.get(code.value()); if (existing != null && !existing.equals(type)) { LogManager.getLogger("mixin").debug("Overriding InjectionPoint {} with {} (previously {})", code.value(), type.getName(), existing.getName()); + } else if (Strings.isNullOrEmpty(namespace)) { + LogManager.getLogger("mixin").warn("Registration of InjectionPoint {} with {} without specifying namespace is deprecated.", + code.value(), type.getName()); } - InjectionPoint.types.put(code.value(), type); + String id = code.value(); + if (!Strings.isNullOrEmpty(namespace)) { + id = namespace + ":" + code.value(); + } + + InjectionPoint.types.put(id, type); + } + + /** + * Register a built-in injection point class. Skips validation and + * namespacing checks + * + * @param type injection point type to register + */ + private static void registerBuiltIn(Class type) { + InjectionPoint.types.put(type.getAnnotation(AtCode.class).value(), type); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 9d04b89d..633649ec 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -256,7 +256,7 @@ public abstract class Injector { public final void inject(Target target, List nodes) { for (InjectionNode node : nodes) { if (node.isRemoved()) { - if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target); } continue; @@ -279,7 +279,7 @@ public abstract class Injector { * @return Target insn nodes in the target method */ private Collection findTargetNodes(InjectorTarget injectorTarget, List injectionPoints) { - IMixinContext mixin = this.info.getContext(); + IMixinContext mixin = this.info.getMixin(); MethodNode method = injectorTarget.getMethod(); Map targetNodes = new TreeMap(); Collection nodes = new ArrayList(32); @@ -522,7 +522,7 @@ public abstract class Injector { * @param args Array of handler args, must not be null */ protected final void validateParams(InjectorData injector, Type returnType, Type... args) { - String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext()); + String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getMixin()); int argIndex = 0; try { injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs); @@ -588,7 +588,7 @@ public abstract class Injector { Object argIndex = isReturn ? "" : " at index " + index; if (fromType.equals(toType)) { - if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (coerce != null && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex, SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java index 85ac3af6..9852b75a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -40,10 +40,11 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; import com.google.common.base.Strings; @@ -406,7 +407,7 @@ public final class MethodSlice { } if (!result) { - if (this.owner.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) { MethodSlice.logger.warn("{} did not match any instructions", this.describe(description)); } return failValue; @@ -434,7 +435,7 @@ public final class MethodSlice { private static String describeSlice(String description, ISliceContext owner) { String annotation = Bytecode.getSimpleName(owner.getAnnotation()); MethodNode method = owner.getMethod(); - return String.format("%s->%s(%s)::%s%s", owner.getContext(), annotation, description, method.name, method.desc); + return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc); } private static String getSliceName(String id) { @@ -469,12 +470,17 @@ public final class MethodSlice { */ public static MethodSlice parse(ISliceContext info, AnnotationNode node) { String id = Annotations.getValue(node, "id"); + String coord = "slice"; + if (!Strings.isNullOrEmpty(id)) { + coord += "." + id; + } + InjectionPointAnnotationContext sliceContext = new InjectionPointAnnotationContext(info, node, coord); AnnotationNode from = Annotations.getValue(node, "from"); AnnotationNode to = Annotations.getValue(node, "to"); - InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null; - InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null; + InjectionPoint fromPoint = from != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, from, "from"), from) : null; + InjectionPoint toPoint = to != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, to, "to"), to) : null; return new MethodSlice(info, id, fromPoint, toPoint); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java index b722d806..df75a876 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java @@ -53,7 +53,7 @@ public class ModifyArgsInjector extends InvokeInjector { public ModifyArgsInjector(InjectionInfo info) { super(info, "@ModifyArgs"); - this.argsClassGenerator = info.getContext().getExtensions().getGenerator(ArgsClassGenerator.class); + this.argsClassGenerator = info.getMixin().getExtensions().getGenerator(ArgsClassGenerator.class); } /* (non-Javadoc) @@ -84,7 +84,7 @@ public class ModifyArgsInjector extends InvokeInjector { + targetMethod.name + targetMethod.desc + " with no arguments!"); } - String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getContext().getMixin()).getName(); + String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getMixin().getMixin()).getName(); boolean withArgs = this.verifyTarget(target); InsnList insns = new InsnList(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index 3f60bb30..a9ad8835 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -133,7 +133,7 @@ public class ModifyConstantInjector extends RedirectInjector { private void injectConstantModifier(Target target, AbstractInsnNode constNode) { final Type constantType = Bytecode.getConstantType(constNode); - if (constantType.getSort() <= Type.INT && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (constantType.getSort() <= Type.INT && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { this.checkNarrowing(target, constNode, constantType); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index a8aa0f47..2cde5ecd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -234,7 +234,7 @@ public class RedirectInjector extends InvokeInjector { protected RedirectInjector(InjectionInfo info, String annotationType) { super(info, annotationType); - int priority = info.getContext().getPriority(); + int priority = info.getMixin().getPriority(); boolean isFinal = Annotations.getVisible(this.methodNode, Final.class) != null; this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc); } @@ -463,7 +463,7 @@ public class RedirectInjector extends InvokeInjector { Type elementType = field.type.getElementType(); int valueArgIndex = field.getTotalDimensions(); if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s", - this.annotationType, this, this.info.getContext()), true)) { + this.annotationType, this, this.info.getMixin()), true)) { elementType = this.methodArgs[valueArgIndex]; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 16d5abd1..4d02c557 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -81,7 +81,7 @@ public class ModifyVariableInjector extends Injector { LocalVariableInjectionPoint(InjectionPointData data) { super(data); - this.mixin = data.getContext(); + this.mixin = data.getMixin(); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index 8354bb58..db18ffdb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -182,9 +182,9 @@ public class BeforeConstant extends InjectionPoint { String strClassValue = data.get("classValue", null); this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null; - this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args"); + this.matchByType = this.validateDiscriminator(data.getMixin(), "V", empty, "in @At(\"CONSTANT\") args"); if ("V".equals(this.matchByType)) { - throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args"); + throw new InvalidInjectionException(data.getMixin(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args"); } List conditions = new ArrayList(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java index 053fb872..f34f7c65 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java @@ -64,7 +64,7 @@ public class BeforeFinalReturn extends InjectionPoint { public BeforeFinalReturn(InjectionPointData data) { super(data); - this.context = data.getContext(); + this.context = data.getMixin(); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index d58c273a..406cceb4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -127,7 +127,7 @@ public class BeforeInvoke extends InjectionPoint { this.ordinal = data.getOrdinal(); this.log = data.get("log", false); this.className = this.getClassName(); - this.context = data.getContext(); + this.context = data.getMixin(); this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) && !this.context.getReferenceMapper().isDefault(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java index 7b0df8ce..c0484c5e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java @@ -113,7 +113,7 @@ public class BeforeNew extends InjectionPoint { String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); ITargetSelector member = TargetSelector.parseAndValidate(target, data.getContext()); if (!(member instanceof ITargetSelectorConstructor)) { - throw new InvalidInjectionPointException(data.getContext(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s", + throw new InvalidInjectionPointException(data.getMixin(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s", target, data.getDescription()); } ITargetSelectorConstructor targetSelector = (ITargetSelectorConstructor)member; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java new file mode 100644 index 00000000..9178198e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java @@ -0,0 +1,83 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import org.spongepowered.asm.mixin.refmap.IMixinContext; + +/** + * Context passed to a {@link ITargetSelector Target Selector} in order to + * support context-sensitive behaviour for the selector. For example obtaining + * the name of the source mixin, or the element containing the selector itself. + */ +public interface ISelectorContext { + + /** + * Get the parent (outer/containing) context. Can be null if this is a root + * element such as an injector method, in which case the parent is the mixin + * instead. + */ + public abstract ISelectorContext getParent(); + + /** + * Get the mixin containing this selector. + */ + public abstract IMixinContext getMixin(); + + /** + * Get the root method upon which this selector is operating, usually the + * injector method + */ + public abstract Object getMethod(); + + /** + * Get the root annotation for the selector, for example the injector or + * accessor annotation + */ + public abstract Object getAnnotation(); + + /** + * Get the annotation for this selector, for example the @At annotation + */ + public abstract Object getSelectorAnnotation(); + + /** + * Get the coordinate for this selector. This is the local coordinate of the + * selector without any parent parts. Parent parts are prepended by + * consumers during the resolve process. + */ + public abstract String getSelectorCoordinate(); + + /** + * Remap a reference in the context of this selector, usually via the local + * refmap of the mixin configuration but can be overridden as needed, for + * example to provide selector-local remap behaviour. + * + * @param reference Reference to remap + * @return Remapped reference or original reference if not remapped, must + * not return null! + */ + public abstract String remap(String reference); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 1dffd05b..d194324a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -26,7 +26,7 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; import org.spongepowered.asm.util.asm.ElementNode; /** @@ -40,13 +40,49 @@ import org.spongepowered.asm.util.asm.ElementNode; *

Explicit Target Selectors are handled internally using * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the * supported variants and examples.

+ * + *

Pattern Target Selectors (Regex Selectors)

+ * + *

Pattern Target Selectors are handled internally using + * {@link MemberMatcher}, see the javadoc for {@link MemberMatcher} for the + * supported variants and examples. Pattern Selectors always end with a forward + * slash character.

+ * + *

Dynamic Target Selectors

+ * + *

Dynamic Target Selectors can be built-in or user-supplied types + * with their own specialised syntax or behaviour. Dynamic selectors are + * specified in the following format, and can be recognised by the fact that + * the selector string starts with "@":

+ * + *
+ *   // Built-in dynamic selector without argument string
+ *   @SelectorId
+ *   
+ *   // Built-in dynamic selector with empty argument string
+ *   @SelectorId()
+ *   
+ *   // Built-in dynamic selector with argument
+ *   @SelectorId(custom,argument,string,in,any,format)
+ *   
+ *   // User-provided dynamic selector with argument. Note that user-provided
+ *   // dynamic selectors are namespaced to avoid conflicts.
+ *   @Namespace:SelectorId(some arguments)
+ *
+ * + *

The exact format of the argument string is specified by the dynamic + * selector itself, consult the documentation for the dynamic selector you are + * using for details on the required format.

+ * */ public interface ITargetSelector { /** * Get the next target selector in this path (or null if this * selector is the last selector in the chain. Called at recurse points in - * the subject in order to match against the child subject. + * the subject in order to match against the child subject. + * + *

Can return null

*/ public abstract ITargetSelector next(); @@ -61,6 +97,8 @@ public interface ITargetSelector { * already configured according to "foo" may simply return this * object, or might return an identically-configured copy.

* + *

Must not return null

+ * * @param args Configuration arguments * @return Configured selector, may return this selector if the specified * condition is already satisfied @@ -86,7 +124,7 @@ public interface ITargetSelector { * @param context Context to attach to * @return Attached selector */ - public abstract ITargetSelector attach(IMixinContext context) throws InvalidSelectorException; + public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException; /** * Number of candidates which this selector should match diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java new file mode 100644 index 00000000..234a5f43 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Decoration interface for dynamic target selectors + */ +public interface ITargetSelectorDynamic extends ITargetSelector { + + /** + * Decoration for subclasses which indicates id used for a specific selector + * when specified, for example @MyNamespace:MySelector(argshere) + * would specify "MySelector" + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface SelectorId { + + /** + * Namespace for this code. Final selectors will be specified as + * <namespace>:<id> in order to avoid overlaps + * between consumer-provided selectors. If left blank defaults to the + * namespace specified in the configuration. + */ + public String namespace() default ""; + + /** + * The string code used to specify the selector selector strings, + * prefixed with namespace from the annotation or from the declaring + * configuration. + */ + public String value(); + + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java new file mode 100644 index 00000000..519b90b4 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -0,0 +1,96 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.spongepowered.asm.util.asm.ElementNode; + +public class InvalidSelector implements ITargetSelector { + + private String input; + + private Throwable cause; + + public InvalidSelector(Throwable cause) { + this(cause, null); + } + + public InvalidSelector(String input) { + this(null, input); + } + + public InvalidSelector(Throwable cause, String input) { + this.input = input; + this.cause = cause; + } + + @Override + public ITargetSelector next() { + return null; + } + + @Override + public ITargetSelector configure(String... args) { + return this; + } + + @Override + public ITargetSelector validate() throws InvalidSelectorException { + if (this.cause instanceof InvalidSelectorException) { + throw (InvalidSelectorException)this.cause; + } + String message = "Error parsing target selector"; + if (this.input != null) { + message += ", the input was in an unexpected format: " + this.input; + } + if (this.cause != null) { + throw new InvalidSelectorException(message, this.cause); + } + throw new InvalidSelectorException(message); + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMatchCount() { + return 0; + } + + @Override + public MatchResult match(ElementNode node) { + this.validate(); + return MatchResult.NONE; + } + + @Override + public MatchResult match(AbstractInsnNode insn) { + this.validate(); + return MatchResult.NONE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index f3ed43cb..39640c98 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -24,14 +24,29 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.IReferenceMapper; +import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; +import org.spongepowered.asm.mixin.throwables.MixinError; +import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.logging.MessageRouter; + +import com.google.common.base.Strings; /** * Utility class for parsing selectors @@ -85,17 +100,121 @@ public final class TargetSelector { } + /** + * A dynamic selector registration entry + */ + static class DynamicSelectorEntry { + + final String namespace; + + final String id; + + final Class type; + + final Method parse; + + DynamicSelectorEntry(String namespace, String id, Class type) throws NoSuchMethodException { + this.namespace = namespace; + this.id = id; + this.type = type; + this.parse = type.getDeclaredMethod("parse", String.class, ISelectorContext.class); + if (!Modifier.isStatic(this.parse.getModifiers())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static"); + } + if (!ITargetSelectorDynamic.class.isAssignableFrom(this.parse.getReturnType())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + + "] must return an ITargetSelectorDynamic subtype"); + } + } + + String getCode() { + return (this.namespace != null ? this.namespace + ":" : "") + this.id; + } + + ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException { + try { + return (ITargetSelectorDynamic)this.parse.invoke(null, input, context); + } catch (InvocationTargetException itex) { + Throwable cause = itex.getCause(); + if (cause instanceof MixinException) { + throw (MixinException)cause; + } + Throwable ex = cause != null ? cause : itex; + throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex); + } + } + } + + /** + * Pattern for matching dynamic selectors + */ + private static final Pattern PATTERN_DYNAMIC = Pattern.compile("^\\x40([a-z]+(:[a-z]+)?)(\\((.*)\\))?$", Pattern.CASE_INSENSITIVE); + + /** + * Registered dynamic selectors + */ + private static Map dynamicSelectors = new LinkedHashMap(); + private TargetSelector() { } /** - * Parse a target selector from a string and perform validation + * Register a dynamic target selector class. The supplied class must be + * decorated with an {@link SelectorId} annotation for registration to + * succeed. * - * @param string String to parse target selector from - * @return parsed target selector + * @param type ITargetSelectorDynamic to register + * @param namespace namespace for SelectorId */ - public static ITargetSelector parseAndValidate(String string) throws InvalidMemberDescriptorException { - return TargetSelector.parse(string, null, null).validate(); + public static void register(Class type, String namespace) { + SelectorId selectorId = type.getAnnotation(SelectorId.class); + if (selectorId == null) { + throw new IllegalArgumentException("Dynamic target selector class " + type + " is not annotated with @SelectorId"); + } + + String annotationNamespace = selectorId.namespace(); + if (!Strings.isNullOrEmpty(annotationNamespace)) { + namespace = annotationNamespace; + } + + if (Strings.isNullOrEmpty(namespace)) { + throw new IllegalArgumentException("Dynamic target selector class " + type + + " has no namespace. Please specify namespace in SelectorId annotation or declaring configuration"); + } + + DynamicSelectorEntry entry; + try { + entry = new DynamicSelectorEntry(namespace, selectorId.value().toLowerCase(Locale.ROOT), type); + } catch (NoSuchMethodException ex) { + throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); + } + DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(entry.id); + if (existing != null) { // && !existing.type.equals(type)) { + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)", + entry.id, type.getName(), existing.type.getName())); + } else { + MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s", + entry.id, type.getName())); + } + + TargetSelector.dynamicSelectors.put(entry.getCode(), entry); + } + + /** + * Register a built-in target selector class. Skips validation and + * namespacing checks + * + * @param type ITargetSelectorDynamic to register + */ + private static void registerBuiltIn(Class type) { + SelectorId selectorId = type.getAnnotation(SelectorId.class); + DynamicSelectorEntry entry; + try { + entry = new DynamicSelectorEntry(null, selectorId.value().toLowerCase(Locale.ROOT), type); + } catch (NoSuchMethodException ex) { + throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); + } + TargetSelector.dynamicSelectors.put(entry.getCode(), entry); } /** @@ -105,18 +224,8 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException { - return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()).validate(); - } - - /** - * Parse a target selector from a string - * - * @param string String to parse target selector from - * @return parsed target selector - */ - public static ITargetSelector parse(String string) { - return TargetSelector.parse(string, null, null); + public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidMemberDescriptorException { + return TargetSelector.parse(string, context).validate(); } /** @@ -126,8 +235,42 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parse(String string, IMixinContext context) { - return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()); + public static ITargetSelector parse(String string, ISelectorContext context) { + string = string.trim(); + + // Ending with slash indicates a regex target, no other type of target + // selector can end (legally) with a forward slash + if (string.endsWith("/")) { + MemberMatcher regexMatcher = MemberMatcher.parse(string, context); + if (regexMatcher != null) { + return regexMatcher; + } + } + + // Starting with @ indicates a dynamic target. Parse as a regular + // MemberInfo if the selector does not start with @ + if (!string.startsWith("@")) { + return MemberInfo.parse(string, context); + } + + Matcher dynamic = TargetSelector.PATTERN_DYNAMIC.matcher(string); + if (!dynamic.matches()) { + return new InvalidSelector(new InvalidSelectorException("Dynamic selector was in an unrecognised format. Parsing selector: " + string)); + } + + String selectorId = dynamic.group(1).toLowerCase(Locale.ROOT); + if (!TargetSelector.dynamicSelectors.containsKey(selectorId)) { + return new InvalidSelector(new InvalidSelectorException("Dynamic selector with id '@" + dynamic.group(1) + + "' is not registered. Parsing selector: " + string)); + } + + try { + return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)), context); + } catch (ReflectiveOperationException ex) { + return new InvalidSelector(ex.getCause(), string); + } catch (Exception ex) { + return new InvalidSelector(ex); + } } /** @@ -141,7 +284,7 @@ public final class TargetSelector { * @param context Mixin context * @return remapped name or original name */ - public static String parseName(String name, IMixinContext context) { + public static String parseName(String name, ISelectorContext context) { ITargetSelector selector = TargetSelector.parse(name, context); if (!(selector instanceof ITargetSelectorByName)) { return name; @@ -150,10 +293,6 @@ public final class TargetSelector { return mappedName != null ? mappedName : name; } - private static ITargetSelector parse(String input, IReferenceMapper refMapper, String mixinClass) { - return MemberInfo.parse(input, refMapper, mixinClass); - } - /** * Run query on supplied target nodes * diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java new file mode 100644 index 00000000..70f6d2b3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java @@ -0,0 +1,57 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.dynamic; + +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; + +/** + * Base class for dynamic selectors, just to reduce some boilerplate + */ +public abstract class DynamicSelectorAbstract implements ITargetSelectorDynamic { + + @Override + public ITargetSelector configure(String... args) { + return this; + } + + @Override + public ITargetSelector validate() throws InvalidSelectorException { + return this; + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMatchCount() { + return Integer.MAX_VALUE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 646e6f73..e94cf747 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -300,7 +300,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC Set selectors = new LinkedHashSet(); for (String method : methods) { try { - selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin)); + selectors.add(TargetSelector.parseAndValidate(method, this).attach(this)); } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus())); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java new file mode 100644 index 00000000..1228ad64 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java @@ -0,0 +1,88 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.util.Bytecode; + +/** + * Specialised SelectorAnnotationContext for injection points + */ +public class InjectionPointAnnotationContext extends SelectorAnnotationContext implements IInjectionPointContext { + + /** + * Parent context + */ + private IInjectionPointContext parentContext; + + public InjectionPointAnnotationContext(IInjectionPointContext parent, Object selectorAnnotation, String selectorCoordinate) { + super(parent, selectorAnnotation, selectorCoordinate); + this.parentContext = parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.util.IMessageSink + * #addMessage(java.lang.String, java.lang.Object[]) + */ + @Override + public void addMessage(String format, Object... args) { + this.parentContext.addMessage(format, args); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getMethod() + */ + @Override + public MethodNode getMethod() { + return this.parentContext.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getAnnotation() + */ + @Override + public AnnotationNode getAnnotation() { + return this.parentContext.getAnnotation(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getSelectorAnnotation() + */ + @Override + public AnnotationNode getSelectorAnnotation() { + return (AnnotationNode)super.getSelectorAnnotation(); + } + + @Override + public String toString() { + return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()), this.getSelectorCoordinate()); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index f970537e..edded14b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -39,6 +39,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -174,10 +175,17 @@ public class InjectionPointData { } /** - * Get the context + * Get the injection point context */ - public IMixinContext getContext() { - return this.context.getContext(); + public IInjectionPointContext getContext() { + return this.context; + } + + /** + * Get the mixin context + */ + public IMixinContext getMixin() { + return this.context.getMixin(); } /** @@ -258,9 +266,9 @@ public class InjectionPointData { */ public ITargetSelector get(String key) { try { - return TargetSelector.parseAndValidate(this.get(key, ""), this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s", + return TargetSelector.parseAndValidate(this.get(key, ""), this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").%s \"%s\" on %s", this.at, key, this.target, this.getDescription()); } } @@ -270,9 +278,9 @@ public class InjectionPointData { */ public ITargetSelector getTarget() { try { - return TargetSelector.parseAndValidate(this.target, this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").target descriptor \"%s\" on %s", + return TargetSelector.parseAndValidate(this.target, this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").target \"%s\" on %s", this.at, this.target, this.getDescription()); } } @@ -281,7 +289,7 @@ public class InjectionPointData { * Get a description of this injector for use in error messages */ public String getDescription() { - return InjectionInfo.describeInjector(this.getContext(), this.getParent(), this.getMethod()); + return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotation(), this.context.getMethod()); } /** @@ -340,7 +348,7 @@ public class InjectionPointData { } private static Pattern createPattern() { - return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values()))); + return Pattern.compile(String.format("^(.+?)(:(%s))?$", Joiner.on('|').join(Selector.values()))); } /** @@ -359,7 +367,7 @@ public class InjectionPointData { } private static Selector parseSelector(Matcher matcher) { - return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT; + return matcher.matches() && matcher.group(3) != null ? Selector.valueOf(matcher.group(3)) : Selector.DEFAULT; } private static int parseInt(String string, int defaultValue) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index e4a932fb..37df0ee0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -28,14 +28,13 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; -import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; @@ -630,8 +629,8 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * #attach(org.spongepowered.asm.mixin.refmap.IMixinContext) */ @Override - public ITargetSelector attach(IMixinContext context) throws InvalidSelectorException { - if (this.owner != null && !this.owner.equals(context.getTargetClassRef())) { + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + if (this.owner != null && !this.owner.equals(context.getMixin().getTargetClassRef())) { throw new TargetNotSupportedException(this.owner); } return this; @@ -679,17 +678,16 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * Parse a MemberInfo from a string * * @param input String to parse MemberInfo from - * @param refMapper Reference mapper to use - * @param className Class context to use for remapping + * @param context Selector context for this parse request * @return parsed MemberInfo */ - public static MemberInfo parse(String input, IReferenceMapper refMapper, String className) { + public static MemberInfo parse(String input, ISelectorContext context) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); - if (refMapper != null) { - name = refMapper.remap(className, name); + if (context != null) { + name = context.remap(name); } int lastDotPos = name.lastIndexOf('.'); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java new file mode 100644 index 00000000..229658f6 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java @@ -0,0 +1,267 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.MatchResult; +import org.spongepowered.asm.util.asm.ElementNode; + +/** + * A {@link ITargetSelector Target Selector} which matches an element of + * candidate members using a regular expression. This selector is not remappable + * and is not suitable for use in obfuscated environments. + * + *

Regular expressions for this selector should be enclosed in / as + * a delimiter character, and \ characters must be escaped per normal + * Java conventions (eg. use \\s instead of \s since the + * backslash must be escaped). Forward slash (/) characters in the + * regex must be escaped as well to avoid being consumed as ending delimiters. + *

+ * + *

By default the regex match is performed against the name of the + * candidate, to specify matching against owner or desc, each + * pattern should be prefixed with owner= or desc= outside + * the delimiting /. + * + *

Some examples:

+ *
+ *   // Matches candidates starting with "foo"
+ *   /^foo/
+ *   
+ *   // Matches candidates ending with "Bar" and which take a single integer
+ *   /bar$/ desc=/^\\(I\\)/
+ *   
+ *   // The same example but with "name" explicitly specified (optional)
+ *   name=/bar$/ desc=/^\\(I\\)/
+ *   
+ *   // Matches candidates whose name contains "Entity"
+ *   /Entity/
+ *   
+ *   // Matches candidates whose owner contains "/google/", note the escaping of
+ *   // the forward slash symbols
+ *   owner=/\\/google\\//
+ *
+ * + *

The owner, name and desc expressions can be + * provided in any order.

+ */ +public final class MemberMatcher implements ITargetSelector { + + /** + * Regex selector, searches for targets using supplied regular expression + */ + private static final Pattern PATTERN = Pattern.compile("((owner|name|desc)\\s*=\\s*)?/(.*?)(? MatchResult match(ElementNode node) { + return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #matches(org.objectweb.asm.tree.AbstractInsnNode) + */ + @Override + public MatchResult match(AbstractInsnNode insn) { + if (insn instanceof MethodInsnNode) { + MethodInsnNode method = (MethodInsnNode)insn; + return this.matches(method.owner, method.name, method.desc); + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode field = (FieldInsnNode)insn; + return this.matches(field.owner, field.name, field.desc); + } + return MatchResult.NONE; + } + + private MatchResult matches(String... args) { + MatchResult result = MatchResult.NONE; +// boolean exactOnly = true; + + for (int i = 0; i < this.patterns.length; i++) { + if (this.patterns[i] == null || args[i] == null) { + continue; + } + + if (this.patterns[i].matcher(args[i]).find()) { +// String pattern = this.patterns[i].pattern(); +// if (pattern.startsWith("^") && pattern.endsWith("$") && exactOnly) { + result = MatchResult.EXACT_MATCH; +// } else { +// result = MatchResult.EXACT_MATCH; +// exactOnly = false; +// } + } else { + result = MatchResult.NONE; + } + } + + return result; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java index 818b76ef..ad184f18 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -70,7 +70,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo { Type returnType = Type.getReturnType(this.method.desc); for (AnnotationNode at : ats) { - this.injectionPoints.add(new BeforeConstant(this.getContext(), at, returnType.getDescriptor())); + this.injectionPoints.add(new BeforeConstant(this.getMixin(), at, returnType.getDescriptor())); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java new file mode 100644 index 00000000..3d1d2f8f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java @@ -0,0 +1,130 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.refmap.IMixinContext; + +/** + * Narrowed context for selectors in annotations which are themselves inside + * a parent annotation, for example @At annotations within a parent + * @Inject annotation. + */ +public class SelectorAnnotationContext implements ISelectorContext { + + /** + * The selector context of the parent, eg. the @Inject context + */ + private final ISelectorContext parent; + + /** + * The annotation for this selector + */ + private final Object selectorAnnotation; + + /** + * The coordinate for this selector + */ + private final String selectorCoordinate; + + /** + * Create a specialised context for a child annotation + * + * @param parent Parent selector context, eg. context of the outer element + * such as @Inject + * @param selectorAnnotation Annotation for this selector, eg. @At + * @param selectorCoordinate Coordinate for this selector + */ + public SelectorAnnotationContext(ISelectorContext parent, Object selectorAnnotation, String selectorCoordinate) { + this.parent = parent; + this.selectorAnnotation = selectorAnnotation; + this.selectorCoordinate = selectorCoordinate; + } + + /** + * Get the parent of this selector, must not return null + * + * @return parent context + */ + @Override + public ISelectorContext getParent() { + return this.parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMixin() + */ + @Override + public IMixinContext getMixin() { + return this.parent.getMixin(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMethod() + */ + @Override + public Object getMethod() { + return this.parent.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getAnnotation() + */ + @Override + public Object getAnnotation() { + return this.parent.getAnnotation(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorAnnotation() + */ + @Override + public Object getSelectorAnnotation() { + return this.selectorAnnotation; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorCoordinate() + */ + @Override + public String getSelectorCoordinate() { + return this.selectorCoordinate; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #remap(java.lang.String) + */ + @Override + public String remap(String reference) { + return this.parent.remap(reference); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java index b80ddb07..5131e261 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java @@ -50,12 +50,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message) { - super(info.getContext(), message); + super(info.getMixin(), message); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) { - super(info.getContext(), message, activityContext); + super(info.getMixin(), message, activityContext); this.info = info; } @@ -70,12 +70,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, Throwable cause) { - super(info.getContext(), cause); + super(info.getMixin(), cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), cause, activityContext); + super(info.getMixin(), cause, activityContext); this.info = info; } @@ -90,12 +90,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) { - super(info.getContext(), message, cause); + super(info.getMixin(), message, cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), message, cause, activityContext); + super(info.getMixin(), message, cause, activityContext); this.info = info; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java index 85eae4d2..2fe9e2ac 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java @@ -40,7 +40,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message) { - super(owner.getContext(), message); + super(owner.getMixin(), message); } public InvalidSliceException(IMixinContext context, Throwable cause) { @@ -48,7 +48,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, Throwable cause) { - super(owner.getContext(), cause); + super(owner.getMixin(), cause); } public InvalidSliceException(IMixinContext context, String message, Throwable cause) { @@ -56,7 +56,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message, Throwable cause) { - super(owner.getContext(), message, cause); + super(owner.getMixin(), message, cause); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index e60da758..07aba734 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -30,7 +30,9 @@ import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.util.logging.MessageRouter; /** @@ -58,6 +60,24 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { this.method = method; this.annotation = annotation; } + + @Override + public String remap(String reference) { + if (this.context != null) { + IReferenceMapper referenceMapper = this.context.getReferenceMapper(); + return referenceMapper != null ? referenceMapper.remap(this.context.getClassName(), reference) : reference; + } + return reference; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getParent() + */ + @Override + public ISelectorContext getParent() { + return null; + } /** * Get the mixin target context for this annotated method @@ -65,7 +85,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return the target context */ @Override - public final IMixinContext getContext() { + public final IMixinContext getMixin() { return this.context; } @@ -80,15 +100,36 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { } /** - * Get the annotation which this InjectionInfo was created from + * Get the primary annotation which makes this method special * - * @return The annotation which this InjectionInfo was created from + * @return The primary method annotation */ @Override public final AnnotationNode getAnnotation() { return this.annotation; } + /** + * Get the annotation context for selectors operating in the context of this + * method. + * + * @return The selector context annotation + */ + @Override + public AnnotationNode getSelectorAnnotation() { + return this.annotation; + } + + /** + * Get the selector coordinate for this method + * + * @return The selector context annotation + */ + @Override + public String getSelectorCoordinate() { + return "method"; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.IInjectionPointContext * #addMessage(java.lang.String, java.lang.Object[]) 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 b178d87c..e1edf045 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -46,6 +46,8 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.mixin.refmap.RemappingReferenceMapper; @@ -76,9 +78,15 @@ final class MixinConfig implements Comparable, IMixinConfig { @SerializedName("defaultGroup") String defaultGroup = "default"; + @SerializedName("namespace") + String namespace; + @SerializedName("injectionPoints") List injectionPoints; + @SerializedName("dynamicSelectors") + List dynamicSelectors; + @SerializedName("maxShiftBy") int maxShiftBy = InjectionPoint.DEFAULT_ALLOWED_SHIFT_BY; @@ -459,7 +467,7 @@ final class MixinConfig implements Comparable, IMixinConfig { this.initialised = true; this.initCompatibilityLevel(); - this.initInjectionPoints(); + this.initExtensions(); return this.checkVersion(); } @@ -514,46 +522,68 @@ final class MixinConfig implements Comparable, IMixinConfig { return fallbackEnvironment; } - private void initInjectionPoints() { - if (this.injectorOptions.injectionPoints == null) { - return; + private void initExtensions() { + if (this.injectorOptions.injectionPoints != null) { + for (String injectionPointClassName : this.injectorOptions.injectionPoints) { + this.initInjectionPoint(injectionPointClassName, this.injectorOptions.namespace); + } } - for (String injectionPointClassName : this.injectorOptions.injectionPoints) { - this.initInjectionPoint(injectionPointClassName); + if (this.injectorOptions.dynamicSelectors != null) { + for (String dynamicSelectorClassName : this.injectorOptions.dynamicSelectors) { + this.initDynamicSelector(dynamicSelectorClassName, this.injectorOptions.namespace); + } } } @SuppressWarnings("unchecked") - public void initInjectionPoint(String className) { + private void initInjectionPoint(String className, String namespace) { try { - Class injectionPointClass = null; - try { - injectionPointClass = this.service.getClassProvider().findClass(className, true); - } catch (ClassNotFoundException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the specified class was not found", className, this, cnfe); - return; + Class injectionPointClass = this.findExtensionClass(className, InjectionPoint.class, "injection point"); + if (injectionPointClass != null) { + try { + injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); + } catch (NoSuchMethodException cnfe) { + this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", + className, this, cnfe); + return; + } + + InjectionPoint.register((Class)injectionPointClass, namespace); } - - if (!InjectionPoint.class.isAssignableFrom(injectionPointClass)) { - this.logger.error("Unable to register injection point {} for {}, class must extend InjectionPoint", className, this); - return; - } - - try { - injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); - } catch (NoSuchMethodException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", - className, this, cnfe); - return; - } - - InjectionPoint.register((Class)injectionPointClass); } catch (Throwable th) { this.logger.catching(th); } } + @SuppressWarnings("unchecked") + private void initDynamicSelector(String className, String namespace) { + try { + Class dynamicSelectorClass = this.findExtensionClass(className, ITargetSelectorDynamic.class, "dynamic selector"); + if (dynamicSelectorClass != null) { + TargetSelector.register((Class)dynamicSelectorClass, namespace); + } + } catch (Throwable th) { + this.logger.catching(th); + } + } + + private Class findExtensionClass(String className, Class superType, String extensionType) { + Class extensionClass = null; + try { + extensionClass = this.service.getClassProvider().findClass(className, true); + } catch (ClassNotFoundException cnfe) { + this.logger.error("Unable to register {} {} for {}, the specified class was not found", extensionType, className, this, cnfe); + return null; + } + + if (!superType.isAssignableFrom(extensionClass)) { + this.logger.error("Unable to register {} {} for {}, class is not assignable to {}", extensionType, className, this, superType); + return null; + } + return extensionClass; + } + private boolean checkVersion() throws MixinInitialisationError { if (this.version == null) { // If the parent is non-null, then the version check has already been diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index e3cb05d8..f57974a6 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -171,7 +171,11 @@ public final class Locals { for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (storeInsn != null) { - frame[storeInsn.var] = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + frame[storeInsn.var] = storedLocal; + if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && Type.getType(storedLocal.desc).getSize() == 2) { + frame[storeInsn.var + 1] = null; // TOP + } storeInsn = null; } diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java new file mode 100644 index 00000000..15348b4c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -0,0 +1,38 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.asm; + +/** + * Interface for annotation handle since main classes may need to read info from + * mirror annotations in the AP + */ +public interface IAnnotationHandle { + + /** + * Get the annotation descriptor + */ + public abstract String getDesc(); + +} From dc3b91512b70bad40aab74de41769f24a79c6883 Mon Sep 17 00:00:00 2001 From: LexManos Date: Sun, 8 Nov 2020 16:31:31 -0800 Subject: [PATCH 10/42] Introduce refMap Wappers --- .../asm/mixin/transformer/MixinConfig.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) 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 e1edf045..aba18c40 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.transformer; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.Constructor; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -284,6 +285,16 @@ final class MixinConfig implements Comparable, IMixinConfig { */ @SerializedName("refmap") private String refMapperConfig; + + /** + * The class name for an implementation of {@Link IReferenceMapper}, mixinPackage will be prepended. + * This allows for full control over the refmap for cases where you need more fine-grained + * control then the default remappers. + * + * Must have a public constructor that takes {@Link MixinEnvironment} and {@Link IReferenceMapper} + */ + @SerializedName("refmapWrapper") + private String refMapperWrapper; /** * True to output "mixing in" messages at INFO level rather than DEBUG @@ -652,6 +663,22 @@ final class MixinConfig implements Comparable, IMixinConfig { if (this.env.getOption(Option.REFMAP_REMAP)) { this.refMapper = RemappingReferenceMapper.of(this.env, this.refMapper); } + + if (this.refMapperWrapper != null) { + String wrapperName = this.mixinPackage + this.refMapperWrapper; + try { + @SuppressWarnings("unchecked") + Class wrapperCls = (Class) Class.forName(wrapperName); + Constructor ctr = wrapperCls.getConstructor(MixinEnvironment.class, IReferenceMapper.class); + this.refMapper = ctr.newInstance(this.env, this.refMapper); + } catch (ClassNotFoundException e) { + this.logger.error("Reference map wrapper '{}' could not be found: ", wrapperName, e); + } catch (ReflectiveOperationException e) { + this.logger.error("Reference map wrapper '{}' could not be created: ", wrapperName, e); + } catch (SecurityException e) { + this.logger.error("Reference map wrapper '{}' could not be created: ", wrapperName, e); + } + } } /** From 2ef2417de6bcf5e16a57750bb6dea9289347aa68 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 23 Jan 2020 21:33:14 +0000 Subject: [PATCH 11/42] Fix formatting in MixinConfig --- .../asm/mixin/transformer/MixinConfig.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) 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 aba18c40..6a75f3ea 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -287,11 +287,13 @@ final class MixinConfig implements Comparable, IMixinConfig { private String refMapperConfig; /** - * The class name for an implementation of {@Link IReferenceMapper}, mixinPackage will be prepended. - * This allows for full control over the refmap for cases where you need more fine-grained - * control then the default remappers. + * The class name for an implementation of {@Link IReferenceMapper}, + * mixinPackage will be prepended. This allows for full control over the + * refmap for cases where you need more fine-grained control then the + * default remappers. * - * Must have a public constructor that takes {@Link MixinEnvironment} and {@Link IReferenceMapper} + *

Must have a public constructor that takes {@Link MixinEnvironment} and + * {@Link IReferenceMapper} */ @SerializedName("refmapWrapper") private String refMapperWrapper; @@ -665,7 +667,7 @@ final class MixinConfig implements Comparable, IMixinConfig { } if (this.refMapperWrapper != null) { - String wrapperName = this.mixinPackage + this.refMapperWrapper; + String wrapperName = this.mixinPackage + this.refMapperWrapper; try { @SuppressWarnings("unchecked") Class wrapperCls = (Class) Class.forName(wrapperName); From 6110084d0bc9404ebd085e91e23c17266dc2a5c7 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 28 Jan 2021 12:27:46 +0000 Subject: [PATCH 12/42] Fix for calculating Locals when target contains no stack map frames --- src/main/java/org/spongepowered/asm/util/Locals.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index e3cb05d8..f57974a6 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -171,7 +171,11 @@ public final class Locals { for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (storeInsn != null) { - frame[storeInsn.var] = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + frame[storeInsn.var] = storedLocal; + if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && Type.getType(storedLocal.desc).getSize() == 2) { + frame[storeInsn.var + 1] = null; // TOP + } storeInsn = null; } From 21881482ae7d088bda57c9dfe93da4068bc41970 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 31 Jan 2021 22:49:08 +0000 Subject: [PATCH 13/42] WIP but mostly working Desc selector functionality --- .../tools/obfuscation/AnnotatedMixin.java | 31 +- .../AnnotatedMixinElementHandler.java | 21 +- ...atedMixinElementHandlerSoftImplements.java | 7 +- .../obfuscation/mirror/AnnotationHandle.java | 31 +- .../spongepowered/asm/mixin/injection/At.java | 6 + .../asm/mixin/injection/Desc.java | 51 ++++ .../asm/mixin/injection/Descriptors.java | 45 +++ .../asm/mixin/injection/Inject.java | 10 +- .../asm/mixin/injection/ModifyArg.java | 10 +- .../asm/mixin/injection/ModifyArgs.java | 10 +- .../asm/mixin/injection/ModifyConstant.java | 10 +- .../asm/mixin/injection/ModifyVariable.java | 10 +- .../asm/mixin/injection/Redirect.java | 10 +- .../injection/selectors/ISelectorContext.java | 5 +- .../injection/selectors/TargetSelector.java | 8 +- .../selectors/dynamic/DescriptorResolver.java | 245 ++++++++++++++++ .../dynamic/DynamicSelectorDesc.java | 266 ++++++++++++++++++ .../mixin/injection/struct/InjectionInfo.java | 25 +- .../InjectionPointAnnotationContext.java | 3 +- .../injection/struct/InjectionPointData.java | 11 + .../struct/SelectorAnnotationContext.java | 2 +- .../asm/mixin/struct/AnnotatedMethodInfo.java | 11 +- .../asm/mixin/struct/SpecialMethodInfo.java | 1 + .../spongepowered/asm/util/Annotations.java | 86 ++++++ .../org/spongepowered/asm/util/Bytecode.java | 14 + .../asm/util/asm/IAnnotatedElement.java | 43 +++ .../asm/util/asm/IAnnotationHandle.java | 68 +++++ 27 files changed, 998 insertions(+), 42 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/Desc.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java create mode 100644 src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 5713f306..2143f37d 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -24,6 +24,7 @@ */ package org.spongepowered.tools.obfuscation; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -47,6 +48,8 @@ import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.mixin.transformer.ext.Extensions; +import org.spongepowered.asm.util.asm.IAnnotatedElement; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementAccessor; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementInvoker; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint; @@ -70,7 +73,7 @@ import com.google.common.base.Strings; /** * Information about a mixin stored during processing */ -class AnnotatedMixin implements IMixinContext { +class AnnotatedMixin implements IMixinContext, IAnnotatedElement { /** * Mixin annotation @@ -386,13 +389,13 @@ class AnnotatedMixin implements IMixinContext { AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap); this.injectors.registerInjector(injectorElement); - List ats = inject.getAnnotationList("at"); - for (AnnotationHandle at : ats) { - this.registerInjectionPoint(method, inject, "at", at, remap, "@At(%s)"); + List ats = inject.getAnnotationList("at"); + for (IAnnotationHandle at : ats) { + this.registerInjectionPoint(method, inject, "at", (AnnotationHandle)at, remap, "@At(%s)"); } - List slices = inject.getAnnotationList("slice"); - for (AnnotationHandle slice : slices) { + List slices = inject.getAnnotationList("slice"); + for (IAnnotationHandle slice : slices) { String id = slice.getValue("id", ""); String coord = "slice"; if (!Strings.isNullOrEmpty(id)) { @@ -400,14 +403,15 @@ class AnnotatedMixin implements IMixinContext { } SelectorAnnotationContext sliceContext = new SelectorAnnotationContext(injectorElement, slice, coord); - AnnotationHandle from = slice.getAnnotation("from"); + IAnnotationHandle from = slice.getAnnotation("from"); if (from != null) { - this.registerSliceInjectionPoint(method, inject, "from", from, remap, "@Slice[" + id + "](from=@At(%s))", sliceContext); + this.registerSliceInjectionPoint(method, inject, "from", (AnnotationHandle)from, remap, "@Slice[" + id + "](from=@At(%s))", + sliceContext); } - AnnotationHandle to = slice.getAnnotation("to"); + IAnnotationHandle to = slice.getAnnotation("to"); if (to != null) { - this.registerSliceInjectionPoint(method, inject, "to", to, remap, "@Slice[" + id + "](to=@At(%s))", sliceContext); + this.registerSliceInjectionPoint(method, inject, "to", (AnnotationHandle)to, remap, "@Slice[" + id + "](to=@At(%s))", sliceContext); } } } @@ -449,7 +453,7 @@ class AnnotatedMixin implements IMixinContext { @Override public String getTargetClassRef() { - throw new UnsupportedOperationException("Target class not available at compile time"); + return this.primaryTarget.getName(); } @Override @@ -476,5 +480,10 @@ class AnnotatedMixin implements IMixinContext { public Target getTargetMethod(MethodNode into) { throw new UnsupportedOperationException("Target not available at compile time"); } + + @Override + public IAnnotationHandle getAnnotation(Class annotationClass) { + return AnnotationHandle.of(this.mixin, annotationClass); + } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 433fba93..e571eadf 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -24,6 +24,7 @@ */ package org.spongepowered.tools.obfuscation; +import java.lang.annotation.Annotation; import java.util.List; import javax.annotation.processing.Messager; @@ -42,6 +43,8 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; +import org.spongepowered.asm.util.asm.IAnnotatedElement; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.asm.util.throwables.ConstraintViolationException; import org.spongepowered.asm.util.throwables.InvalidConstraintException; import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible; @@ -66,7 +69,7 @@ abstract class AnnotatedMixinElementHandler { * * @param type of inner element */ - abstract static class AnnotatedElement { + abstract static class AnnotatedElement implements IAnnotatedElement { protected final E element; @@ -104,6 +107,11 @@ abstract class AnnotatedMixinElementHandler { messager.printMessage(kind, msg, this.element, this.annotation.asMirror(), suppressedBy); } + @Override + public IAnnotationHandle getAnnotation(Class annotationClass) { + return AnnotationHandle.of(this.element, annotationClass); + } + } abstract static class AnnotatedElementExecutable extends AnnotatedElement implements ISelectorContext { @@ -130,7 +138,12 @@ abstract class AnnotatedMixinElementHandler { @Override public Object getMethod() { - return this.getElement(); + return new IAnnotatedElement() { + @Override + public IAnnotationHandle getAnnotation(Class annotationClass) { + return AnnotationHandle.of(AnnotatedElementExecutable.this.getElement(), annotationClass); + } + }; } @Override @@ -139,8 +152,8 @@ abstract class AnnotatedMixinElementHandler { } @Override - public String getSelectorCoordinate() { - return this.selectorCoordinate; + public String getSelectorCoordinate(boolean leaf) { + return leaf ? this.selectorCoordinate : TypeUtils.getName(this.element); } @Override diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java index 330494ed..c3c51553 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java @@ -33,6 +33,7 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.Interface.Remap; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.MethodHandle; @@ -63,7 +64,7 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl return; } - List interfaces = implementsAnnotation.getAnnotationList("value"); + List interfaces = implementsAnnotation.getAnnotationList("value"); // Derp? if (interfaces.size() < 1) { @@ -71,7 +72,7 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl return; } - for (AnnotationHandle interfaceAnnotation : interfaces) { + for (IAnnotationHandle interfaceAnnotation : interfaces) { Remap remap = interfaceAnnotation.getValue("remap", Remap.ALL); if (remap == Remap.NONE) { continue; @@ -83,7 +84,7 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl this.processSoftImplements(remap, iface, prefix); } catch (Exception ex) { this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), - this.mixin.getMixinElement(), interfaceAnnotation.asMirror()); + this.mixin.getMixinElement(), ((AnnotationHandle)interfaceAnnotation).asMirror()); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index 469226cf..63890786 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -28,6 +28,7 @@ import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.ListIterator; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; @@ -35,7 +36,9 @@ import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeMirror; +import org.objectweb.asm.Type; import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.collect.ImmutableList; @@ -109,6 +112,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * @return value or default if not set * @param duck type */ + @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T getValue(String key, T defaultValue) { if (this.annotation == null) { @@ -133,6 +137,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * @param duck type * @return value or null if not present or not set */ + @Override public T getValue() { return this.getValue("value", null); } @@ -145,6 +150,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * @param duck type * @return value or null if not present or not set */ + @Override public T getValue(String key) { return this.getValue(key, null); } @@ -167,7 +173,8 @@ public final class AnnotationHandle implements IAnnotationHandle { * @param key key to search for in the value map * @return value or null if not set */ - public AnnotationHandle getAnnotation(String key) { + @Override + public IAnnotationHandle getAnnotation(String key) { Object value = this.getValue(key); if (value instanceof AnnotationMirror) { return AnnotationHandle.of((AnnotationMirror)value); @@ -200,6 +207,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * @param list element duck type * @return list of values */ + @Override public List getList(String key) { List list = this.>getValue(key, Collections.emptyList()); return AnnotationHandle.unwrapAnnotationValueList(list); @@ -211,15 +219,16 @@ public final class AnnotationHandle implements IAnnotationHandle { * @param key key to fetch * @return list of annotations */ - public List getAnnotationList(String key) { + @Override + public List getAnnotationList(String key) { Object val = this.getValue(key, null); if (val == null) { - return Collections.emptyList(); + return Collections.emptyList(); } // Fix for JDT, single values are just returned as a bare AnnotationMirror if (val instanceof AnnotationMirror) { - return ImmutableList.of(AnnotationHandle.of((AnnotationMirror)val)); + return ImmutableList.of(AnnotationHandle.of((AnnotationMirror)val)); } @SuppressWarnings("unchecked") List list = (List)val; @@ -227,7 +236,19 @@ public final class AnnotationHandle implements IAnnotationHandle { for (AnnotationValue value : list) { annotations.add(new AnnotationHandle((AnnotationMirror)value.getValue())); } - return Collections.unmodifiableList(annotations); + return Collections.unmodifiableList(annotations); + } + + @Override + public List getTypeList(String key) { + List list = this.getList(key); + for (ListIterator iter = list.listIterator(); iter.hasNext();) { + Object next = iter.next(); + if (next instanceof TypeMirror) { + iter.set(Type.getType(TypeUtils.getInternalName((TypeMirror)next))); + } + } + return list; } protected AnnotationValue getAnnotationValue(String key) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 789843a5..6136d580 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -165,6 +165,12 @@ public @interface At { */ public String target() default ""; + /** + * Target descriptor used in place of string-based descriptors for + * {@link #target} + */ + public Desc desc() default @Desc(""); + /** * Ordinal offset. Many InjectionPoints will return every opcode matching * their criteria, specifying ordinal allows a particular opcode to diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java new file mode 100644 index 00000000..a61e809f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * TODO Javadoc + */ +@Target({ ElementType.TYPE, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +@Repeatable(Descriptors.class) +public @interface Desc { + + public String id() default ""; + + public Class owner() default Void.class; + + public String value(); + + public Class ret() default Void.class; + + public Class[] args() default { }; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java b/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java new file mode 100644 index 00000000..6bb3a8fc --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Collection type for {@link Desc} to allow {@link Repeatable} to work. + */ +@Target({ ElementType.TYPE, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Descriptors { + + /** + * Desc annotations for element + */ + Desc[] value(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index 1fcaf47a..d3122829 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -122,7 +122,15 @@ public @interface Inject { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * Array of {@link Slice} annotations which describe the method bisections diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index 645a60bf..fe9ffe82 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -80,7 +80,15 @@ public @interface ModifyArg { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * A {@link Slice} annotation which describes the method bisection used in diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java index 69018c32..bb702003 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java @@ -85,7 +85,15 @@ public @interface ModifyArgs { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * A {@link Slice} annotation which describes the method bisection used in diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java index 6e7ba332..9870a40e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -67,7 +67,15 @@ public @interface ModifyConstant { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * Array of {@link Slice} annotations which describe the method bisections diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 83acc4fe..d8f76088 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -79,7 +79,15 @@ public @interface ModifyVariable { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * A {@link Slice} annotation which describes the method bisection used in diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 6df4b87f..3bca4255 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -326,7 +326,15 @@ public @interface Redirect { * * @return target method(s) for this injector */ - public String[] method(); + public String[] method() default {}; + + /** + * Literal representation of one or more {@link Desc @Desc} annotations + * which identify the target methods. + * + * @return target method(s) for this injector as descriptors + */ + public Desc[] target() default {}; /** * A {@link Slice} annotation which describes the method bisection used in diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java index 9178198e..0652aa14 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java @@ -66,8 +66,11 @@ public interface ISelectorContext { * Get the coordinate for this selector. This is the local coordinate of the * selector without any parent parts. Parent parts are prepended by * consumers during the resolve process. + * + * @param leaf True if getting the coordinate when this element is a leaf, + * false if getting the coordinate when it is a parent */ - public abstract String getSelectorCoordinate(); + public abstract String getSelectorCoordinate(boolean leaf); /** * Remap a reference in the context of this selector, usually via the local diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index 39640c98..ccddc13a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -38,6 +38,7 @@ import java.util.regex.Pattern; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; @@ -140,6 +141,7 @@ public final class TargetSelector { throw (MixinException)cause; } Throwable ex = cause != null ? cause : itex; + ex.printStackTrace(); throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex); } } @@ -155,6 +157,10 @@ public final class TargetSelector { */ private static Map dynamicSelectors = new LinkedHashMap(); + static { + TargetSelector.registerBuiltIn(DynamicSelectorDesc.class); + } + private TargetSelector() { } @@ -265,7 +271,7 @@ public final class TargetSelector { } try { - return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)), context); + return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)).trim(), context); } catch (ReflectiveOperationException ex) { return new InvalidSelector(ex.getCause(), string); } catch (Exception ex) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java new file mode 100644 index 00000000..d7b18da0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -0,0 +1,245 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.dynamic; + +import java.lang.annotation.Annotation; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.Desc; +import org.spongepowered.asm.mixin.injection.Descriptors; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.asm.IAnnotatedElement; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +import com.google.common.base.Strings; + +/** + * Utility class which contains the logic for resolving descriptors + * ({@link Desc} annotations) starting from an element and recursing up the tree + * of parent elements looking for a matching descriptor + */ +public final class DescriptorResolver { + + /** + * Resolution result + */ + public static final class Result { + + /** + * The set of coordinates which were searched, stored here so they can + * be included in error messages if resolution fails + */ + private final Set searched; + + /** + * The resolved descriptor + */ + private final IAnnotationHandle desc; + + Result(Set searched, IAnnotationHandle desc) { + this.searched = searched; + this.desc = desc; + } + + /** + * True if the resolution process was successful + */ + public boolean isResolved() { + return this.desc != null; + } + + /** + * Gets the resolved descriptor annotation if successful, otherwise + * returns null + */ + public IAnnotationHandle getAnnotation() { + return this.desc; + } + + /** + * Gets the set of coordinates which were searched during resolution + */ + public Set getSearched() { + return this.searched; + } + + } + + // No + private DescriptorResolver() { + } + + /** + * Resolve the specified descriptor id starting at the specified context + * + * @param id Id to resolve, can be empty if resolving by coordinate + * @param context Selector context, usually from the source annotation + * @return Resolution result + */ + public static Result resolve(String id, ISelectorContext context) { + Set searched = new LinkedHashSet(); + if (!Strings.isNullOrEmpty(id)) { + searched.add(id); + } + return DescriptorResolver.resolve(id, context, searched, context.getSelectorCoordinate(true)); + } + + /** + * Recursive function which checks an element and then recurses to parent + */ + private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate) { + searched.add(coordinate); + + IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation()); + + // First check if there's a "desc" value on the current annotation + Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, annotation.getAnnotationList("desc")); + if (resolved != null) { + return resolved; + } + + // Next check with the current coordinates on the owning method + resolved = DescriptorResolver.resolve(id, context, searched, coordinate, context.getMethod()); + if (resolved != null) { + return resolved; + } + + ISelectorContext root = DescriptorResolver.getRoot(context); + String rootCoordinate = root.getSelectorCoordinate(false); + String mixinCoordinate = !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate; + + // Next check with the current coordinates on the mixin + resolved = DescriptorResolver.resolve(id, context, searched, mixinCoordinate, context.getMixin()); + if (resolved != null) { + return resolved; + } + + // Otherwise compute the parent coordinates and then recurse into the parent + ISelectorContext parent = context.getParent(); + if (parent != null) { + String parentCoordinate = parent.getSelectorCoordinate(false) + "." + coordinate; + return DescriptorResolver.resolve(id, parent, searched, parentCoordinate); + } + + // If all else fails, return failure + return new Result(searched, null); + } + + /** + * Attempt to resolve on an element + */ + private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, Object element) { + searched.add(coordinate); + + IAnnotationHandle descriptors = DescriptorResolver.getVisibleAnnotation(element, Descriptors.class); + if (descriptors != null) { + Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptors.getAnnotationList("value")); + if (resolved != null) { + return resolved; + } + } + + IAnnotationHandle descriptor = DescriptorResolver.getVisibleAnnotation(element, Desc.class); + if (descriptor != null) { + Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptor); + if (resolved != null) { + return resolved; + } + } + + return null; + } + + /** + * Attempt resolution using annotations from a particular element + */ + private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, + List availableDescriptors) { + if (availableDescriptors != null) { + searched.add(coordinate); + for (IAnnotationHandle desc : availableDescriptors) { + Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, desc); + if (resolved != null) { + return resolved; + } + } + } + return null; + } + + /** + * Attempt resolution using an actual annotation + */ + private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, IAnnotationHandle desc) { + if (desc != null) { + String descriptorId = desc.getValue("id", coordinate); + boolean implicit = Strings.isNullOrEmpty(id); + if ((implicit && descriptorId.equalsIgnoreCase(coordinate)) || (!implicit && descriptorId.equalsIgnoreCase(id))) { + return new Result(searched, desc); + } + } + return null; + } + + /** + * Utility function, gets an annotation handle from the candidate elements + * we are able to process + * + * @param element Element to fetch annotations for + * @param annotationClass Annotation we're searching for + * @return Annotation handle or null if the source is null + * @throws IllegalStateException if element is of an unsupported type + */ + private static IAnnotationHandle getVisibleAnnotation(Object element, Class annotationClass) { + if (element instanceof MethodNode) { + return Annotations.handleOf(Annotations.getVisible((MethodNode)element, annotationClass)); + } else if (element instanceof ClassNode) { + return Annotations.handleOf(Annotations.getVisible((ClassNode)element, annotationClass)); + } else if (element instanceof MixinTargetContext) { + return Annotations.handleOf(Annotations.getVisible(((MixinTargetContext)element).getClassNode(), annotationClass)); + } else if (element instanceof IAnnotatedElement) { + return ((IAnnotatedElement)element).getAnnotation(annotationClass); + } else if (element == null) { + return null; + } + throw new IllegalStateException("Cannot read visible annotations from element with unknown type: " + element.getClass().getName()); + } + + private static ISelectorContext getRoot(ISelectorContext context) { + ISelectorContext parent = context.getParent(); + while (parent != null) { + context = parent; + parent = context.getParent(); + } + return context; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java new file mode 100644 index 00000000..9b05de8b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -0,0 +1,266 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.dynamic; + +import java.util.List; +import java.util.Set; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.Desc; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.MatchResult; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DescriptorResolver.Result; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +/** + * A {@link ITargetSelector Target Selector} which matches candidates using + * descriptors contained in {@link Desc} annotations. The descriptor annotations + * may be local, or may be applied to the method or even the owning mixin using + * user-specified ids, or implicit coordinates. + * + *

TODO complete javadoc

+ */ +@SelectorId("Desc") +public final class DynamicSelectorDesc extends DynamicSelectorAbstract { + + /** + * The input string, only stored if the descriptor is invalid so we can emit + * it in the error message + */ + private final String input; + + /** + * Searched coordinates, only stored if the descriptor is invalid so we can + * emit it in the error message + */ + private final Set searched; + + /** + * Resolved id + */ + private final String id; + + /** + * The owner specified in the resolved {@link Desc} annotation, or null if + * resolution failed + */ + private final Type owner; + + /** + * The name specified in the resolved {@link Desc} annotation, or null if + * resolution failed + */ + private final String name; + + /** + * The arguments specified in the resolved {@link Desc} annotation, or null + * if resolution failed + */ + private final Type[] args; + + /** + * The return type specified in the resolved {@link Desc} annotation, or + * null if resolution failed + */ + private final Type returnType; + + /** + * Method descriptor, used for matching against methods. Computed from + * argument types and return type + */ + private final String methodDesc; + + private DynamicSelectorDesc(String id, Type owner, String name, Type[] args, Type returnType) { + this(null, null, id, owner, name, args, returnType, Bytecode.getDescriptor(returnType, args)); + } + + private DynamicSelectorDesc(String input, Set searched) { + this(input, searched, null, null, null, null, null, null); + } + + private DynamicSelectorDesc(String input, Set searched, String id, Type owner, String name, Type[] args, Type returnType, String desc) { + this.input = input; + this.searched = searched; + this.id = id; + this.owner = owner; + this.name = name; + this.args = args; + this.returnType = returnType; + this.methodDesc = desc; + } + + /** + * Parse a descriptor selector from the supplied input. The input is treated + * as a descriptor id to be resolved, or if empty uses implicit coordinates + * from the selection context + * + * @param input ID string, can be empty + * @param context Selector context + * @return parsed selector + */ + public static DynamicSelectorDesc parse(String input, ISelectorContext context) { + Result result = DescriptorResolver.resolve(input, context); + if (!result.isResolved()) { + return new DynamicSelectorDesc(input, result.getSearched()); + } + return DynamicSelectorDesc.of(context, result.getAnnotation()); + } + + /** + * Resolve a descriptor selector from the supplied context only, implicit + * coordinates are used. + * + * @param context Selector context + * @return parsed selector + */ + public static DynamicSelectorDesc resolve(ISelectorContext context) { + Result result = DescriptorResolver.resolve("", context); + if (!result.isResolved()) { + return null; + } + return DynamicSelectorDesc.of(context, result.getAnnotation()); + } + + /** + * Convert the supplied annotation into a selector instance + * + * @param context Selector context + * @param desc Annotation to parse + * @return selector + */ + public static DynamicSelectorDesc of(ISelectorContext context, IAnnotationHandle desc) { + return DynamicSelectorDesc.of(context.getMixin(), desc); + } + + /** + * Convert the supplied annotation into a selector instance + * + * @param mixin Mixin context + * @param desc Annotation to parse + * @return selector + */ + public static DynamicSelectorDesc of(IMixinContext mixin, IAnnotationHandle desc) { + String id = desc.getValue("id", ""); + Type ownerClass = desc.getValue("owner", Type.VOID_TYPE); + Type owner = ownerClass == Type.VOID_TYPE ? Type.getObjectType(mixin.getTargetClassRef()) : ownerClass; + String name = desc.getValue(); + List args = desc.getTypeList("args"); + Type returnType = desc.getValue("ret", Type.VOID_TYPE); + return new DynamicSelectorDesc(id, owner, name, args.toArray(new Type[args.size()]), returnType); + } + + public String getId() { + return this.id; + } + + public Type getOwner() { + return this.owner; + } + + public String getName() { + return this.name; + } + + public Type[] getArgs() { + return this.args; + } + + public Type getReturnType() { + return this.returnType; + } + + @Override + public ITargetSelector validate() throws InvalidSelectorException { + if (this.input != null) { + String extra = this.input.length() == 0 ? " searched in " + this.searched : ""; + throw new InvalidSelectorException("Could not resolve @Desc(" + this.input + ")" + extra); + } + return this; + } + + @Override + public ITargetSelector next() { + return this; // Recurse + } + + @Override + public int getMatchCount() { + return 1; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.spongepowered.asm.util.asm.ElementNode) + */ + @Override + public MatchResult match(ElementNode node) { + if (node == null) { + return MatchResult.NONE; + } else if (node.isMethod()) { + return this.matches(node.getOwnerName(), node.getName(), node.getDesc(), this.methodDesc); + } else { + return this.matches(node.getOwnerName(), node.getName(), node.getDesc(), this.returnType.getInternalName()); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #matches(org.objectweb.asm.tree.AbstractInsnNode) + */ + @Override + public MatchResult match(AbstractInsnNode insn) { + if (insn instanceof MethodInsnNode) { + MethodInsnNode method = (MethodInsnNode)insn; + return this.matches(method.owner, method.name, method.desc, this.methodDesc); + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode field = (FieldInsnNode)insn; + return this.matches(field.owner, field.name, field.desc, this.returnType.getInternalName()); + } + return MatchResult.NONE; + } + + private MatchResult matches(String owner, String name, String desc, String compareWithDesc) { + if (!compareWithDesc.equals(desc)) { + return MatchResult.NONE; + } else if (!this.owner.getInternalName().equals(owner)) { + return MatchResult.NONE; + } else if (this.name.equals(name)) { + return MatchResult.EXACT_MATCH; + } else if (this.name.equalsIgnoreCase(name)) { + return MatchResult.MATCH; + } + return MatchResult.NONE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index e94cf747..9c4e0280 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -53,6 +53,7 @@ import org.spongepowered.asm.mixin.injection.code.MethodSlices; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -291,14 +292,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } protected Set parseTargets() { - List methods = Annotations.getValue(this.annotation, "method", false); - if (methods == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", - this.annotationType, this.methodName)); - } - Set selectors = new LinkedHashSet(); - for (String method : methods) { + + for (String method : Annotations.getValue(this.annotation, "method", false)) { try { selectors.add(TargetSelector.parseAndValidate(method, this).attach(this)); } catch (InvalidMemberDescriptorException ex) { @@ -314,6 +310,21 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC ex.getMessage())); } } + + for (AnnotationNode target : Annotations.getValue(this.annotation, "target", false)) { + try { + selectors.add(DynamicSelectorDesc.of(this.mixin, Annotations.handleOf(target)).validate()); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionException(this, + String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName, + ex.getMessage())); + } + } + + if (selectors.size() == 0) { + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'desc' to specify targets", + this.annotationType, this.methodName)); + } return selectors; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java index 1228ad64..66815fa8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java @@ -82,7 +82,8 @@ public class InjectionPointAnnotationContext extends SelectorAnnotationContext i @Override public String toString() { - return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()), this.getSelectorCoordinate()); + return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()), + this.getSelectorCoordinate(false)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index edded14b..80f95927 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -41,8 +41,10 @@ import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.IMessageSink; import com.google.common.base.Joiner; @@ -278,6 +280,15 @@ public class InjectionPointData { */ public ITargetSelector getTarget() { try { + if (Strings.isNullOrEmpty(this.target)) { + AnnotationNode desc = Annotations.getValue(this.context.getSelectorAnnotation(), "desc"); + if (desc != null) { + String id = Annotations.getValue(desc, "id", "at"); + if ("at".equalsIgnoreCase(id)) { + return DynamicSelectorDesc.of(this.context, Annotations.handleOf(desc)); + } + } + } return TargetSelector.parseAndValidate(this.target, this.context); } catch (InvalidSelectorException ex) { throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").target \"%s\" on %s", diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java index 3d1d2f8f..ce959e8e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java @@ -114,7 +114,7 @@ public class SelectorAnnotationContext implements ISelectorContext { * #getSelectorCoordinate() */ @Override - public String getSelectorCoordinate() { + public String getSelectorCoordinate(boolean leaf) { return this.selectorCoordinate; } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index 07aba734..4ce05960 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -98,6 +98,13 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { public final MethodNode getMethod() { return this.method; } + + /** + * Get the original name of the method, if available + */ + public String getMethodName() { + return this.method.name; + } /** * Get the primary annotation which makes this method special @@ -126,8 +133,8 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return The selector context annotation */ @Override - public String getSelectorCoordinate() { - return "method"; + public String getSelectorCoordinate(boolean leaf) { + return leaf ? "method" : this.getMethodName().toLowerCase(); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java index 09344f69..181feffa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -84,6 +84,7 @@ public class SpecialMethodInfo extends AnnotatedMethodInfo { /** * Get the original name of the method, if available */ + @Override public String getMethodName() { return this.methodName; } diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index e50725f7..892317df 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -43,6 +43,7 @@ import org.spongepowered.asm.mixin.Debug; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.base.Function; import com.google.common.base.Preconditions; @@ -53,6 +54,73 @@ import com.google.common.collect.Lists; */ public final class Annotations { + /** + * Wrapper for AnnotationNode to support access via IAnnotationHandle + */ + public static class Handle implements IAnnotationHandle { + + private final AnnotationNode annotation; + + public Handle(AnnotationNode annotation) { + Preconditions.checkNotNull(annotation, "annotation"); + this.annotation = annotation; + } + + @Override + public String getDesc() { + return this.annotation.desc; + } + + @Override + public List getAnnotationList(String key) { + List value = Annotations.getValue(this.annotation, key, false); + List list = new ArrayList(); + if (value != null) { + for (AnnotationNode node : value) { + list.add(new Handle(node)); + } + } + return list; + } + + @Override + public List getTypeList(String key) { + return this.getList(key); + } + + @Override + public IAnnotationHandle getAnnotation(String key) { + AnnotationNode value = Annotations.getValue(this.annotation, key); + return value != null ? new Handle(value) : null; + } + + @Override + public T getValue(String key, T defaultValue) { + return Annotations.getValue(this.annotation, key, defaultValue); + } + + @Override + public T getValue() { + return this.getValue("value", null); + } + + @Override + public T getValue(String key) { + return this.getValue(key, null); + } + + @Override + public List getList(String key) { + return Annotations.getValue(this.annotation, key, false); + } + + @Override + public String toString() { + return "@" + Bytecode.getSimpleName(this.annotation); + } + + } + /** * Annotations which are eligible for merge via {@link #mergeAnnotations} */ @@ -70,6 +138,24 @@ public final class Annotations { private Annotations() { // Utility class } + + /** + * Get the supplied annotation object as an annotation handle + * + * @param annotation Annotation to return + * @return Wrapped or cast annotation + */ + public static IAnnotationHandle handleOf(Object annotation) { + if (annotation instanceof IAnnotationHandle) { + return (IAnnotationHandle)annotation; + } else if (annotation instanceof AnnotationNode) { + return new Annotations.Handle((AnnotationNode)annotation); + } else if (annotation == null) { + return null; + } else { + throw new IllegalArgumentException("Unsupported annotation type: " + annotation.getClass().getName()); + } + } /** * Set a runtime-visible annotation of the specified class on the supplied diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 0bc9e7a2..66f877b7 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -646,6 +646,20 @@ public final class Bytecode { } } + /** + * Get an array of Types from an array of classes. + * + * @param classes Array of classes to convert + * @return Array of types + */ + public static Type[] getTypes(Class... classes) { + Type[] types = new Type[classes.length]; + for (int index = 0; index < classes.length; index++) { + types[index] = Type.getType(classes[index]); + } + return types; + } + /** * Clones all of the labels in the source instruction list and returns the * clones in a map of old label -> new label. This is used to facilitate diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java new file mode 100644 index 00000000..0a450969 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java @@ -0,0 +1,43 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.asm; + +import java.lang.annotation.Annotation; + +/** + * Interface for objects which can be annotated since main classes may need to + * read info from mirror annotations in the AP + */ +public interface IAnnotatedElement { + + /** + * Get annotation from element + * + * @param annotationClass Annotation class to retrieve + * @return annotation handle + */ + public abstract IAnnotationHandle getAnnotation(Class annotationClass); + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java index 15348b4c..2695337c 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -24,6 +24,10 @@ */ package org.spongepowered.asm.util.asm; +import java.util.List; + +import org.objectweb.asm.Type; + /** * Interface for annotation handle since main classes may need to read info from * mirror annotations in the AP @@ -35,4 +39,68 @@ public interface IAnnotationHandle { */ public abstract String getDesc(); + /** + * Retrieve an annotation key as a list of annotation handles + * + * @param key key to fetch + * @return list of annotations + */ + public abstract List getAnnotationList(String key); + + /** + * Retrieve an annotation key as a list of annotation Types + * + * @param key key to fetch + * @return list of types + */ + public abstract List getTypeList(String key); + + /** + * Get an annotation value as an annotation handle + * + * @param key key to search for in the value map + * @return value or null if not set + */ + public abstract IAnnotationHandle getAnnotation(String key); + + /** + * Get a value with the specified key from this annotation, return the + * specified default value if the key is not set or is not present + * + * @param key key + * @param defaultValue value to return if the key is not set or not present + * @param duck type + * @return value or default if not set + */ + public abstract T getValue(String key, T defaultValue); + + /** + * Get the annotation value or return null if not present or not set + * + * @param duck type + * @return value or null if not present or not set + */ + public abstract T getValue(); + + /** + * Get the annotation value with the specified key or return null if not + * present or not set + * + * @param key key to fetch + * @param duck type + * @return value or null if not present or not set + */ + public abstract T getValue(String key); + + /** + * Retrieve the annotation value with the specified key as a list with + * values of the specified type. Returns an empty list if the value is not + * present or not set. + * + * @param key key to fetch + * @param list element duck type + * @return list of values + */ + public abstract List getList(String key); + } From f9aeec8b05fb97f1ceb63bd386dc3a011ee2ef2d Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 31 Jan 2021 22:50:01 +0000 Subject: [PATCH 14/42] Bump version to 0.8.3-SNAPSHOT --- build.gradle | 2 +- gradle.properties | 4 ++-- .../java/org/spongepowered/asm/launch/MixinBootstrap.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 1aa5f027..5024ef9a 100644 --- a/build.gradle +++ b/build.gradle @@ -55,7 +55,7 @@ repositories { maven { // For fernflower name = 'sponge' - url = 'http://repo.spongepowered.org/maven' + url = 'https://repo.spongepowered.org/maven' } maven { // For modlauncher diff --git a/gradle.properties b/gradle.properties index 02908621..efa97310 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,8 +4,8 @@ packaging=jar description=Mixin url=https://www.spongepowered.org organization=SpongePowered -buildVersion=0.8.2 -buildType=RELEASE +buildVersion=0.8.3 +buildType=SNAPSHOT asmVersion=7.2 legacyForgeAsmVersion=5.0.3 modlauncherAsmVersion=7.2 diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index d8be34b1..87067c65 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -61,7 +61,7 @@ public abstract class MixinBootstrap { /** * Subsystem version */ - public static final String VERSION = "0.8.2"; + public static final String VERSION = "0.8.3"; /** * Log all the things From ef6422f26e76d897d3da114fbace521ca22ee92d Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 3 Feb 2021 20:53:16 +0000 Subject: [PATCH 15/42] Flesh out Desc selector javadoc and functionality --- .../AnnotatedMixinElementHandler.java | 2 +- .../AnnotatedMixinElementHandlerAccessor.java | 2 +- .../AnnotatedMixinElementHandlerInjector.java | 3 +- ...atedMixinElementHandlerSoftImplements.java | 2 +- .../MixinObfuscationProcessor.java | 2 +- .../asm/launch/platform/MixinContainer.java | 3 +- .../asm/mixin/gen/AccessorGenerator.java | 2 +- .../asm/mixin/gen/AccessorInfo.java | 2 +- .../asm/mixin/injection/Desc.java | 69 +++++- .../injection/IInjectionPointContext.java | 9 +- .../asm/mixin/injection/InjectionPoint.java | 18 +- .../asm/mixin/injection/code/MethodSlice.java | 3 +- .../mixin/injection/code/MethodSlices.java | 2 +- .../injection/selectors/ISelectorContext.java | 5 +- .../injection/selectors/ITargetSelector.java | 11 +- .../{struct => selectors}/MemberMatcher.java | 22 +- .../injection/selectors/TargetSelector.java | 37 +-- .../selectors/dynamic/DescriptorResolver.java | 216 +++++++++++++++--- .../dynamic/DynamicSelectorDesc.java | 198 ++++++++++++---- .../dynamic/IResolvedDescriptor.java | 81 +++++++ .../mixin/injection/struct/InjectionInfo.java | 6 +- .../InjectionPointAnnotationContext.java | 32 +-- .../injection/struct/InjectionPointData.java | 11 +- .../struct/SelectorAnnotationContext.java | 9 +- .../asm/mixin/struct/AnnotatedMethodInfo.java | 22 +- .../asm/mixin/struct/SpecialMethodInfo.java | 4 +- .../transformer/MixinApplicatorStandard.java | 2 +- .../MixinPreProcessorStandard.java | 4 +- .../mixin/transformer/MixinTargetContext.java | 2 +- .../spongepowered/asm/util/Annotations.java | 32 ++- .../org/spongepowered/asm/util/Bytecode.java | 23 -- 31 files changed, 634 insertions(+), 202 deletions(-) rename src/main/java/org/spongepowered/asm/mixin/injection/{struct => selectors}/MemberMatcher.java (92%) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index e571eadf..0d715188 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -147,7 +147,7 @@ abstract class AnnotatedMixinElementHandler { } @Override - public Object getSelectorAnnotation() { + public IAnnotationHandle getSelectorAnnotation() { return this.getAnnotation(); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index e3e75e19..8f1b3af6 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -54,7 +54,7 @@ import com.google.common.base.Strings; /** * A module for {@link AnnotatedMixin} which handles accessors */ -public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler { +class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler { /** * Accessor element diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index fdd02a6c..6d88dda8 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -46,6 +46,7 @@ import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorExcep import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; import org.spongepowered.tools.obfuscation.ext.SpecialPackages; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; @@ -126,7 +127,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } @Override - public Object getSelectorAnnotation() { + public IAnnotationHandle getSelectorAnnotation() { return this.getAt(); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java index c3c51553..0efaef38 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java @@ -43,7 +43,7 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle; /** * A module for {@link AnnotatedMixin} whic handles soft-implements clauses */ -public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler { +class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler { AnnotatedMixinElementHandlerSoftImplements(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java index b19e6b07..44192441 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java @@ -40,7 +40,7 @@ import org.spongepowered.asm.mixin.Mixin; /** * Base class for mixin annotation processor modules */ -public abstract class MixinObfuscationProcessor extends AbstractProcessor { +abstract class MixinObfuscationProcessor extends AbstractProcessor { /** * Mixin info manager diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 4e6491ad..6477b329 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; +import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -79,7 +80,7 @@ public class MixinContainer { continue; } - MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(), this.handle); + MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(Locale.ROOT), this.handle); } catch (InstantiationException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java index deee0838..98d52d64 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -73,7 +73,7 @@ public abstract class AccessorGenerator { MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name, method.desc, null, null); accessor.visibleAnnotations = new ArrayList(); - accessor.visibleAnnotations.add(this.info.getAnnotation()); + accessor.visibleAnnotations.add(this.info.getAnnotationNode()); accessor.maxLocals = maxLocals; accessor.maxStack = maxStack; return accessor; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index 32dee538..225d544f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -461,7 +461,7 @@ public class AccessorInfo extends SpecialMethodInfo { @Override public String toString() { String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR"; - return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString, + return String.format("%s->@%s[%s]::%s%s", this.mixin, Annotations.getSimpleName(this.annotation), typeString, this.methodName, this.method.desc); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java index a61e809f..5a9613dd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -30,22 +30,85 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; + /** - * TODO Javadoc + *

A descriptor for matching a target element, for details of usage see + * {@link DynamicSelectorDesc}.

+ * + *

Unlike {@link MemberInfo Explicit Target Selectors} which can match any + * element of a candidate member, @Desc descriptors always match + * all elements of a target explicitly. Element defaults are as follows:

+ * + *
+ *
{@link #owner}
+ *
Defaults to the current target of the mixin if not specified
+ *
{@link #ret}
+ *
Defaults to void
+ *
{@link #args}
+ *
Defaults to an empty array matching a target with no arguments, + * omitting this value does not mean "match any" signature and + * will explicitly match targets with no arguments. This value is ignored + * for fields.
+ *
+ * + *

Notes

+ * + *
    + *
  • It should be noted that specifying the only required value + * ({@link #value}) will therefore match elements with owner type equal to the + * current mixin target, taking no arguments and returning void.
  • + * + *
  • Note that when matching fields the value of {@link #args} is ignored. + *
  • + *
*/ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Repeatable(Descriptors.class) public @interface Desc { + /** + * The identifier for this descriptor. Can be an implicit coordinate or a + * user-defined string. IDs are not case-sensitive but must be unique within + * a mixin or resolution scope. For more details on resolution for + * descriptors see {@link DynamicSelectorDesc}. + */ public String id() default ""; - public Class owner() default Void.class; + /** + * The owner of the member to match. The "owner" is the class which declares + * the member or, ocasionally the type of class upon which a virtual + * call is being made. For example if a class SuperType defines a + * method doSomething, usually owner will be + * SuperType. However note that where a method retrieves a + * reference to a derived type DerivedType which overrides + * doSomething, it's possible the invocation will be made using + * that type. To ensure usage of the correct type, inspect the disassembled + * bytecode for your target. + * + *

When owner is not specified, it defaults to the current + * target of the mixin.

+ */ + public Class owner() default void.class; + /** + * The name of the member to match. Must be specified. Matched + * case-sensitively against targets. + */ public String value(); - public Class ret() default Void.class; + /** + * The return type of a method to match, or the declared type of a field. + * Defaults to void. + */ + public Class ret() default void.class; + /** + * The argument types of a method to match, ignored for fields. Note that + * failing to specify this value matches a target with no arguments. + */ public Class[] args() default { }; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java index f13199f5..cb02eb59 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java @@ -44,13 +44,6 @@ public interface IInjectionPointContext extends IMessageSink, ISelectorContext { /** * Get the parent annotation (eg. the @Inject annotation) */ - @Override - public abstract AnnotationNode getAnnotation(); - - /** - * Get the selector annotation (eg. the @At annotation) - */ - @Override - public abstract AnnotationNode getSelectorAnnotation(); + public abstract AnnotationNode getAnnotationNode(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index e30de0af..171994c7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -38,6 +38,7 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; +import java.util.Locale; import java.util.Map; import org.apache.logging.log4j.LogManager; @@ -58,7 +59,6 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.IMessageSink; import com.google.common.base.Joiner; @@ -715,7 +715,7 @@ public abstract class InjectionPoint { @SuppressWarnings("unchecked") private static Class findClass(IMixinContext context, InjectionPointData data) { String type = data.getType(); - Class ipClass = InjectionPoint.types.get(type); + Class ipClass = InjectionPoint.types.get(type.toUpperCase(Locale.ROOT)); if (ipClass == null) { if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { try { @@ -761,7 +761,7 @@ public abstract class InjectionPoint { } else if (shift == At.Shift.AFTER) { return InjectionPoint.after(point); } else if (shift == At.Shift.BY) { - InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotation(), point, by); + InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotationNode(), point, by); return InjectionPoint.shift(point, by); } } @@ -793,7 +793,7 @@ public abstract class InjectionPoint { allowed = InjectionPoint.MAX_ALLOWED_SHIFT_BY; } - String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Bytecode.getSimpleName(parent), point, + String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Annotations.getSimpleName(parent), point, by, context, method.name, limitBreached, allowed, advice); if (err == ShiftByViolationBehaviour.WARN && allowed < InjectionPoint.MAX_ALLOWED_SHIFT_BY) { @@ -806,7 +806,7 @@ public abstract class InjectionPoint { protected String getAtCode() { AtCode code = this.getClass().getAnnotation(AtCode.class); - return code == null ? this.getClass().getName() : code.value(); + return code == null ? this.getClass().getName() : code.value().toUpperCase(); } /** @@ -846,9 +846,9 @@ public abstract class InjectionPoint { code.value(), type.getName()); } - String id = code.value(); + String id = code.value().toUpperCase(Locale.ROOT); if (!Strings.isNullOrEmpty(namespace)) { - id = namespace + ":" + code.value(); + id = namespace.toUpperCase(Locale.ROOT) + ":" + id; } InjectionPoint.types.put(id, type); @@ -861,7 +861,9 @@ public abstract class InjectionPoint { * @param type injection point type to register */ private static void registerBuiltIn(Class type) { - InjectionPoint.types.put(type.getAnnotation(AtCode.class).value(), type); + String code = type.getAnnotation(AtCode.class).value().toUpperCase(Locale.ROOT); + InjectionPoint.types.put(code, type); + InjectionPoint.types.put("MIXIN:" + code, type); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java index 9852b75a..4de644ca 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -44,7 +44,6 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationCont import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; import org.spongepowered.asm.util.Annotations; -import org.spongepowered.asm.util.Bytecode; import com.google.common.base.Strings; @@ -433,7 +432,7 @@ public final class MethodSlice { } private static String describeSlice(String description, ISliceContext owner) { - String annotation = Bytecode.getSimpleName(owner.getAnnotation()); + String annotation = Annotations.getSimpleName(owner.getAnnotationNode()); MethodNode method = owner.getMethod(); return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java index 3681ed5a..fb9979aa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java @@ -99,7 +99,7 @@ public final class MethodSlices { public static MethodSlices parse(InjectionInfo info) { MethodSlices slices = new MethodSlices(info); - AnnotationNode annotation = info.getAnnotation(); + AnnotationNode annotation = info.getAnnotationNode(); if (annotation != null) { for (AnnotationNode node : Annotations.getValue(annotation, "slice", true)) { MethodSlice slice = MethodSlice.parse(info, node); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java index 0652aa14..763bfee4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.asm.IAnnotationHandle; /** * Context passed to a {@link ITargetSelector Target Selector} in order to @@ -55,12 +56,12 @@ public interface ISelectorContext { * Get the root annotation for the selector, for example the injector or * accessor annotation */ - public abstract Object getAnnotation(); + public abstract IAnnotationHandle getAnnotation(); /** * Get the annotation for this selector, for example the @At annotation */ - public abstract Object getSelectorAnnotation(); + public abstract IAnnotationHandle getSelectorAnnotation(); /** * Get the coordinate for this selector. This is the local coordinate of the diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index d194324a..f385c897 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; import org.spongepowered.asm.util.asm.ElementNode; /** @@ -56,17 +55,17 @@ import org.spongepowered.asm.util.asm.ElementNode; * the selector string starts with "@":

* *
- *   // Built-in dynamic selector without argument string
+ *   // Built-in dynamic selector without argument string
  *   @SelectorId
  *   
- *   // Built-in dynamic selector with empty argument string
+ *   // Built-in dynamic selector with empty argument string
  *   @SelectorId()
  *   
- *   // Built-in dynamic selector with argument
+ *   // Built-in dynamic selector with argument
  *   @SelectorId(custom,argument,string,in,any,format)
  *   
- *   // User-provided dynamic selector with argument. Note that user-provided
- *   // dynamic selectors are namespaced to avoid conflicts.
+ *   // User-provided dynamic selector with argument. Note that
+ *   // user-provided dynamic selectors are namespaced to avoid conflicts.
  *   @Namespace:SelectorId(some arguments)
*
* diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java similarity index 92% rename from src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java rename to src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java index 229658f6..7700e855 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.injection.struct; +package org.spongepowered.asm.mixin.injection.selectors; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -31,10 +31,6 @@ import java.util.regex.PatternSyntaxException; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; -import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; -import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; -import org.spongepowered.asm.mixin.injection.selectors.MatchResult; import org.spongepowered.asm.util.asm.ElementNode; /** @@ -56,20 +52,20 @@ import org.spongepowered.asm.util.asm.ElementNode; * *

Some examples:

*
- *   // Matches candidates starting with "foo"
+ *   // Matches candidates starting with "foo"
  *   /^foo/
  *   
- *   // Matches candidates ending with "Bar" and which take a single integer
- *   /bar$/ desc=/^\\(I\\)/
+ *   // Matches candidates ending with "Bar" and which take a single int
+ *   /bar$/ desc=/^\\(I\\)/
  *   
- *   // The same example but with "name" explicitly specified (optional)
- *   name=/bar$/ desc=/^\\(I\\)/
+ *   // The same example but with "name" explicitly specified (optional)
+ *   name=/bar$/ desc=/^\\(I\\)/
  *   
- *   // Matches candidates whose name contains "Entity"
+ *   // Matches candidates whose name contains "Entity"
  *   /Entity/
  *   
- *   // Matches candidates whose owner contains "/google/", note the escaping of
- *   // the forward slash symbols
+ *   // Matches candidates whose owner contains "/google/", note the
+ *   // escaping of the forward slash symbols
  *   owner=/\\/google\\//
*
* diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index ccddc13a..c255a165 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -41,7 +41,6 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.Se import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.util.asm.ElementNode; @@ -141,16 +140,20 @@ public final class TargetSelector { throw (MixinException)cause; } Throwable ex = cause != null ? cause : itex; - ex.printStackTrace(); throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex); } } } + /** + * Regex for dynamic selector ids + */ + private static final String DYNAMIC_SELECTOR_ID = "[a-z]+(:[a-z]+)?"; + /** * Pattern for matching dynamic selectors */ - private static final Pattern PATTERN_DYNAMIC = Pattern.compile("^\\x40([a-z]+(:[a-z]+)?)(\\((.*)\\))?$", Pattern.CASE_INSENSITIVE); + private static final Pattern PATTERN_DYNAMIC = Pattern.compile("(?i)^\\x40(" + TargetSelector.DYNAMIC_SELECTOR_ID + ")(\\((.*)\\))?$"); /** * Registered dynamic selectors @@ -190,20 +193,27 @@ public final class TargetSelector { DynamicSelectorEntry entry; try { - entry = new DynamicSelectorEntry(namespace, selectorId.value().toLowerCase(Locale.ROOT), type); + entry = new DynamicSelectorEntry(namespace.toLowerCase(Locale.ROOT), selectorId.value().toLowerCase(Locale.ROOT), type); } catch (NoSuchMethodException ex) { throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); } - DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(entry.id); - if (existing != null) { // && !existing.type.equals(type)) { - MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)", - entry.id, type.getName(), existing.type.getName())); - } else { - MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s", - entry.id, type.getName())); + + String code = entry.getCode(); + if (!Pattern.matches(TargetSelector.DYNAMIC_SELECTOR_ID, code)) { + throw new IllegalArgumentException("Dynamic target selector class " + type + + " has an invalid id. Only alpha characters can be used in selector ids and namespaces"); } - TargetSelector.dynamicSelectors.put(entry.getCode(), entry); + DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(code); + if (existing != null) { // && !existing.type.equals(type)) { + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)", + code, type.getName(), existing.type.getName())); + } else { + MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s", + code, type.getName())); + } + + TargetSelector.dynamicSelectors.put(code, entry); } /** @@ -220,7 +230,8 @@ public final class TargetSelector { } catch (NoSuchMethodException ex) { throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); } - TargetSelector.dynamicSelectors.put(entry.getCode(), entry); + TargetSelector.dynamicSelectors.put(entry.id, entry); + TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java index d7b18da0..62dd7197 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -25,10 +25,12 @@ package org.spongepowered.asm.mixin.injection.selectors.dynamic; import java.lang.annotation.Annotation; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.Desc; @@ -36,9 +38,11 @@ import org.spongepowered.asm.mixin.injection.Descriptors; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.asm.IAnnotatedElement; import org.spongepowered.asm.util.asm.IAnnotationHandle; +import com.google.common.base.Joiner; import com.google.common.base.Strings; /** @@ -51,7 +55,7 @@ public final class DescriptorResolver { /** * Resolution result */ - public static final class Result { + static final class Descriptor implements IResolvedDescriptor { /** * The set of coordinates which were searched, stored here so they can @@ -59,43 +63,190 @@ public final class DescriptorResolver { */ private final Set searched; + /** + * Selector context + */ + private final ISelectorContext context; + /** * The resolved descriptor */ private final IAnnotationHandle desc; - Result(Set searched, IAnnotationHandle desc) { + Descriptor(Set searched, ISelectorContext context, IAnnotationHandle desc) { this.searched = searched; + this.context = context; this.desc = desc; } /** * True if the resolution process was successful */ + @Override public boolean isResolved() { return this.desc != null; } + /** + * Get information about the resolution of this descriptor, for + * inclusion in error messages when isResolved is false + * + */ + @Override + public String getResolutionInfo() { + if (this.searched == null) { + return ""; + } + return String.format("Searched coordinates [ \"%s\" ]", Joiner.on("\", \"").join(this.searched)); + } + /** * Gets the resolved descriptor annotation if successful, otherwise * returns null */ + @Override public IAnnotationHandle getAnnotation() { return this.desc; } - /** - * Gets the set of coordinates which were searched during resolution - */ - public Set getSearched() { - return this.searched; + @Override + public String getId() { + return this.desc != null ? this.desc.getValue("id", "") : ""; + } + + @Override + public Type getOwner() { + if (this.desc == null) { + return Type.VOID_TYPE; + } + Type ownerClass = this.desc.getValue("owner", Type.VOID_TYPE); + return ownerClass == Type.VOID_TYPE ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass; + } + + @Override + public String getName() { + if (this.desc == null) { + return ""; + } + String value = this.desc.getValue("value", ""); + if (!value.isEmpty()) { + return value; + } + return this.desc.getValue("name", ""); + } + + @Override + public Type[] getArgs() { + if (this.desc == null) { + return new Type[0]; + } + List args = this.desc.getTypeList("args"); + return args.toArray(new Type[args.size()]); + } + + @Override + public Type getReturnType() { + if (this.desc == null) { + return Type.VOID_TYPE; + } + return this.desc.getValue("ret", Type.VOID_TYPE); } } + /** + * Observer for the resolution process, used to support printing resolution + * path during debug or collecting resolution info for inclusion in error + * messages + */ + interface IResolverObserver { + + /** + * Called when the resolver visits a coordinate on the specified member + * + * @param coordinate coordinate being visited + * @param element element being visited + * @param detail diagnostic detail + */ + public abstract void visit(String coordinate, Object element, String detail); + + /** + * Get all of the searched coordinates, for inclusion in error messages + */ + public abstract Set getSearched(); + + /** + * Called after resolution completes + */ + public abstract void postResolve(); + + } + + /** + * Basic resolver observer which just collects searched coordinates + */ + static class ResolverObserverBasic implements IResolverObserver { + + private final Set searched = new LinkedHashSet(); + + @Override + public void visit(String coordinate, Object element, String detail) { + this.searched.add(coordinate); + } + + @Override + public Set getSearched() { + return this.searched; + } + + @Override + public void postResolve() { + } + + } + + /** + * Debug resolver observer which prints resolution debug info after + * resolution is complete + */ + static class ResolverObserverDebug extends ResolverObserverBasic { + + private final PrettyPrinter printer = new PrettyPrinter(); + + ResolverObserverDebug(ISelectorContext context) { + this.printer.add("Searching for implicit descriptor").add(context).hr().table(); + this.printer.tr("Context Coordinate:", context.getSelectorCoordinate(true) + " (" + context.getSelectorCoordinate(false) + ")"); + this.printer.tr("Selector Annotation:", context.getSelectorAnnotation()); + this.printer.tr("Root Annotation:", context.getAnnotation()); + this.printer.tr("Method:", context.getMethod()).hr(); + this.printer.table("Search Coordinate", "Search Element", "Detail").th().hr(); + } + + @Override + public void visit(String coordinate, Object element, String detail) { + super.visit(coordinate, element, detail); + this.printer.tr(coordinate, element, detail); + } + + @Override + public void postResolve() { + this.printer.print(); + } + + } + + /** + * Special ID used to instruct the resolver to print its progress. + */ + public static String PRINT_ID = "?"; + // No private DescriptorResolver() { } + + public static IResolvedDescriptor resolve(ISelectorContext context, IAnnotationHandle desc) { + return new Descriptor(Collections.emptySet(), context, desc); + } /** * Resolve the specified descriptor id starting at the specified context @@ -104,40 +255,48 @@ public final class DescriptorResolver { * @param context Selector context, usually from the source annotation * @return Resolution result */ - public static Result resolve(String id, ISelectorContext context) { - Set searched = new LinkedHashSet(); + public static IResolvedDescriptor resolve(String id, ISelectorContext context) { + IResolverObserver observer = new ResolverObserverBasic(); if (!Strings.isNullOrEmpty(id)) { - searched.add(id); + if (DescriptorResolver.PRINT_ID.equals(id)) { + observer = new ResolverObserverDebug(context); + id = ""; + } else { + observer.visit(id, "", ""); + } } - return DescriptorResolver.resolve(id, context, searched, context.getSelectorCoordinate(true)); + + IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true)); + observer.postResolve(); + return new Descriptor(observer.getSearched(), context, desc); } /** * Recursive function which checks an element and then recurses to parent */ - private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate) { - searched.add(coordinate); + private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate) { IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation()); + observer.visit(coordinate, annotation, annotation.toString() + ".desc"); // First check if there's a "desc" value on the current annotation - Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, annotation.getAnnotationList("desc")); + IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, annotation.getAnnotationList("desc")); if (resolved != null) { return resolved; } // Next check with the current coordinates on the owning method - resolved = DescriptorResolver.resolve(id, context, searched, coordinate, context.getMethod()); + resolved = DescriptorResolver.resolve(id, context, observer, coordinate, context.getMethod(), "method"); if (resolved != null) { return resolved; } ISelectorContext root = DescriptorResolver.getRoot(context); String rootCoordinate = root.getSelectorCoordinate(false); - String mixinCoordinate = !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate; + String mixinCoordinate = root != context && !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate; // Next check with the current coordinates on the mixin - resolved = DescriptorResolver.resolve(id, context, searched, mixinCoordinate, context.getMixin()); + resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin"); if (resolved != null) { return resolved; } @@ -146,22 +305,23 @@ public final class DescriptorResolver { ISelectorContext parent = context.getParent(); if (parent != null) { String parentCoordinate = parent.getSelectorCoordinate(false) + "." + coordinate; - return DescriptorResolver.resolve(id, parent, searched, parentCoordinate); + return DescriptorResolver.resolve(id, parent, observer, parentCoordinate); } // If all else fails, return failure - return new Result(searched, null); + return null; } /** * Attempt to resolve on an element */ - private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, Object element) { - searched.add(coordinate); + private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, Object element, + String detail) { + observer.visit(coordinate, element, detail); IAnnotationHandle descriptors = DescriptorResolver.getVisibleAnnotation(element, Descriptors.class); if (descriptors != null) { - Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptors.getAnnotationList("value")); + IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptors.getAnnotationList("value")); if (resolved != null) { return resolved; } @@ -169,7 +329,7 @@ public final class DescriptorResolver { IAnnotationHandle descriptor = DescriptorResolver.getVisibleAnnotation(element, Desc.class); if (descriptor != null) { - Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptor); + IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptor); if (resolved != null) { return resolved; } @@ -181,12 +341,11 @@ public final class DescriptorResolver { /** * Attempt resolution using annotations from a particular element */ - private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, + private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, List availableDescriptors) { if (availableDescriptors != null) { - searched.add(coordinate); for (IAnnotationHandle desc : availableDescriptors) { - Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, desc); + IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, desc); if (resolved != null) { return resolved; } @@ -198,12 +357,13 @@ public final class DescriptorResolver { /** * Attempt resolution using an actual annotation */ - private static Result resolve(String id, ISelectorContext context, Set searched, String coordinate, IAnnotationHandle desc) { + private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, + IAnnotationHandle desc) { if (desc != null) { String descriptorId = desc.getValue("id", coordinate); boolean implicit = Strings.isNullOrEmpty(id); if ((implicit && descriptorId.equalsIgnoreCase(coordinate)) || (!implicit && descriptorId.equalsIgnoreCase(id))) { - return new Result(searched, desc); + return desc; } } return null; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index 9b05de8b..ed773f26 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -24,47 +24,149 @@ */ package org.spongepowered.asm.mixin.injection.selectors.dynamic; -import java.util.List; -import java.util.Set; - import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Desc; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; -import org.spongepowered.asm.mixin.injection.selectors.dynamic.DescriptorResolver.Result; -import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.IAnnotationHandle; /** * A {@link ITargetSelector Target Selector} which matches candidates using - * descriptors contained in {@link Desc} annotations. The descriptor annotations - * may be local, or may be applied to the method or even the owning mixin using - * user-specified ids, or implicit coordinates. + * descriptors contained in {@link Desc @Desc} annotations. The descriptor + * annotations may be local, or may be applied to the method or even the owning + * mixin using user-specified ids, or implicit coordinates based on the relative + * location of the consumer. eg. an @At annotation and the @Desc + * annotation itself, which might be on a parent element for convenience. * - *

TODO complete javadoc

+ *

See {@link Desc @Desc} for the specific syntax of descriptor + * annotations.

+ * + *

Local Descriptors

+ * + *

Some annotations can use {@link Desc @Desc} selectors directly, + * namely {@link At @At} (specified in {@link At#desc @At.desc}) and + * all Injector annotations (specified in target - for example + * {@link Inject#target @Inject.target}). In these cases it is not + * necessary to specify an {@link Desc#id id} for the descriptor since the usage + * is inferred from context.

+ * + *

Resolved Descriptors

+ * + *

Descriptors can also be placed as annotations on the mixin method or the + * mixin class, thus allowing descriptors to be re-used by multiple consumers. + * For example where several injectors target the same method, the descriptor + * can be placed on the mixin itself and consumed by id. In this situation it is + * necessary to specify an {@link Desc#id id} for the descriptor and specify the + * chosen id as a selector string:

+ * + *
@Mixin(TargetClass.class)
+ * @Desc(id = "foo", value = "getFoo", args = { int.class }) + *
+ * abstract class MyMixin {
+ *
+ *     @Inject(target = "@Desc(foo)", at = + * @At("RETURN"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     }
+ *
+ * }
+ * + *

Note that the id string can be anything you wish, but is matched + * case-insensitively and must be non-empty, so feel free to be as descriptive + * as you wish.

+ * + *

Implicit coordinates

+ * + *

As an alternative to specifying an explicit descriptor id for + * descriptors, it is also possible to use implicit coordinates generated using + * the location of the consumer. To do so, use the selector "@Desc" + * with no arguments and give the descriptor an {@link Desc#id id} which + * corresponds to the coordinate of the consumer:

+ * + *

In this example, the coordinate of the {@link At @At} annotation, + * "at" is used as the descriptor id.

+ * + *
+ *     @Desc(id = "at", + * value = "theMethodName", args = { String.class }, ret = boolean.class)
+ *     @Inject(method = "targetMethod()V", at = + * @At(value = "INVOKE" target = "@Desc"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     } + *
+ * + *

As the resolver widens its search it adds new components to the start of + * the implicit coordinate which match the element, separated by dots. For + * example {@link At @At} annotations inside a {@link Slice @Slice} + * will first resolve as (local coordinate) from, followed by + * slice.from, and finally handlerMethodName.slice.from. This + * allows implicit coordinates to be used up to the mixin level as in the first + * example.

+ * + *
@Mixin(TargetClass.class)
+ * @Desc(id = "myHandlerMethod.at", value = "theMethodName", + * args = { String.class }, ret = boolean.class)
+ * @Desc(id = "myHandlerMethod.method", value = "getFoo", args = + * { int.class })
+ * abstract class MyMixin {
+ *
+ *     @Inject(method = "@Desc", at = @At(value = + * "INVOKE" target = "@Desc"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     } + *
+ * + *

To view the coordinates used to resolve the descriptor for a particular + * element, use the special id "?" in the selector:

+ * + *
+ *     @Inject(method = "@Desc", at = @At(value = + * "INVOKE" target = "@Desc(?)")) + *
+ *     void myHandlerMethod(int arg, CallbackInfo ci) { + *
+ * + *

This will cause the resolver to pretty-print the considered coordinates + * and elements into the console:

+ * + *
/*****************************************************/
+ */* Coordinate    Search Element       Detail         */
+ */*****************************************************/
+ */* at            @At                  @At.desc       */
+ */* at            myHandler            method         */
+ */* myhandler.at  mixins.json:MyMixin  mixin          */
+ */* myhandler.at  @Redirect            @Redirect.desc */
+ */* myhandler.at  myhandler            method         */
+ */*****************************************************/
+ *
+ * + *

Don't worry that some combinations of coordinate and element are not + * possible (for example there is no member desc on @At). + * The resolver doesn't know that and scans each visited element for members it + * supports.

*/ @SelectorId("Desc") public final class DynamicSelectorDesc extends DynamicSelectorAbstract { /** - * The input string, only stored if the descriptor is invalid so we can emit - * it in the error message + * Parser/resolver error mesage, only stored if the descriptor is invalid so + * we can emit it when {@link #validate} is called */ - private final String input; - - /** - * Searched coordinates, only stored if the descriptor is invalid so we can - * emit it in the error message - */ - private final Set searched; + private final InvalidSelectorException parseException; /** * Resolved id @@ -101,23 +203,23 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { */ private final String methodDesc; - private DynamicSelectorDesc(String id, Type owner, String name, Type[] args, Type returnType) { - this(null, null, id, owner, name, args, returnType, Bytecode.getDescriptor(returnType, args)); + private DynamicSelectorDesc(IResolvedDescriptor desc) { + this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType()); } - private DynamicSelectorDesc(String input, Set searched) { - this(input, searched, null, null, null, null, null, null); + private DynamicSelectorDesc(InvalidSelectorException ex) { + this(ex, null, null, null, null, null); } - private DynamicSelectorDesc(String input, Set searched, String id, Type owner, String name, Type[] args, Type returnType, String desc) { - this.input = input; - this.searched = searched; + private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType) { + this.parseException = ex; + this.id = id; this.owner = owner; this.name = name; this.args = args; this.returnType = returnType; - this.methodDesc = desc; + this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; } /** @@ -130,11 +232,13 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { * @return parsed selector */ public static DynamicSelectorDesc parse(String input, ISelectorContext context) { - Result result = DescriptorResolver.resolve(input, context); - if (!result.isResolved()) { - return new DynamicSelectorDesc(input, result.getSearched()); + IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context); + if (!descriptor.isResolved()) { + String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : ""; + InvalidSelectorException ex = new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra); + return new DynamicSelectorDesc(ex); } - return DynamicSelectorDesc.of(context, result.getAnnotation()); + return DynamicSelectorDesc.of(descriptor); } /** @@ -145,11 +249,11 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { * @return parsed selector */ public static DynamicSelectorDesc resolve(ISelectorContext context) { - Result result = DescriptorResolver.resolve("", context); - if (!result.isResolved()) { + IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context); + if (!descriptor.isResolved()) { return null; } - return DynamicSelectorDesc.of(context, result.getAnnotation()); + return DynamicSelectorDesc.of(descriptor); } /** @@ -160,24 +264,21 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { * @return selector */ public static DynamicSelectorDesc of(ISelectorContext context, IAnnotationHandle desc) { - return DynamicSelectorDesc.of(context.getMixin(), desc); + IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context); + if (!descriptor.isResolved()) { + return null; + } + return DynamicSelectorDesc.of(context, descriptor.getAnnotation()); } - + /** * Convert the supplied annotation into a selector instance * - * @param mixin Mixin context - * @param desc Annotation to parse + * @param desc Resolved descriptor * @return selector */ - public static DynamicSelectorDesc of(IMixinContext mixin, IAnnotationHandle desc) { - String id = desc.getValue("id", ""); - Type ownerClass = desc.getValue("owner", Type.VOID_TYPE); - Type owner = ownerClass == Type.VOID_TYPE ? Type.getObjectType(mixin.getTargetClassRef()) : ownerClass; - String name = desc.getValue(); - List args = desc.getTypeList("args"); - Type returnType = desc.getValue("ret", Type.VOID_TYPE); - return new DynamicSelectorDesc(id, owner, name, args.toArray(new Type[args.size()]), returnType); + public static DynamicSelectorDesc of(IResolvedDescriptor desc) { + return new DynamicSelectorDesc(desc); } public String getId() { @@ -202,9 +303,8 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { @Override public ITargetSelector validate() throws InvalidSelectorException { - if (this.input != null) { - String extra = this.input.length() == 0 ? " searched in " + this.searched : ""; - throw new InvalidSelectorException("Could not resolve @Desc(" + this.input + ")" + extra); + if (this.parseException != null) { + throw this.parseException; } return this; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java new file mode 100644 index 00000000..5b1bc5e9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java @@ -0,0 +1,81 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.dynamic; + +import org.objectweb.asm.Type; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +/** + * A resolved descriptor, or rather the result of resolving a descriptor. If the + * descriptor was not resolved then {@link #isResolved} returns false. + */ +public interface IResolvedDescriptor { + + /** + * Get whether the descriptor was successfully resolved + */ + public abstract boolean isResolved(); + + /** + * Get the resolved descriptor, or null if the descriptor was not resolved + */ + public abstract IAnnotationHandle getAnnotation(); + + /** + * Get information about the resolution process (eg. visited implicit + * coordinates) as a human-readable string for inclusion in error messages. + */ + public abstract String getResolutionInfo(); + + /** + * Get the ID of the resolved descriptor, should match the query + */ + public abstract String getId(); + + /** + * Get the owner from the resolved descriptor, returns void if the + * descriptor was not resolved. + */ + public abstract Type getOwner(); + + /** + * Get the name from the resolved descriptor, returns an empty string if the + * descriptor was not resolved. + */ + public abstract String getName(); + + /** + * Get the arguments from the resolved descriptor, returns an empty array if + * the descriptor was not resolved. + */ + public abstract Type[] getArgs(); + + /** + * Get the return type from the resolved descriptor, returns void + * if the descriptor was not resolved. + */ + public abstract Type getReturnType(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 9c4e0280..63ee06a7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -313,7 +313,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC for (AnnotationNode target : Annotations.getValue(this.annotation, "target", false)) { try { - selectors.add(DynamicSelectorDesc.of(this.mixin, Annotations.handleOf(target)).validate()); + selectors.add(DynamicSelectorDesc.of(this, Annotations.handleOf(target)).validate()); } catch (InvalidSelectorException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName, @@ -322,7 +322,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } if (selectors.size() == 0) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'desc' to specify targets", + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", this.annotationType, this.methodName)); } return selectors; @@ -680,7 +680,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) { - return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); + return String.format("%s->@%s::%s%s", mixin.toString(), Annotations.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java index 66815fa8..ff2fa85f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java @@ -27,7 +27,8 @@ package org.spongepowered.asm.mixin.injection.struct; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; -import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.asm.IAnnotationHandle; /** * Specialised SelectorAnnotationContext for injection points @@ -39,11 +40,16 @@ public class InjectionPointAnnotationContext extends SelectorAnnotationContext i */ private IInjectionPointContext parentContext; - public InjectionPointAnnotationContext(IInjectionPointContext parent, Object selectorAnnotation, String selectorCoordinate) { + public InjectionPointAnnotationContext(IInjectionPointContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) { super(parent, selectorAnnotation, selectorCoordinate); this.parentContext = parent; } + public InjectionPointAnnotationContext(IInjectionPointContext parent, AnnotationNode selectorAnnotation, String selectorCoordinate) { + super(parent, Annotations.handleOf(selectorAnnotation), selectorCoordinate); + this.parentContext = parent; + } + /* (non-Javadoc) * @see org.spongepowered.asm.util.IMessageSink * #addMessage(java.lang.String, java.lang.Object[]) @@ -62,27 +68,27 @@ public class InjectionPointAnnotationContext extends SelectorAnnotationContext i return this.parentContext.getMethod(); } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.IInjectionPointContext + * #getAnnotationNode() + */ + @Override + public AnnotationNode getAnnotationNode() { + return this.parentContext.getAnnotationNode(); + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.struct * .SelectorAnnotationContext#getAnnotation() */ @Override - public AnnotationNode getAnnotation() { + public IAnnotationHandle getAnnotation() { return this.parentContext.getAnnotation(); } - - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.struct - * .SelectorAnnotationContext#getSelectorAnnotation() - */ - @Override - public AnnotationNode getSelectorAnnotation() { - return (AnnotationNode)super.getSelectorAnnotation(); - } @Override public String toString() { - return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()), + return String.format("%s->%s(%s)", this.parentContext, this.getSelectorAnnotation(), this.getSelectorCoordinate(false)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index 80f95927..d7c620a3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -45,7 +45,9 @@ import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDe import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Annotations.Handle; import org.spongepowered.asm.util.IMessageSink; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.base.Joiner; import com.google.common.base.Strings; @@ -208,7 +210,7 @@ public class InjectionPointData { * Get the root annotation (eg. {@link Inject}) */ public AnnotationNode getParent() { - return this.context.getAnnotation(); + return this.context.getAnnotationNode(); } /** @@ -281,7 +283,8 @@ public class InjectionPointData { public ITargetSelector getTarget() { try { if (Strings.isNullOrEmpty(this.target)) { - AnnotationNode desc = Annotations.getValue(this.context.getSelectorAnnotation(), "desc"); + IAnnotationHandle selectorAnnotation = this.context.getSelectorAnnotation(); + AnnotationNode desc = Annotations.getValue(((Handle)selectorAnnotation).getNode(), "desc"); if (desc != null) { String id = Annotations.getValue(desc, "id", "at"); if ("at".equalsIgnoreCase(id)) { @@ -291,7 +294,7 @@ public class InjectionPointData { } return TargetSelector.parseAndValidate(this.target, this.context); } catch (InvalidSelectorException ex) { - throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").target \"%s\" on %s", + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed validating @At(\"%s\").target \"%s\" on %s", this.at, this.target, this.getDescription()); } } @@ -300,7 +303,7 @@ public class InjectionPointData { * Get a description of this injector for use in error messages */ public String getDescription() { - return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotation(), this.context.getMethod()); + return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotationNode(), this.context.getMethod()); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java index ce959e8e..605d0b08 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.struct; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.asm.IAnnotationHandle; /** * Narrowed context for selectors in annotations which are themselves inside @@ -42,7 +43,7 @@ public class SelectorAnnotationContext implements ISelectorContext { /** * The annotation for this selector */ - private final Object selectorAnnotation; + private final IAnnotationHandle selectorAnnotation; /** * The coordinate for this selector @@ -57,7 +58,7 @@ public class SelectorAnnotationContext implements ISelectorContext { * @param selectorAnnotation Annotation for this selector, eg. @At * @param selectorCoordinate Coordinate for this selector */ - public SelectorAnnotationContext(ISelectorContext parent, Object selectorAnnotation, String selectorCoordinate) { + public SelectorAnnotationContext(ISelectorContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) { this.parent = parent; this.selectorAnnotation = selectorAnnotation; this.selectorCoordinate = selectorCoordinate; @@ -96,7 +97,7 @@ public class SelectorAnnotationContext implements ISelectorContext { * #getAnnotation() */ @Override - public Object getAnnotation() { + public IAnnotationHandle getAnnotation() { return this.parent.getAnnotation(); } @@ -105,7 +106,7 @@ public class SelectorAnnotationContext implements ISelectorContext { * #getSelectorAnnotation() */ @Override - public Object getSelectorAnnotation() { + public IAnnotationHandle getSelectorAnnotation() { return this.selectorAnnotation; } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index 4ce05960..0bcf67a8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.struct; +import java.util.Locale; + import javax.tools.Diagnostic.Kind; import org.objectweb.asm.tree.AnnotationNode; @@ -33,6 +35,8 @@ import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.asm.util.logging.MessageRouter; /** @@ -105,6 +109,14 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { public String getMethodName() { return this.method.name; } + + /** + * Get the primary annotation which makes this method special + */ + @Override + public AnnotationNode getAnnotationNode() { + return this.annotation; + } /** * Get the primary annotation which makes this method special @@ -112,8 +124,8 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return The primary method annotation */ @Override - public final AnnotationNode getAnnotation() { - return this.annotation; + public final IAnnotationHandle getAnnotation() { + return Annotations.handleOf(this.annotation); } /** @@ -123,8 +135,8 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return The selector context annotation */ @Override - public AnnotationNode getSelectorAnnotation() { - return this.annotation; + public IAnnotationHandle getSelectorAnnotation() { + return Annotations.handleOf(this.annotation); } /** @@ -134,7 +146,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { */ @Override public String getSelectorCoordinate(boolean leaf) { - return leaf ? "method" : this.getMethodName().toLowerCase(); + return leaf ? "method" : this.getMethodName().toLowerCase(Locale.ROOT); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java index 181feffa..d509a898 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -29,7 +29,7 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; -import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.asm.MethodNodeEx; /** @@ -60,7 +60,7 @@ public class SpecialMethodInfo extends AnnotatedMethodInfo { public SpecialMethodInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { super(mixin, method, annotation); this.mixin = mixin; - this.annotationType = this.annotation != null ? "@" + Bytecode.getSimpleName(this.annotation) : "Undecorated injector"; + this.annotationType = this.annotation != null ? "@" + Annotations.getSimpleName(this.annotation) : "Undecorated injector"; this.classNode = mixin.getTargetClassNode(); this.methodName = MethodNodeEx.getName(method); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 9f43be95..0ab8774d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -636,7 +636,7 @@ class MixinApplicatorStandard { return true; } throw new InvalidMixinException(mixin, String.format("Incompatible @%s %s (for %s) in %s previously written by %s (for %s)", - Bytecode.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget)); + Annotations.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index 16b2aa91..ba43f425 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -112,7 +112,7 @@ class MixinPreProcessorStandard { private SpecialMethod(boolean isOverwrite, Class type) { this.isOverwrite = isOverwrite; this.annotation = type; - this.description = "@" + Bytecode.getSimpleName(type); + this.description = "@" + Annotations.getSimpleName(type); } private SpecialMethod(boolean isOverwrite) { @@ -380,7 +380,7 @@ class MixinPreProcessorStandard { } else { String uniqueName = context.getUniqueName(mixinMethod, true); MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @{} method {}{} to {} in {}", - Bytecode.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); + Annotations.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); mixinMethod.name = method.conform(uniqueName); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 268bc9e5..b4ccbbc3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -1257,7 +1257,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { } methodActivity.next("Undecorate"); - method.visibleAnnotations.remove(injectInfo.getAnnotation()); + method.visibleAnnotations.remove(injectInfo.getAnnotationNode()); methodActivity.end(); } prepareActivity.end(); diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index 892317df..08a27eb1 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -61,11 +61,15 @@ public final class Annotations { private final AnnotationNode annotation; - public Handle(AnnotationNode annotation) { + Handle(AnnotationNode annotation) { Preconditions.checkNotNull(annotation, "annotation"); this.annotation = annotation; } - + + public AnnotationNode getNode() { + return this.annotation; + } + @Override public String getDesc() { return this.annotation.desc; @@ -116,7 +120,7 @@ public final class Annotations { @Override public String toString() { - return "@" + Bytecode.getSimpleName(this.annotation); + return "@" + Annotations.getSimpleName(this.annotation); } } @@ -157,6 +161,28 @@ public final class Annotations { } } + /** + * Returns the simple name of an annotation, mainly used for printing + * annotation names in error messages/user-facing strings + * + * @param annotationType annotation + * @return annotation's simple name + */ + public static String getSimpleName(Class annotationType) { + return annotationType.getSimpleName(); + } + + /** + * Returns the simple name of an annotation, mainly used for printing + * annotation names in error messages/user-facing strings + * + * @param annotation annotation node + * @return annotation's simple name + */ + public static String getSimpleName(AnnotationNode annotation) { + return Bytecode.getSimpleName(annotation.desc); + } + /** * Set a runtime-visible annotation of the specified class on the supplied * field node diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 66f877b7..c1b02b35 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -26,7 +26,6 @@ package org.spongepowered.asm.util; import java.io.OutputStream; import java.io.PrintWriter; -import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -766,17 +765,6 @@ public final class Bytecode { return desc.substring(0, desc.lastIndexOf(')') + 1) + returnType; } - /** - * Returns the simple name of an annotation, mainly used for printing - * annotation names in error messages/user-facing strings - * - * @param annotationType annotation - * @return annotation's simple name - */ - public static String getSimpleName(Class annotationType) { - return annotationType.getSimpleName(); - } - /** * Returns the simple name of a type representing a class * @@ -786,17 +774,6 @@ public final class Bytecode { public static String getSimpleName(Type type) { return type.getSort() < Type.ARRAY ? type.getDescriptor() : Bytecode.getSimpleName(type.getClassName()); } - - /** - * Returns the simple name of an annotation, mainly used for printing - * annotation names in error messages/user-facing strings - * - * @param annotation annotation node - * @return annotation's simple name - */ - public static String getSimpleName(AnnotationNode annotation) { - return Bytecode.getSimpleName(annotation.desc); - } /** * Returns the simple name from an object type descriptor (in L...; format) From c1aec0fb49a907f25bc4f958586b075162c77ffc Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 6 Feb 2021 01:13:10 +0000 Subject: [PATCH 16/42] Show the javadoc some love and a bit of a facelift, improve some docs Closes #457, closes #446 --- README.MD | 2 +- build.gradle | 18 + docs/javadoc/mixin.css | 273 +++++++++ docs/javadoc/overview.html | 37 ++ docs/javadoc/resources/jdk8_stylesheet.css | 574 ++++++++++++++++++ docs/{ => javadoc/resources}/logo.png | Bin .../tools/obfuscation/SuppressedBy.java | 39 +- .../tools/obfuscation/package-info.java | 29 + .../asm/launch/package-info.java | 30 + .../platform/container/package-info.java | 29 + .../asm/launch/platform/package-info.java | 30 + .../spongepowered/asm/mixin/Implements.java | 8 +- .../spongepowered/asm/mixin/Intrinsic.java | 42 +- .../org/spongepowered/asm/mixin/Mixin.java | 48 +- .../org/spongepowered/asm/mixin/Pseudo.java | 45 +- .../asm/mixin/connect/package-info.java | 29 + .../asm/mixin/extensibility/package-info.java | 30 + .../asm/mixin/gen/package-info.java | 32 + .../mixin/gen/throwables/package-info.java | 29 + .../asm/mixin/injection/InjectionPoint.java | 21 +- .../asm/mixin/injection/ModifyArg.java | 48 +- .../asm/mixin/injection/ModifyVariable.java | 17 +- .../asm/mixin/injection/Redirect.java | 40 +- .../asm/mixin/injection/Slice.java | 2 +- .../injection/callback/package-info.java | 30 + .../mixin/injection/code/package-info.java | 29 + .../injection/invoke/RedirectInjector.java | 2 +- .../injection/invoke/arg/package-info.java | 32 + .../mixin/injection/invoke/package-info.java | 29 + .../injection/invoke/util/package-info.java | 29 + .../mixin/injection/modify/package-info.java | 31 + .../asm/mixin/injection/package-info.java | 30 + .../injection/points/BeforeConstant.java | 24 +- .../injection/points/BeforeFieldAccess.java | 33 +- .../asm/mixin/injection/points/BeforeNew.java | 10 +- .../injection/points/BeforeStringInvoke.java | 2 +- .../mixin/injection/points/package-info.java | 30 + .../selectors/dynamic/package-info.java | 29 + .../injection/selectors/package-info.java | 31 + .../mixin/injection/struct/MemberInfo.java | 48 +- .../mixin/injection/struct/package-info.java | 29 + .../injection/throwables/package-info.java | 29 + .../spongepowered/asm/mixin/package-info.java | 34 ++ .../asm/mixin/refmap/package-info.java | 31 + .../asm/mixin/struct/package-info.java | 29 + .../asm/mixin/throwables/package-info.java | 29 + .../asm/mixin/transformer/ClassInfo.java | 8 +- .../asm/mixin/transformer/InterfaceInfo.java | 2 +- .../asm/mixin/transformer/MethodMapper.java | 2 +- .../asm/mixin/transformer/MixinProcessor.java | 2 +- .../ext/extensions/package-info.java | 29 + .../mixin/transformer/ext/package-info.java | 30 + .../mixin/transformer/meta/package-info.java | 29 + .../asm/mixin/transformer/package-info.java | 29 + .../transformer/throwables/package-info.java | 29 + .../mapping/common/package-info.java | 29 + .../obfuscation/mapping/fg3/package-info.java | 30 + .../obfuscation/mapping/mcp/package-info.java | 29 + .../asm/obfuscation/mapping/package-info.java | 29 + .../asm/obfuscation/package-info.java | 30 + .../org/spongepowered/asm/package-info.java | 29 + .../asm/service/package-info.java | 31 + .../asm/transformers/package-info.java | 29 + .../asm/util/asm/package-info.java | 30 + .../asm/util/logging/package-info.java | 30 + .../spongepowered/asm/util/package-info.java | 30 + .../asm/util/perf/package-info.java | 29 + 67 files changed, 2406 insertions(+), 161 deletions(-) create mode 100644 docs/javadoc/mixin.css create mode 100644 docs/javadoc/overview.html create mode 100644 docs/javadoc/resources/jdk8_stylesheet.css rename docs/{ => javadoc/resources}/logo.png (100%) create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/launch/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/launch/platform/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/connect/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/gen/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/struct/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/obfuscation/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/service/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/transformers/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/util/asm/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/util/logging/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/util/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/util/perf/package-info.java diff --git a/README.MD b/README.MD index 6c5b29bb..e35254d8 100644 --- a/README.MD +++ b/README.MD @@ -1,7 +1,7 @@ ### [![Build Status](http://ci.liteloader.com/view/Other/job/Mixin/badge/icon)](http://ci.liteloader.com/view/Other/job/Mixin/lastSuccessfulBuild/) -![Mixin Logo](docs/logo.png?raw=true) +![Mixin Logo](docs/javadoc/resources/logo.png?raw=true) **Mixin** is a trait/mixin framework for Java using [ASM](http://asm.ow2.org/) and hooking into the runtime class-loading process via Mojang's diff --git a/build.gradle b/build.gradle index 5024ef9a..835530b1 100644 --- a/build.gradle +++ b/build.gradle @@ -94,6 +94,8 @@ sourceSets { } launchwrapper { compileClasspath += main.output + sourceCompatibility = '1.8' + targetCompatibility = '1.8' } modlauncher { compileClasspath += main.output @@ -170,7 +172,23 @@ dependencies { } javadoc { + exclude '**/throwables' classpath += sourceSets.legacy.output + source sourceSets.ap.allJava + exclude { + it.relativePath.file && it.relativePath.pathString =~ 'tools' && !(it.name =~ /SuppressedBy|package-info/) } + options { + docTitle 'Welcome to the Mixin Javadoc' + overview 'docs/javadoc/overview.html' + stylesheetFile file('docs/javadoc/mixin.css') + addBooleanOption '-allow-script-in-comments', true + } + doLast { + copy { + from 'docs/javadoc/resources' + into outputDirectory + } + } } // Eclipse diff --git a/docs/javadoc/mixin.css b/docs/javadoc/mixin.css new file mode 100644 index 00000000..fbebec3a --- /dev/null +++ b/docs/javadoc/mixin.css @@ -0,0 +1,273 @@ +@import url('jdk8_stylesheet.css'); + +/* Montserrat font, for sponge style */ +@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700;900'); + +span.summary { + clear: both; + display: block; +} + +span.summary.p { + padding: 12px 0; +} + +span.summary hr { + color: transparent; + margin: 8px; +} + +.subTitle .block .summary { + margin-block-start: 0; +} + +.tableSubHeadingColor { + background-color:#EEEEFF; +} +.altColor, .rowColor { + background-color:#FFFFFF; +} + +/* altColor and rowColor get screwed up by hidden classes so just use css */ +tr.altColor:nth-child(even), tr.rowColor:nth-child(even) { + background: #EEE; +} + +sup { + font-size:8px; +} + +tt { + color: #6c4e0b; +} + +code i, dt i { + color: #996c0c; +} + +a:link, a:visited, code b { + color: #c79015; +} + +a:hover, a:focus, a:active, code em { + color: #e8aa21; +} + +code b, code em, code i, dt i { + font-style: normal; + font-weight: normal; +} + +ins { + background-color: #ffd26d; + text-decoration: none; +} + +del { + color: #AAA; + text-decoration: none; +} + +table.infoTable { + border-collapse: collapse; +} + +table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th { + padding: 6px 8px; + background-color: #F0F0F0; +} + +table.cellTable th, table.cellTable td { + text-align: center; +} + +table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th { + background-color: #CCC; + font-weight: bold; +} + +a[name] { + color: #353833; +} + +a[name]:hover { + text-decoration:none; + color: #353833; +} + +body { + background-color: #FFF; +} + +body, div.block { + font-family: Tahoma, sans-serif, sans; + font-size: 15px; +} + +.indexContainer, +td.colFirst, th.colFirst, td.colLast, th.colLast, td.colOne, th.colOne, +.indexHeader h1, .header ul li, .footer ul li { + font-size: 16px; +} + +.indexHeader span { + font-size: 24px; +} + +.indexHeader h1 { + font-size:13px; +} + +.indexContainer h2 { + font-size: 17px; +} + +.bar a, .bar a:link, .bar a:visited, .bar a:active { + color:#FFFFFF; +} + +.bar { + font-size: 17px; +} + +.tab { + color: #FFFFFF; +} + +.topNav, .bottomNav, .bar { + color: #FFFFFF; + background-color: #666; +} + +.topNav, .bottomNav { + font-size: 16px; +} + +.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { + color:#FFFFFF; +} + +.subNav { + background-color: #CCC; + font-size: 15px; +} + +.navBarCell1Rev { + background-color: #e8aa21; + color: #000; +} + +.header ul li, .footer ul li { + font-size:13px; +} +.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, +.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { + background-color: #e8aa21; + padding: 6px 12px; + height: auto; + font-family: Montserrat; + text-transform: uppercase; +} + +.memberSummary caption span.activeTableTab span { + background-color: #e8aa21; + padding: 6px 12px; + height: auto; + border-bottom: 2px solid #e8aa21; +} + +.memberSummary caption span.tableTab span { + background-color: #666; + padding: 6px 12px; + height: auto; + border-bottom: 2px solid white; +} + +.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { + border-width: 2px; +} + +.title, h1, h2, h3, h4, h5, h6, .h1 { + font-family: 'Montserrat'; +} + +.title { + font-weight: 700; + color: #666; +} + +h1.overviewTitle, .header img { + margin: 32px 0 0 0; +} + +h1, .h1 { + font-weight: bold; + font-size: 45px; +} + +h2 { + font-size: 32px; +} + +h3 { + font-style: normal; +} + +h1.title, .summary.h1 { + text-transform: uppercase; +} + +pre, code, tt, dt code, table tr td dt code { + font-family: 'Consolas', monospace; + font-size: 16px; +} + +.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { + font-size: 15px; +} + +.contentContainer .description .block dl dt { + background: #CCC; + display: inline-block; + padding: 6px 12px; + margin-left: 20px; +} + +.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { + font-family: Tahoma, sans-serif, sans; + font-size: 15px; +} + +.contentContainer .description .block dl dd { + background: #F0F0F0; + margin: -6px 0 0 40px; + padding: 12px; +} + +div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4, ul.blockList ul.blockList ul.blockList li.blockList h3 { + background-color: #CCC; + border: 0; + margin: 0 0 6px -8px; + padding: 9px 12px; +} + +th.colFirst, th.colLast, th.colOne, .constantsSummary th { + background: #CCC; + padding: 8px; +} + +blockquote { + background-color: #F5F5F5; + padding: 12px 40px; + margin: 12px 0; +} + +blockquote pre { + margin: 0; +} + +ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { + padding-top: 1px; + border: 0; + background-color: #F5F5F5; +} diff --git a/docs/javadoc/overview.html b/docs/javadoc/overview.html new file mode 100644 index 00000000..8d52d610 --- /dev/null +++ b/docs/javadoc/overview.html @@ -0,0 +1,37 @@ + +

+ Mixin is a trait/mixin framework for Java using + ASM and hooking into + the runtime class-loading process via Mojang's + + LegacyLauncher system. The main documentation for Mixin can + be found in the + + Wiki. +

+ +

+ This Javadoc contains documentation for individual features and + annotations. For additional help use the channel + #mixin + on the Sponge Discord Server. +

+ + + diff --git a/docs/javadoc/resources/jdk8_stylesheet.css b/docs/javadoc/resources/jdk8_stylesheet.css new file mode 100644 index 00000000..98055b22 --- /dev/null +++ b/docs/javadoc/resources/jdk8_stylesheet.css @@ -0,0 +1,574 @@ +/* Javadoc style sheet */ +/* +Overall document style +*/ + +@import url('resources/fonts/dejavu.css'); + +body { + background-color:#ffffff; + color:#353833; + font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; + font-size:14px; + margin:0; +} +a:link, a:visited { + text-decoration:none; + color:#4A6782; +} +a:hover, a:focus { + text-decoration:none; + color:#bb7a2a; +} +a:active { + text-decoration:none; + color:#4A6782; +} +a[name] { + color:#353833; +} +a[name]:hover { + text-decoration:none; + color:#353833; +} +pre { + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; +} +h1 { + font-size:20px; +} +h2 { + font-size:18px; +} +h3 { + font-size:16px; + font-style:italic; +} +h4 { + font-size:13px; +} +h5 { + font-size:12px; +} +h6 { + font-size:11px; +} +ul { + list-style-type:disc; +} +code, tt { + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; + padding-top:4px; + margin-top:8px; + line-height:1.4em; +} +dt code { + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; + padding-top:4px; +} +table tr td dt code { + font-family:'DejaVu Sans Mono', monospace; + font-size:14px; + vertical-align:top; + padding-top:4px; +} +sup { + font-size:8px; +} +/* +Document title and Copyright styles +*/ +.clear { + clear:both; + height:0px; + overflow:hidden; +} +.aboutLanguage { + float:right; + padding:0px 21px; + font-size:11px; + z-index:200; + margin-top:-9px; +} +.legalCopy { + margin-left:.5em; +} +.bar a, .bar a:link, .bar a:visited, .bar a:active { + color:#FFFFFF; + text-decoration:none; +} +.bar a:hover, .bar a:focus { + color:#bb7a2a; +} +.tab { + background-color:#0066FF; + color:#ffffff; + padding:8px; + width:5em; + font-weight:bold; +} +/* +Navigation bar styles +*/ +.bar { + background-color:#4D7A97; + color:#FFFFFF; + padding:.8em .5em .4em .8em; + height:auto;/*height:1.8em;*/ + font-size:11px; + margin:0; +} +.topNav { + background-color:#4D7A97; + color:#FFFFFF; + float:left; + padding:0; + width:100%; + clear:right; + height:2.8em; + padding-top:10px; + overflow:hidden; + font-size:12px; +} +.bottomNav { + margin-top:10px; + background-color:#4D7A97; + color:#FFFFFF; + float:left; + padding:0; + width:100%; + clear:right; + height:2.8em; + padding-top:10px; + overflow:hidden; + font-size:12px; +} +.subNav { + background-color:#dee3e9; + float:left; + width:100%; + overflow:hidden; + font-size:12px; +} +.subNav div { + clear:left; + float:left; + padding:0 0 5px 6px; + text-transform:uppercase; +} +ul.navList, ul.subNavList { + float:left; + margin:0 25px 0 0; + padding:0; +} +ul.navList li{ + list-style:none; + float:left; + padding: 5px 6px; + text-transform:uppercase; +} +ul.subNavList li{ + list-style:none; + float:left; +} +.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { + color:#FFFFFF; + text-decoration:none; + text-transform:uppercase; +} +.topNav a:hover, .bottomNav a:hover { + text-decoration:none; + color:#bb7a2a; + text-transform:uppercase; +} +.navBarCell1Rev { + background-color:#F8981D; + color:#253441; + margin: auto 5px; +} +.skipNav { + position:absolute; + top:auto; + left:-9999px; + overflow:hidden; +} +/* +Page header and footer styles +*/ +.header, .footer { + clear:both; + margin:0 20px; + padding:5px 0 0 0; +} +.indexHeader { + margin:10px; + position:relative; +} +.indexHeader span{ + margin-right:15px; +} +.indexHeader h1 { + font-size:13px; +} +.title { + color:#2c4557; + margin:10px 0; +} +.subTitle { + margin:5px 0 0 0; +} +.header ul { + margin:0 0 15px 0; + padding:0; +} +.footer ul { + margin:20px 0 5px 0; +} +.header ul li, .footer ul li { + list-style:none; + font-size:13px; +} +/* +Heading styles +*/ +div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { + background-color:#dee3e9; + border:1px solid #d0d9e0; + margin:0 0 6px -8px; + padding:7px 5px; +} +ul.blockList ul.blockList ul.blockList li.blockList h3 { + background-color:#dee3e9; + border:1px solid #d0d9e0; + margin:0 0 6px -8px; + padding:7px 5px; +} +ul.blockList ul.blockList li.blockList h3 { + padding:0; + margin:15px 0; +} +ul.blockList li.blockList h2 { + padding:0px 0 20px 0; +} +/* +Page layout container styles +*/ +.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { + clear:both; + padding:10px 20px; + position:relative; +} +.indexContainer { + margin:10px; + position:relative; + font-size:12px; +} +.indexContainer h2 { + font-size:13px; + padding:0 0 3px 0; +} +.indexContainer ul { + margin:0; + padding:0; +} +.indexContainer ul li { + list-style:none; + padding-top:2px; +} +.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { + font-size:12px; + font-weight:bold; + margin:10px 0 0 0; + color:#4E4E4E; +} +.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { + margin:5px 0 10px 0px; + font-size:14px; + font-family:'DejaVu Sans Mono',monospace; +} +.serializedFormContainer dl.nameValue dt { + margin-left:1px; + font-size:1.1em; + display:inline; + font-weight:bold; +} +.serializedFormContainer dl.nameValue dd { + margin:0 0 0 1px; + font-size:1.1em; + display:inline; +} +/* +List styles +*/ +ul.horizontal li { + display:inline; + font-size:0.9em; +} +ul.inheritance { + margin:0; + padding:0; +} +ul.inheritance li { + display:inline; + list-style:none; +} +ul.inheritance li ul.inheritance { + margin-left:15px; + padding-left:15px; + padding-top:1px; +} +ul.blockList, ul.blockListLast { + margin:10px 0 10px 0; + padding:0; +} +ul.blockList li.blockList, ul.blockListLast li.blockList { + list-style:none; + margin-bottom:15px; + line-height:1.4; +} +ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { + padding:0px 20px 5px 10px; + border:1px solid #ededed; + background-color:#f8f8f8; +} +ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { + padding:0 0 5px 8px; + background-color:#ffffff; + border:none; +} +ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { + margin-left:0; + padding-left:0; + padding-bottom:15px; + border:none; +} +ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { + list-style:none; + border-bottom:none; + padding-bottom:0; +} +table tr td dl, table tr td dl dt, table tr td dl dd { + margin-top:0; + margin-bottom:1px; +} +/* +Table styles +*/ +.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { + width:100%; + border-left:1px solid #EEE; + border-right:1px solid #EEE; + border-bottom:1px solid #EEE; +} +.overviewSummary, .memberSummary { + padding:0px; +} +.overviewSummary caption, .memberSummary caption, .typeSummary caption, +.useSummary caption, .constantsSummary caption, .deprecatedSummary caption { + position:relative; + text-align:left; + background-repeat:no-repeat; + color:#253441; + font-weight:bold; + clear:none; + overflow:hidden; + padding:0px; + padding-top:10px; + padding-left:1px; + margin:0px; + white-space:pre; +} +.overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, +.useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, +.overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, +.useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover, +.overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active, +.useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, +.overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, +.useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { + color:#FFFFFF; +} +.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, +.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { + white-space:nowrap; + padding-top:5px; + padding-left:12px; + padding-right:12px; + padding-bottom:7px; + display:inline-block; + float:left; + background-color:#F8981D; + border: none; + height:16px; +} +.memberSummary caption span.activeTableTab span { + white-space:nowrap; + padding-top:5px; + padding-left:12px; + padding-right:12px; + margin-right:3px; + display:inline-block; + float:left; + background-color:#F8981D; + height:16px; +} +.memberSummary caption span.tableTab span { + white-space:nowrap; + padding-top:5px; + padding-left:12px; + padding-right:12px; + margin-right:3px; + display:inline-block; + float:left; + background-color:#4D7A97; + height:16px; +} +.memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { + padding-top:0px; + padding-left:0px; + padding-right:0px; + background-image:none; + float:none; + display:inline; +} +.overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd, +.useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { + display:none; + width:5px; + position:relative; + float:left; + background-color:#F8981D; +} +.memberSummary .activeTableTab .tabEnd { + display:none; + width:5px; + margin-right:3px; + position:relative; + float:left; + background-color:#F8981D; +} +.memberSummary .tableTab .tabEnd { + display:none; + width:5px; + margin-right:3px; + position:relative; + background-color:#4D7A97; + float:left; + +} +.overviewSummary td, .memberSummary td, .typeSummary td, +.useSummary td, .constantsSummary td, .deprecatedSummary td { + text-align:left; + padding:0px 0px 12px 10px; +} +th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, +td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{ + vertical-align:top; + padding-right:0px; + padding-top:8px; + padding-bottom:3px; +} +th.colFirst, th.colLast, th.colOne, .constantsSummary th { + background:#dee3e9; + text-align:left; + padding:8px 3px 3px 7px; +} +td.colFirst, th.colFirst { + white-space:nowrap; + font-size:13px; +} +td.colLast, th.colLast { + font-size:13px; +} +td.colOne, th.colOne { + font-size:13px; +} +.overviewSummary td.colFirst, .overviewSummary th.colFirst, +.useSummary td.colFirst, .useSummary th.colFirst, +.overviewSummary td.colOne, .overviewSummary th.colOne, +.memberSummary td.colFirst, .memberSummary th.colFirst, +.memberSummary td.colOne, .memberSummary th.colOne, +.typeSummary td.colFirst{ + width:25%; + vertical-align:top; +} +td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { + font-weight:bold; +} +.tableSubHeadingColor { + background-color:#EEEEFF; +} +.altColor { + background-color:#FFFFFF; +} +.rowColor { + background-color:#EEEEEF; +} +/* +Content styles +*/ +.description pre { + margin-top:0; +} +.deprecatedContent { + margin:0; + padding:10px 0; +} +.docSummary { + padding:0; +} + +ul.blockList ul.blockList ul.blockList li.blockList h3 { + font-style:normal; +} + +div.block { + font-size:14px; + font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; +} + +td.colLast div { + padding-top:0px; +} + + +td.colLast a { + padding-bottom:3px; +} +/* +Formatting effect styles +*/ +.sourceLineNo { + color:green; + padding:0 30px 0 0; +} +h1.hidden { + visibility:hidden; + overflow:hidden; + font-size:10px; +} +.block { + display:block; + margin:3px 10px 2px 0px; + color:#474747; +} +.deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, +.overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, +.seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { + font-weight:bold; +} +.deprecationComment, .emphasizedPhrase, .interfaceName { + font-style:italic; +} + +div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase, +div.block div.block span.interfaceName { + font-style:normal; +} + +div.contentContainer ul.blockList li.blockList h2{ + padding-bottom:0px; +} diff --git a/docs/logo.png b/docs/javadoc/resources/logo.png similarity index 100% rename from docs/logo.png rename to docs/javadoc/resources/logo.png diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java index 70ecf4f6..c8c50547 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -24,6 +24,8 @@ */ package org.spongepowered.tools.obfuscation; +import org.spongepowered.asm.mixin.Overwrite; + /** * A centralised list of tokens supported by the AP for use in * {@link SuppressWarnings} annotations. Collected here mainly for @@ -33,52 +35,79 @@ public enum SuppressedBy { /** * Suppress warnings for constraint violations + *
Usage: + * @SuppressWarnings('constraints') + *
*/ CONSTRAINTS("constraints"), /** * Suppress warnings about overwrite visibility upgrading/downgrading target * visibility + *
Usage: + * @SuppressWarnings('visibility') + *
*/ VISIBILITY("visibility"), /** * Suppress warnings when an injector target cannot be found + *
Usage: + * @SuppressWarnings('target') + *
*/ TARGET("target"), /** * Suppress warnings when a class, method or field mapping cannot be located + *
Usage: + * @SuppressWarnings('mapping') + *
*/ MAPPING("mapping"), /** - * Suppress warnings for when an @Overwrite method is missing - * javadoc, or author or reason tags + * Suppress warnings for when an {@link Overwrite @Overwrite} method is + * missing javadoc, or author or reason tags + *
Usage: + * @SuppressWarnings('overwrite') + *
*/ OVERWRITE("overwrite"), /** * Suppress warnings when a mixin target specified by name is located in the * default package + *
Usage: + * @SuppressWarnings('default-package') + *
*/ DEFAULT_PACKAGE("default-package"), /** * Suppress warnings when a mixin target is resolved by the AP as visible * but cannot be referenced with a class literal for some reason + *
Usage: + * @SuppressWarnings('public-target') + *
*/ PUBLIC_TARGET("public-target"), /** - * Suppress warning when a mixin target is resolved by the AP as imaginary - * (unresolvable via Mirror at compile time). For example for anonymous - * inner classes or other synthetic member classes. + * Suppress warning when a mixin target is resolved by the AP as imaginary + * (unresolvable via Mirror at compile time), for example for anonymous + * inner classes or other synthetic member classes + *
Usage: + * @SuppressWarnings('unresolvable-target') + *
*/ UNRESOLVABLE_TARGET("unresolvable-target"), /** * The default java "raw types" suppressions + *
Usage: + * @SuppressWarnings('rawtypes') + *
*/ RAW_TYPES("rawtypes"); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java b/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java new file mode 100644 index 00000000..cf2d2f33 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Base package for the Mixin Annotation Processor. + */ +package org.spongepowered.tools.obfuscation; diff --git a/src/main/java/org/spongepowered/asm/launch/package-info.java b/src/main/java/org/spongepowered/asm/launch/package-info.java new file mode 100644 index 00000000..9fd94a8e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Classes which support environment-agnostic launch logic for the Mixin + * subsystem and base classes and interfaces for environment-specific adapters. + */ +package org.spongepowered.asm.launch; diff --git a/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java b/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java new file mode 100644 index 00000000..b3adc6e7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Default (platform-agnostic) container handles + */ +package org.spongepowered.asm.launch.platform.container; diff --git a/src/main/java/org/spongepowered/asm/launch/platform/package-info.java b/src/main/java/org/spongepowered/asm/launch/platform/package-info.java new file mode 100644 index 00000000..df016e33 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Base classes for environment-specific adapters and default platform-agnostic + * handlers for environment and mixin containers. + */ +package org.spongepowered.asm.launch.platform; diff --git a/src/main/java/org/spongepowered/asm/mixin/Implements.java b/src/main/java/org/spongepowered/asm/mixin/Implements.java index 0547eaf9..1820ad9a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Implements.java +++ b/src/main/java/org/spongepowered/asm/mixin/Implements.java @@ -31,7 +31,13 @@ import java.lang.annotation.Target; /** * Pseudo-implements decorator for Mixins with conflicting methods in a - * superclass to soft-implement an interface + * superclass to soft-implement an interface. + * + *

See Introduction to Mixins - Resolving + * Method Signature Conflicts for details on soft implementation of + * interfaces.

*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) diff --git a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java index 721e513b..1896b7db 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java +++ b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java @@ -46,10 +46,10 @@ import java.lang.annotation.Target; *

Consider the following code:

* *
@Shadow public int getSomething();
- * 
- * public int soft$getSomething() {
- *     return this.getSomething();
- * }
+ * + *public int soft$getSomething() { + * return this.getSomething(); + *} * *

This type of accessor is common when an interface conflict occurs, but has * the problem that the injected accessor will be effectively self-referential @@ -61,9 +61,9 @@ import java.lang.annotation.Target; * *

@Shadow private int something;
  * 
- * public int soft$getSomething() {
- *     return this.something;
- * }
+ *public int soft$getSomething() { + * return this.something; + *} * *

But this has the drawback of forcing the mixin to re-implement the target * method, and thus forces ongoing maintenance of the mixin to include updating @@ -75,21 +75,21 @@ import java.lang.annotation.Target; * accessor with {@link Intrinsic @Intrinsic}:

* *
@Shadow public int getSomething();
- * 
- * @Intrinsic // don't merge the method if the target already exists
- * public int soft$getSomething() {
- *     return this.getSomething();
- * }
+ * + *@Intrinsic // don't merge the method if the target already exists + *public int soft$getSomething() { + * return this.getSomething(); + *} * *

This is ideal if the accessor is simply providing a proxy through to an * underlying obfuscated method, as in the example above. However, if the new * method contains additional code, such as in this example:

* *
@Shadow public int getSomething();
- * 
- * public int soft$getSomething() {
- *     return this.someCondition ? this.someOtherValue : this.getSomething();
- * }
+ * + *public int soft$getSomething() { + * return this.someCondition ? this.someOtherValue : this.getSomething(); + *} * *

Then we still have the original problem that the method becomes re-entrant * without specifying the additional Overwrite. We can solve this with the @@ -108,11 +108,11 @@ import java.lang.annotation.Target; * accessor will call the overwritten method.

* *
@Shadow public int getSomething();
- * 
- * @Intrinsic(displace = true) // if the target already exists, displace it
- * public int soft$getSomething() {
- *     return this.someCondition ? this.someOtherValue : this.getSomething();
- * }
+ * + *@Intrinsic(displace = true) // if the target already exists, displace it + *public int soft$getSomething() { + * return this.someCondition ? this.someOtherValue : this.getSomething(); + *} * */ @Target({ ElementType.METHOD }) diff --git a/src/main/java/org/spongepowered/asm/mixin/Mixin.java b/src/main/java/org/spongepowered/asm/mixin/Mixin.java index 3d490711..bd071095 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Mixin.java +++ b/src/main/java/org/spongepowered/asm/mixin/Mixin.java @@ -30,7 +30,22 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Decorator for mixin classes + * The main decorator for mixin classes, this annotation denotes a class as a + * mixin and specifies two key attributes: + * + *
+ *
The target classes
+ *
Every mixin requires at least one target class in order to be valid. + * The target classes should be specified via {@link #value} where possible + * using class literals. However for anonymous inner classes, + * package-private classes, or unavailable classes (eg. synthetic classes) + * being targetted via {@link Pseudo @Pseudo}, the targets should be + * specified via the {@link #targets} instead.
+ *
The priority
+ *
The mixin {@link #priority} is used to express the mixin's desired + * ordering with respect to other mixins being applied to the same target + * class.
+ *
*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) @@ -46,18 +61,34 @@ public @interface Mixin { /** * Since specifying targets in {@link #value} requires that the classes be * publicly visible, this property is provided to allow package-private, - * anonymous innner, and private inner classes to be referenced. Referencing - * an otherwise public class using this property is an error condition and - * will throw an exception at runtime. It is completely fine to specify both - * public and private targets for the same mixin however. + * anonymous innner, and private inner, or unavailable ({@link Pseudo + * @Pseudo} classes to be referenced. Referencing an otherwise public + * class using this property is an error condition and will raise a warning + * at runtime or an error if {@link MixinEnvironment.Option#DEBUG_STRICT + * strict checks} are enabled. It is completely fine to specify both publi + * and private targets for the same mixin however. + * + *

Note that unlike class literals specified in {@link #value}, imports + * are not supported and therefore the class specified here must be + * fully-qualified with the package name.

* - * @return protected or package-private classes this mixin targets + * @return protected, package-private, or {@link Pseudo pseudo} classes this + * mixin targets */ public String[] targets() default { }; /** * Priority for the mixin, relative to other mixins targetting the same - * classes + * classes. By default mixins inherit their priority from the parent + * configuration that contains them, setting this value allows the priority + * to be overridden on a per-mixin basis. + * + *

Priorities sort mixins into natural order with lower priority + * mixins being applied first. This changes the nature of priority based on + * your intentions. Especially with respect to injectors, which must be + * considered on a case-by-case basis since the semantics of priority vary + * by injector because of first-come-first-served versus implied ordering of + * injectors such as inject-at-HEAD.

* * @return the mixin priority (relative to other mixins targetting the same * class) @@ -66,7 +97,7 @@ public @interface Mixin { /** * By default, the annotation processor will attempt to locate an - * obfuscation mapping for all {@link Shadow} and + * obfuscation mapping for all {@link Overwrite}, {@link Shadow} and * {@link org.spongepowered.asm.mixin.injection.Inject} annotated members * since it is anticipated that in general the target of a {@link Mixin} * will be an obfuscated class and all annotated members will need to be @@ -84,4 +115,5 @@ public @interface Mixin { * obfuscation mappings for this annotation (default true). */ public boolean remap() default true; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/Pseudo.java b/src/main/java/org/spongepowered/asm/mixin/Pseudo.java index fc6c394a..335304f4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Pseudo.java +++ b/src/main/java/org/spongepowered/asm/mixin/Pseudo.java @@ -30,23 +30,38 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * A Mixin marked as Pseudo is allowed to target classes which are not - * available at compile time and may not be available at runtime. This means - * that certain restrictions apply: + * A Mixin marked as @Pseudo is allowed to target classes which are + * not available at compile time and may not be available at runtime. + * This can be used in situations where - for one reason or another - a target + * class is not available to a project being compiled and would therefore fail + * AP verification. The target class is simulated by the AP using knowledge of + * only the superclass of the target (or at least, any available known + * superclass of the target. This means that certain restrictions apply: * - *

In particular, the superclass requirement for pseudo mixins is extremely - * important if the target has an obfuscated class in its hierarchy. For example - * let's assume that we're mixing into a class SomeCustomScreen from - * another party which extends GuiScreen which is obfuscated. - * Attempting to inject into initGui will succeed at dev time and fail - * at production time, because the reference is obfuscated. We can overcome this - * by ensuring the mixin inherits from the same superclass, thus allowing - * initGui to be resolved in the superclass hierarchy (this is not the - * case for normal mixins).

+ *

The superclass requirement for pseudo mixins is extremely important if + * the target has an obfuscated class in its hierarchy. For example + * let's assume that we're mixing into a class CustomGuiScreen from + * another party which extends GuiScreen, where GuiScreen is + * an obfuscated class. GuiScreen contains an obfuscated method + * initGui which the (@Pseudo) target class overrides. Attempting + * to inject into initGui would succeed at dev time but would fail + * at production time, because the reference is obfuscated. Normally when a + * target overrides an obfuscated method in this way, the AP can resolve the + * obfuscation by walking the superclass hierarchy of the target in order to + * discover a mapping. However when the target is not available at compile time + * the AP cannot do this and must rely on only information from the mixin + * itself. We can overcome this problem by ensuring the mixin inherits from the + * same superclass (or at least a superclass which contains the obfuscated + * methods or fields used in the mixin), thus allowing our example initGui + * method to be resolved in the superclass hierarchy. This behaviour is + * not available to normal mixins as the AP always resolves the hierarchy via + * the target class metadata when it is available.

* - *

{@link Overwrite} methods which are not inherited from a superclass - * (if the target is obfuscated) must be decorated manually with aliases. - *

+ *

If the target class contains obfuscated methods which the mixin needs to + * {@link Overwrite} or {@link Shadow} which are not inherited from a + * superclass (eg. the target is obfuscated), the {@link Overwrite} or + * {@link Shadow} must be decorated manually with aliases since + * there is no mechanism for the AP to resolve the mappings automatically.

*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) diff --git a/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java b/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java new file mode 100644 index 00000000..0a71a362 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * See {@link org.spongepowered.asm.mixin.connect.IMixinConnector} + */ +package org.spongepowered.asm.mixin.connect; diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java new file mode 100644 index 00000000..79f0a47d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Interfaces for internal Mixin objects which provide extensibility for mixin + * consumers. + */ +package org.spongepowered.asm.mixin.extensibility; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java b/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java new file mode 100644 index 00000000..8b740b19 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Generators, a special type of injector which replace the annotated method + * with synthetic content, see + * {@link org.spongepowered.asm.mixin.gen.Accessor @Accessor} and + * {@link org.spongepowered.asm.mixin.gen.Invoker @Invoker}. + */ +package org.spongepowered.asm.mixin.gen; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java new file mode 100644 index 00000000..49468b98 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Exceptions for generators. + */ +package org.spongepowered.asm.mixin.gen.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 171994c7..5a2f332e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -69,22 +69,23 @@ import com.google.common.collect.ImmutableList.Builder; /** *

Base class for injection point discovery classes. Each subclass describes * a strategy for locating code injection points within an instruction list, - * with the {@link #find} method populating a collection with insn nodes from - * the supplied list which satisfy its strategy.

+ * with the {@link #find find} method populating a collection with insn nodes + * from the supplied list which satisfy its strategy.

* *

This base class also contains composite strategy factory methods such as - * {@link #and} and {@link #or} which allow strategies to be combined using - * intersection (and) or union (or) relationships to allow multiple strategies - * to be easily combined.

+ * {@link #and and} and {@link #or or} which allow strategies to be combined + * using intersection (and) or union (or) relationships to allow multiple + * strategies to be easily combined.

* *

You are free to create your own injection point subclasses, but take note * that it is allowed for a single InjectionPoint instance to be used for * multiple injections and thus implementing classes MUST NOT cache the insn - * list, event, or nodes instance passed to the {@link #find} method, as each - * call to {@link #find} must be considered a separate functional contract and - * the InjectionPoint's lifespan is not linked to the discovery lifespan, - * therefore it is important that the InjectionPoint implementation is fully - * stateless.

+ * list, event, or nodes instance passed to the {@link #find find} method, as + * each call to {@link #find find} must be considered a separate functional + * contract and the InjectionPoint's lifespan is not linked to the discovery + * lifespan, therefore it is important that the InjectionPoint implementation is + * fully stateless and that calls to {@link #find find} are idempotent. + *

*/ public abstract class InjectionPoint { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index fe9ffe82..048b8238 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -38,24 +38,35 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; /** * Specifies that this mixin method should inject an argument modifier to itself * in the target method(s) identified by {@link #method}. This type of injection - * provides a lightweight mechanism for changing a single argument of a target - * method invocation. To affect multiple arguments at once, use {@link - * ModifyArgs} instead. + * provides a lightweight mechanism for changing a single argument of a selected + * method invocation within the target method(s). To affect multiple arguments + * of an invocation all at once, use {@link ModifyArgs} instead. * - *

Consider the following method call:

+ *

Use this injector when a method contains an method invocation and you wish + * to change a single value being passed to that method. If you need to + * alter an argument received by a target method, use {@link + * ModifyVariable} instead.

* - *
// x, y and z are of type float
- *someObject.setLocation(x, y, z, true);
+ *

Consider the following method:

* - *

Let us assume that we wish to modify the y value in the method - * call. We know that the arguments are floats and that the y - * value is the second (index = 1) float argument. Thus our - * injector requires the following signature: + *

private void targetMethod() {
+ *    Entity someEntity = this.obtainEntity();
+ *    float x = 1.0F, y = 3.0F, z = 0.1F;
+ *    someEntity.setLocation(x, y, z, true);
+ *}
+ *
+ * + *

Let us assume that we wish to modify the y value when + * calling the setLocation method. We know that the + * arguments are floats and that the y value is the second + * (index = 1) float argument. Thus our injector requires the + * following signature: * - *

@ModifyArg(method = "...", at = ..., index = 1)
- *private float adjustYCoord(float y) {
- *    return y + 64.0F;
- *}
+ *
@ModifyArg(method = "targetMethod", at = @At(value + * = "INVOKE", target = "setLocation(FFFZ)V"), index = 1)
+ * private float adjustYCoord(float y) {
+ *     return y + 64.0F;
+ * }
* *

The callback consumes the original value of y and returns the * adjusted value.

@@ -64,10 +75,11 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * arguments if required, to provide additional context for the callback. In * this case the arguments of the callback should match the target method:

* - *
@ModifyArg(method = "...", at = ..., index = 1)
- *private float adjustYCoord(float x, float y, float z, boolean interpolate) {
- *    return (x == 0 && y == 0) ? 0 : y;
- *}
+ *
@ModifyArg(method = "targetMethod", at = @At(value + * = "INVOKE", target = "setLocation(FFFZ)V"), index = 1)
+ * private float adjustYCoord(float x, float y, float z, boolean interpolate) { + *
    return (x == 0 && y == 0) ? 0 : y;
+ * }
*/ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index d8f76088..5dd71cfe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -37,20 +37,27 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; /** * Specifies that this mixin method should inject a variable modifier callback - * to itself in the target method(s) identified by {@link #method}. + * to itself in the target method(s) identified by {@link #method}. The variable + * modifier can modify a single local variable in the target method frame. + * + *

If the variable being modified is a method argument, specifying the + * {@link #argsOnly argsOnly=true} reduces the overhead of calculating + * the local variable table for the method.

* *

ModifyVariable callbacks should always take one argument of the * type to capture and return the same type. For example a ModifyVariable - * for a local of type {@link String} should have the signature:

+ * for a local of type {@link String} should have the + * signature:

* - * private String methodName(String variable) { ... + *
private String myHandlerMethod(String + * variable) {
    ...
* *

The callback receives the current value of the local variable, and should * return the new value.

* *

The injector has two operating modes, explicit and implicit - * , and can operate either on the entire LVT or on the method arguments - * only

. + * , and can operate either on the entire LVT or on the {@link #argsOnly + * ethod arguments only}.

* *

In explicit mode, the variable to capture can be specified by * specifying values for the discriminator arguments {@link #ordinal}, diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 3bca4255..b72f5fdc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -55,7 +55,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * int def = 1; * Foo someObject = new Foo(); * - * // Hooking this method + * // Hooking this method * boolean xyz = someObject.bar(abc, def); *} * @@ -63,7 +63,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *

The signature of the redirected method should be:

* *
- *
public boolean barProxy(Foo someObject, int abc, int def)
+ * public boolean barProxy(Foo someObject, int abc, int def) *
* *

For obvious reasons this does not apply for static methods, for static @@ -77,8 +77,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * arguments) by appending the arguments to the method signature:

* *
- *
public boolean barProxy(Foo someObject, int abc, int def,
- *    int someInt, String someString)
+ * public boolean barProxy(Foo someObject, int abc, int def, + * int someInt, String someString) *
* *

All arguments of a method redirect handler, and the return type, can be @@ -92,7 +92,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * handling a field write (PUTFIELD, PUTSTATIC) or a * field read (GETFIELD, GETSTATIC).

* - * + *
* * * @@ -148,7 +148,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * indices, for multi-dimensional arrays) and returns the element * type (in this case String) as follows:

* - *
Operation (OPCODE)Handler signature
+ *
* * * @@ -177,16 +177,16 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * array=length and configure your handler signature to return int * and consume the array as an argument:

* - *
private int getLength(ElementType[] array) + *
private int getLength(ElementType[] array) *
- * + * - *

For multi-dimensional arrays, provide one int argument for each * additional dimension of the array:

* - *
// Multidimensional array
- * private ElementType[][] array;

- * // Handler signature:
- * private int getLength(ElementType[][] array, int baseDim) + *
// Multidimensional array
+ * private ElementType[][] array;

+ * // Handler signature:
private int + * getLength(ElementType[][] array, int baseDim) *
* *

New Object Redirect Mode (Factory Mode)

@@ -211,7 +211,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *class Foo { * private final int x, y; * - * // ctor we wish to hook + * // ctor we wish to hook * Foo(int x, int y) { * this.x = x; * this.y = y; @@ -231,7 +231,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * example to redirect the following object creation call:

* *
public void exampleFunc(String someString, int dx, int dy) {
- *    // Hooking this constructor
+ *    // Hooking this constructor
  *    Foo someFoo = new Foo(dx * 10, dy * 10);
  *}
*
@@ -239,15 +239,15 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *

The signature of the handler method should be:

* *
- *
public Foo constructFoo(int x, int y)
+ * public Foo constructFoo(int x, int y) *
* *

Note that like other redirectors, it is possible to capture the target * method's arguments by appending them to the handler method's signature:

* *
- * public Foo constructFoo(int x, int y, String someString, int dx, - * int dy) + * public Foo constructFoo(int x, int y, String someString, int dx, + * int dy) *
* *

instanceof Redirect Mode

@@ -277,8 +277,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * *

Note that this results in the injected code being less efficient, because * the instanceof opcode is replaced with discrete code similar to - * reference != null && yourClass.isAssignableFrom(reference.getClass()) in - * the target method body.

+ * reference != null && yourClass.isAssignableFrom(reference.getClass()) + * in the target method body.

* *

The arguments to an instanceof redirect handler must always be * Object, Class even if the variable type is known. This is @@ -298,7 +298,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * *

class Foo : Bar {
  *    Foo(int arg) {
- *        super(Foo.isEven(arg));
+ *        super(Foo.isEven(arg));
  *    }
  *    
  *    static int isEven(int arg) {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
index 769b1555..857432db 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
@@ -85,7 +85,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
  *         thing.processStuff();
  *     }
  *     
- *     // A new call to processStuff, which now has the ordinal 1
+ *     // A new call to processStuff, which now has the ordinal 1
  *     bar.getActiveThing().processStuff();
  *     
  *     Thing specialThing = bar.getSpecialThing();
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java
new file mode 100644
index 00000000..39952e3a
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java
@@ -0,0 +1,30 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered 
+ * 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.
+ */
+
+/**
+ * Implementation of callback injector functionality provided by
+ * {@link org.spongepowered.asm.mixin.injection.Inject @#64;Inject}.
+ */
+package org.spongepowered.asm.mixin.injection.callback;
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java
new file mode 100644
index 00000000..1a505452
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java
@@ -0,0 +1,29 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered 
+ * 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.
+ */
+
+/**
+ * Common base classes for injector implementations.
+ */
+package org.spongepowered.asm.mixin.injection.code;
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
index 2cde5ecd..6e6d1967 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
@@ -65,7 +65,7 @@ import com.google.common.primitives.Ints;
  *   int def = 1;
  *   Foo someObject = new Foo();
  *   
- *   // Hooking this method
+ *   // Hooking this method
  *   boolean xyz = someObject.bar(abc, def);
*
* diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java new file mode 100644 index 00000000..e0a1adc5 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Support classes for + * {@link org.spongepowered.asm.mixin.injection.ModifyArgs @ModifyArgs} + * which handle argument bundles + * ({@link org.spongepowered.asm.mixin.injection.invoke.arg.Args}). + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java new file mode 100644 index 00000000..cbfaf69d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Implementation of injectors which primarily mutate method invocations. + */ +package org.spongepowered.asm.mixin.injection.invoke; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java new file mode 100644 index 00000000..3dd49622 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Utility classes for invoke injectors. + */ +package org.spongepowered.asm.mixin.injection.invoke.util; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java new file mode 100644 index 00000000..20ceda6c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Implementation of variable modifier injector specified by + * {@link org.spongepowered.asm.mixin.injection.ModifyVariable + * @ModifyVariable} + */ +package org.spongepowered.asm.mixin.injection.modify; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java new file mode 100644 index 00000000..c1190db2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Injectors are class postprocessors which search for annotated methods merged + * by mixins and perform weaving operations as requested. + */ +package org.spongepowered.asm.mixin.injection; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index db18ffdb..8cab6c01 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -71,41 +71,41 @@ import com.google.common.primitives.Longs; *
ordinal
*
The ordinal position of the constant opcode to match. The default value * is -1 which supresses ordinal matching
- *
named argument nullValue
+ *
named argument: nullValue
*
To match null literals in the method body, set this to * true
- *
named argument intValue
+ *
named argument: intValue
*
To match int literals in the method body. See also the * expandZeroConditions argument below for concerns when matching * conditional zeroes.
- *
named argument floatValue
+ *
named argument: floatValue
*
To match float literals in the method body.
- *
named argument longValue
+ *
named argument: longValue
*
To match long literals in the method body.
- *
named argument doubleValue
+ *
named argument: doubleValue
*
To match double literals in the method body.
- *
named argument stringValue
+ *
named argument: stringValue
*
To match {@link String} literals in the method body.
- *
named argument classValue
+ *
named argument: classValue
*
To match {@link Class} literals in the method body.
- *
named argument log
+ *
named argument: log
*
Enable debug logging when searching for matching opcodes.
- *
named argument expandZeroConditions
+ *
named argument: expandZeroConditions
*
See the {@link Constant#expandZeroConditions} option, this argument * should be a list of {@link Condition} names
* * *

Examples:

*
- *   // Find all integer constans with value 4
+ *   // Find all integer constans with value 4
  *   @At(value = "CONSTANT", args = "intValue=4")
*
*
- *   // Find the String literal "foo"
+ *   // Find the String literal "foo"
  *   @At(value = "CONSTANT", args = "stringValue=foo"
*
*
- *   // Find all integer constants with value 0 and expand conditionals
+ *   // Find integer constants with value 0 and expand conditionals
  *   @At(
  *     value = "CONSTANT",
  *     args = {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
index 0cc4b05d..5d3de468 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
@@ -49,21 +49,33 @@ import org.spongepowered.asm.util.Bytecode;
  * 
*
target
*
A {@link ITargetSelector Target Selector} which identifies the target - * field.
+ * field. *
opcode
*
The {@link Opcodes opcode} of the field access, must be one of - * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
+ * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. *
ordinal
*
The ordinal position of the field access to match. For example if the - * field is referenced 3 times and you want to match the 3rd then you can - * specify an ordinal of 2 (ordinals are zero-indexed). The - * default value is -1 which supresses ordinal matching
+ * field is referenced 3 times and you want to match the 3rd then you can + * specify an ordinal of 2 (ordinals are zero-indexed). The + * default value is -1 which supresses ordinal matching + *
named argument: array
+ *
For matching accesses to an array field element following a GETFIELD or + * GETSTATIC. Specify get, set or length to match + * the desired operation.
+ *
named argument: fuzz
+ *
When matching array operations using array the injection point + * will by default search up to 8 instructions after the matched field insn. + * However in some cases the array operation may be further from the matched + * GETFIELD or GETSTATIC and the amount to search (the "fuzz factor" can be + * specified using this argument. Likewise to optimise the search against + * false positives, this value can be specified as a lower value if desired. + * Has no effect if array is not specified.
*
* *

Example:

- *
+ * 
* @At(value = "FIELD", target="field_59_z:I", opcode = Opcodes.GETFIELD) - *
+ * *
* *

Matching array access:

@@ -72,9 +84,10 @@ import org.spongepowered.asm.util.Bytecode; * operation. To enable this behaviour specify the array named-argument * with the desired operation:

* - *
- *   @At(value = "FIELD", target="myIntArray:[I", args = "array=get")
- * 
+ *
+ * @At(value = "FIELD", target="myIntArray:[I", opcode + * = Opcodes.GETFIELD, args = "array=get") + * *
* *

See {@link Redirect} for information on array element redirection.

diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java index c0484c5e..72249325 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java @@ -52,7 +52,7 @@ import com.google.common.base.Strings; * {@link org.spongepowered.asm.mixin.injection.At At}:

* *
- *
named argument class (or specify using target
+ *
named argument: class (or specify using target
*
The value of the NEW node to look for, the fully-qualified class name *
*
ordinal
@@ -70,16 +70,16 @@ import com.google.common.base.Strings; * *

Examples:

*
- *   // Find all NEW opcodes for String
+ *   // Find all NEW opcodes for String
  *   @At(value = "NEW", args = "class=java/lang/String")
*
*
- *   // Find all NEW opcodes for String
+ *   // Find all NEW opcodes for String
  *   @At(value = "NEW", target = "java/lang/String"
*
*
- *   // Find all NEW opcodes for String which are constructed using the
- *   // ctor which takes an array of char
+ *   // Find all NEW opcodes for String which are constructed
+ *   // using the ctor which takes an array of char
  *   @At(value = "NEW", target = "([C)Ljava/lang/String;"
*
* diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java index fe02f649..82318a1c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java @@ -64,7 +64,7 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * the method is invoked 3 times and you want to match the 3rd then you can * specify an ordinal of 2 (ordinals are zero-indexed). The * default value is -1 which supresses ordinal matching - *
named argument ldc
+ *
named argument: ldc
*
The value of the LDC node to look for prior to the method invocation *
*
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java new file mode 100644 index 00000000..d84bf042 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Built-in {@link org.spongepowered.asm.mixin.injection.InjectionPoint + * injection point} classes. + */ +package org.spongepowered.asm.mixin.injection.points; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java new file mode 100644 index 00000000..c126bc42 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Dynamic target selectors provide custom logic for selecting injector targets. + */ +package org.spongepowered.asm.mixin.injection.selectors.dynamic; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java new file mode 100644 index 00000000..d50ea83a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Target selectors are consumed by injectors and injection points when + * identifying target members in a class or inside a method, see {@link + * org.spongepowered.asm.mixin.injection.selectors.ITargetSelector}. + */ +package org.spongepowered.asm.mixin.injection.selectors; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index 37df0ee0..fa59165c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -48,43 +48,51 @@ import com.google.common.base.Objects; import com.google.common.base.Strings; /** - *

Target selector, also used as a general-purpose information bundle about a - * member (method or field) parsed from a String token in another annotation, - * this is used where target members need to be specified as Strings in order to - * parse the String representation to something useful. See - * {@link ITargetSelector} for other supported selector types.

+ *

Struct which defines an Explcit Target selector, See + * {@link ITargetSelector} for other supported selector types. This struct is + * also used as a general-purpose information bundle about a member (method or + * field) parsed from a String token in another annotation, this is used where + * target members need to be specified as Strings in order to parse the String + * representation to something useful.

* *

Some examples:

*
- *   // references a method or field called func_1234_a, if there are multiple
- *   // members with the same signature, matches the first occurrence
- *   func_1234_a
+ *   // references a method or field called func_1234_a, if there are
+ *   // multiple members with the same signature, matches the first occurrence
+ *   func_1234_a
  *   
- *   // references a method or field called func_1234_a, if there are multiple
- *   // members with the same signature, matches all occurrences
+ *   // references a method or field called func_1234_a, if there are
+ *   // multiple members with matching name, matches all occurrences
  *   func_1234_a*
  *   
- *   // references a method called func_1234_a which takes 3 ints and returns
- *   // a bool
+ *   // references all methods which take 3 ints and return a bool
+ *   *(III)Z
+ *   
+ *   // references a method called func_1234_a which takes 3 ints and
+ *   // returns a bool
  *   func_1234_a(III)Z
  *   
- *   // references a field called field_5678_z which is a String
+ *   // references a field called field_5678_z which is a String
  *   field_5678_z:Ljava/lang/String;
  *   
- *   // references a ctor which takes a single String argument 
+ *   // references a ctor which takes a single String argument 
  *   <init>(Ljava/lang/String;)V
  *   
- *   // references a method called func_1234_a in class foo.bar.Baz
+ *   // references a method called func_1234_a in class foo.bar.Baz
  *   Lfoo/bar/Baz;func_1234_a
  *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   Lcom/example/Dave;field_5678_z
+ *   // references a field called field_5678_z in class com.example.Dave
+ *   Lcom/example/Dave;field_5678_z
  *  
- *   // references a method called func_1234_a in class foo.bar.Baz which takes
- *   // three doubles and returns void
+ *   // references a field called field_5678_z in class com.example.Dave
+ *   // which is of type String
+ *   Lcom/example/Dave;field_5678_z:Ljava/lang/String;
+ *  
+ *   // references a method called func_1234_a in class foo.bar.Baz which
+ *   // takes three doubles and returns void
  *   Lfoo/bar/Baz;func_1234_a(DDD)V
  *   
- *   // alternate syntax for the same
+ *   // alternate syntax for the same
  *   foo.bar.Baz.func_1234_a(DDD)V
*
*/ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java new file mode 100644 index 00000000..e4138056 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal data bundles used by injectors during application. + */ +package org.spongepowered.asm.mixin.injection.struct; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java new file mode 100644 index 00000000..a1a3d686 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Throwable classes (errors and exceptions) for injectors. + */ +package org.spongepowered.asm.mixin.injection.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/package-info.java b/src/main/java/org/spongepowered/asm/mixin/package-info.java new file mode 100644 index 00000000..08b2b9c2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/package-info.java @@ -0,0 +1,34 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Primary interaction points ( + * {@link org.spongepowered.asm.mixin.Mixin @Mixin} and + * {@link org.spongepowered.asm.mixin.MixinEnvironment @MixinEnvironment}) + * and annotations (eg. + * {@link org.spongepowered.asm.mixin.Mixin @Mixin}, + * {@link org.spongepowered.asm.mixin.Shadow @Shadow}) for mixin consumers. + */ +package org.spongepowered.asm.mixin; diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java b/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java new file mode 100644 index 00000000..19669c41 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Refmaps are data bundles which map string references to obfuscated + * counterparts at runtime, see {@link + * org.spongepowered.asm.mixin.refmap.ReferenceMapper}. + */ +package org.spongepowered.asm.mixin.refmap; diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java b/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java new file mode 100644 index 00000000..ec338bc3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal data bundles used by mixin during application. + */ +package org.spongepowered.asm.mixin.struct; diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java new file mode 100644 index 00000000..aa5cc880 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin throwables and throwable base classes. + */ +package org.spongepowered.asm.mixin.throwables; 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 8eb20a93..097149e7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -112,9 +112,9 @@ public final class ClassInfo { } /** - * When using {@link ClassInfo#forType}, determines whether an array type - * should be returned as declared (eg. as Object) or whether the - * element type should be returned instead. + * When using {@link ClassInfo#forType ClassInfo.forType}, determines + * whether an array type should be returned as declared (eg. as Object + * ) or whether the element type should be returned instead. */ public static enum TypeLookup { @@ -974,7 +974,7 @@ public final class ClassInfo { return this.name; } - public MethodMapper getMethodMapper() { + MethodMapper getMethodMapper() { return this.methodMapper; } 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 5e567f3f..2ff9d94e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -42,7 +42,7 @@ import org.spongepowered.asm.util.Annotations; * Information about an interface being runtime-patched onto a mixin target * class, see {@link org.spongepowered.asm.mixin.Implements Implements} */ -public final class InterfaceInfo { +final class InterfaceInfo { /** * Parent mixin diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java index 55baab6d..1e298a57 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java @@ -44,7 +44,7 @@ import com.google.common.base.Strings; /** * Maintains method remaps for a target class */ -public class MethodMapper { +class MethodMapper { /** * Logger diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 86d82b28..68043f0e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -69,7 +69,7 @@ import org.spongepowered.asm.util.perf.Profiler.Section; /** * Heart of the Mixin pipeline */ -public class MixinProcessor { +class MixinProcessor { /** * Phase during which an error occurred, delegates to functionality in diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java new file mode 100644 index 00000000..9f661b44 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline extensions. + */ +package org.spongepowered.asm.mixin.transformer.ext.extensions; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java new file mode 100644 index 00000000..16d1fa4d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline extension interface and registry of + * active extensions. + */ +package org.spongepowered.asm.mixin.transformer.ext; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java new file mode 100644 index 00000000..9d6a3b8b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Meta annotations applied by the mixin processor to fingerprint mixin actions. + */ +package org.spongepowered.asm.mixin.transformer.meta; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java new file mode 100644 index 00000000..34f240d9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline classes. + */ +package org.spongepowered.asm.mixin.transformer; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java new file mode 100644 index 00000000..cd3fafb2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin transformation pipeline throwables. + */ +package org.spongepowered.asm.mixin.transformer.throwables; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java new file mode 100644 index 00000000..da35f651 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings. + */ +package org.spongepowered.asm.obfuscation.mapping.common; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java new file mode 100644 index 00000000..b18be912 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings with specific behaviour for ForgeGradle + * 3 and above. + */ +package org.spongepowered.asm.obfuscation.mapping.fg3; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java new file mode 100644 index 00000000..a12457a2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings with specific behaviour for MCP + */ +package org.spongepowered.asm.obfuscation.mapping.mcp; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java new file mode 100644 index 00000000..ea731a55 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Interface for structs for method and field mappings. + */ +package org.spongepowered.asm.obfuscation.mapping; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/package-info.java new file mode 100644 index 00000000..4aa77ff4 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Obfuscation-related structs for interoperability with the annotation + * processor and runtime obfuscation utilities. + */ +package org.spongepowered.asm.obfuscation; diff --git a/src/main/java/org/spongepowered/asm/package-info.java b/src/main/java/org/spongepowered/asm/package-info.java new file mode 100644 index 00000000..41b69dd0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * The Mixin runtime and utilities. + */ +package org.spongepowered.asm; diff --git a/src/main/java/org/spongepowered/asm/service/package-info.java b/src/main/java/org/spongepowered/asm/service/package-info.java new file mode 100644 index 00000000..39cc7d8f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin service interface, with base classes for all the moving parts of the + * Mixin transformation pipeline and supporting infrastructure. Abstracted here + * and implemented by platform-specific modules. + */ +package org.spongepowered.asm.service; diff --git a/src/main/java/org/spongepowered/asm/transformers/package-info.java b/src/main/java/org/spongepowered/asm/transformers/package-info.java new file mode 100644 index 00000000..ea62595f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/transformers/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Specialised ASM utility and base classes used by the mixin processor. + */ +package org.spongepowered.asm.transformers; diff --git a/src/main/java/org/spongepowered/asm/util/asm/package-info.java b/src/main/java/org/spongepowered/asm/util/asm/package-info.java new file mode 100644 index 00000000..6fe9322f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Utilities, abstractions and specialised subclasses used by Mixin for + * interacting with ASM. + */ +package org.spongepowered.asm.util.asm; diff --git a/src/main/java/org/spongepowered/asm/util/logging/package-info.java b/src/main/java/org/spongepowered/asm/util/logging/package-info.java new file mode 100644 index 00000000..387fd39f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/logging/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Logging abstraction to provide a unified logging interface for classes which + * operate both at runtime and in the AP. + */ +package org.spongepowered.asm.util.logging; diff --git a/src/main/java/org/spongepowered/asm/util/package-info.java b/src/main/java/org/spongepowered/asm/util/package-info.java new file mode 100644 index 00000000..1ab1784e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Utility classes used by the entire Mixin pipeline, including utilities for + * working with bytecode as well as general-purpose tools and parsers. + */ +package org.spongepowered.asm.util; diff --git a/src/main/java/org/spongepowered/asm/util/perf/package-info.java b/src/main/java/org/spongepowered/asm/util/perf/package-info.java new file mode 100644 index 00000000..2c054f95 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/perf/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Performance profiling for Mixin. + */ +package org.spongepowered.asm.util.perf; From ae5bb845dae76b910ec42a10954763884e9bad44 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 6 Feb 2021 01:17:07 +0000 Subject: [PATCH 17/42] Update checkstyle --- build.gradle | 2 +- checkstyle.xml | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 835530b1..dce3a615 100644 --- a/build.gradle +++ b/build.gradle @@ -238,7 +238,7 @@ checkstyle { "year" : project.inceptionYear ] configFile = file("checkstyle.xml") - toolVersion = '8.25' + toolVersion = '8.36.1' } // Source compiler configuration diff --git a/checkstyle.xml b/checkstyle.xml index ea6a9e1d..fd6970e0 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -92,9 +92,7 @@ - - @@ -104,9 +102,7 @@ - - From 6f35fe1ded84994967486f128d81eb884b065904 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 14 Feb 2021 21:33:06 +0000 Subject: [PATCH 18/42] Finalise desc selector and javadoc, enhancements to explicit selector --- docs/javadoc/mixin.css | 37 +- .../tools/obfuscation/AnnotatedMixin.java | 1 - .../AnnotatedMixinElementHandler.java | 20 +- .../AnnotatedMixinElementHandlerInjector.java | 181 +++---- .../obfuscation/ObfuscationEnvironment.java | 3 +- .../obfuscation/mirror/AnnotationHandle.java | 7 + .../asm/mixin/gen/AccessorInfo.java | 3 +- .../asm/mixin/gen/InvokerInfo.java | 4 +- .../asm/mixin/injection/Desc.java | 30 ++ .../asm/mixin/injection/InjectionPoint.java | 3 +- .../asm/mixin/injection/code/Injector.java | 3 +- .../injection/invoke/RedirectInjector.java | 2 +- .../mixin/injection/points/BeforeInvoke.java | 51 +- .../injection/selectors/ITargetSelector.java | 138 +++++- .../selectors/ITargetSelectorByName.java | 37 -- .../selectors/ITargetSelectorDynamic.java | 16 + .../selectors/ITargetSelectorRemappable.java | 37 ++ .../injection/selectors/InvalidSelector.java | 62 ++- .../injection/selectors/MemberMatcher.java | 23 +- .../injection/selectors/TargetSelector.java | 183 ++++++- .../selectors/dynamic/DescriptorResolver.java | 43 +- .../dynamic/DynamicSelectorDesc.java | 171 ++++++- .../dynamic/IResolvedDescriptor.java | 6 + .../SelectorConstraintException.java} | 34 +- .../throwables/SelectorException.java | 59 +++ .../selectors/throwables/package-info.java | 29 ++ .../mixin/injection/struct/InjectionInfo.java | 106 ++-- .../injection/struct/InjectionPointData.java | 2 +- .../injection/struct/InjectorGroupInfo.java | 3 +- .../InvalidMemberDescriptorException.java | 14 +- .../mixin/injection/struct/MemberInfo.java | 453 +++++++++++++----- .../asm/mixin/transformer/MixinConfig.java | 7 + .../asm/mixin/transformer/MixinInfo.java | 8 +- .../mixin/transformer/MixinPostProcessor.java | 6 + .../mixin/transformer/MixinTargetContext.java | 6 +- .../extensions/ExtensionCheckInterfaces.java | 20 +- .../spongepowered/asm/util/Annotations.java | 24 +- .../org/spongepowered/asm/util/Bytecode.java | 22 + .../spongepowered/asm/util/Quantifier.java | 214 +++++++++ .../asm/util/asm/IAnnotationHandle.java | 32 +- 40 files changed, 1672 insertions(+), 428 deletions(-) rename src/main/java/org/spongepowered/asm/mixin/injection/selectors/{dynamic/DynamicSelectorAbstract.java => throwables/SelectorConstraintException.java} (61%) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java create mode 100644 src/main/java/org/spongepowered/asm/util/Quantifier.java diff --git a/docs/javadoc/mixin.css b/docs/javadoc/mixin.css index fbebec3a..87631c8f 100644 --- a/docs/javadoc/mixin.css +++ b/docs/javadoc/mixin.css @@ -72,7 +72,7 @@ table.infoTable { border-collapse: collapse; } -table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th { +table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th, table.selectorTable td, table.selectorTable th { padding: 6px 8px; background-color: #F0F0F0; } @@ -81,11 +81,44 @@ table.cellTable th, table.cellTable td { text-align: center; } -table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th { +table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th, table.selectorTable th, table.selectorTable td.th { background-color: #CCC; font-weight: bold; } +table.selectorTable tbody td, table.selectorTable thead th { + border-left: 6px solid #FFF; +} + +table.selectorTable tbody td { + font-family: 'Consolas', monospace; +} + +table.selectorTable th, table.selectorTable td.th { + background: transparent; + font-family: inherit; +} + +table.selectorTable thead th.ownr { background-color: #CFC } +table.selectorTable thead th.name { background-color: #CCF } +table.selectorTable thead th.quan { background-color: #FFC } +table.selectorTable thead th.desc { background-color: #FCC } + +table.selectorTable tbody td.ownr { background-color: #F0FFF0 } +table.selectorTable tbody td.name { background-color: #F0F0FF } +table.selectorTable tbody td.quan { background-color: #FFFFF0 } +table.selectorTable tbody td.desc { background-color: #FFF0F0 } + +span.aownr { background-color: #DFD } +span.aname { background-color: #DDF } +span.aquan { background-color: #FFD } +span.adesc { background-color: #FDD } + +span.ownr {color: #090 } +span.name {color: #009 } +span.quan {color: #990 } +span.desc {color: #900 } + a[name] { color: #353833; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 2143f37d..dc31d05b 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -384,7 +384,6 @@ class AnnotatedMixin implements IMixinContext, IAnnotatedElement { } public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) { - System.err.printf(">>> %s\n", method); this.methods.remove(method); AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap); this.injectors.registerInjector(injectorElement); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 0d715188..cd24aad5 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -143,6 +143,11 @@ abstract class AnnotatedMixinElementHandler { public IAnnotationHandle getAnnotation(Class annotationClass) { return AnnotationHandle.of(AnnotatedElementExecutable.this.getElement(), annotationClass); } + + @Override + public String toString() { + return AnnotatedElementExecutable.this.getElement().getSimpleName().toString(); + } }; } @@ -161,6 +166,11 @@ abstract class AnnotatedMixinElementHandler { return reference; } + @Override + public String toString() { + return TypeUtils.getName(this.element); + } + } /** @@ -545,12 +555,12 @@ abstract class AnnotatedMixinElementHandler { * Checks whether the referenced method exists in all targets and raises * warnings where appropriate */ - protected final void validateReferencedTarget(ExecutableElement method, AnnotationHandle inject, ITargetSelector reference, String type) { - if (!(reference instanceof ITargetSelectorByName)) { + protected final void validateReferencedTarget(AnnotatedElementExecutable elem, String reference, ITargetSelector targetSelector, String subject) { + if (!(targetSelector instanceof ITargetSelectorByName)) { return; } - ITargetSelectorByName nameRef = (ITargetSelectorByName)reference; + ITargetSelectorByName nameRef = (ITargetSelectorByName)targetSelector; String signature = nameRef.toDescriptor(); for (TypeHandle target : this.mixin.getTargets()) { @@ -560,8 +570,8 @@ abstract class AnnotatedMixinElementHandler { MethodHandle targetMethod = target.findMethod(nameRef.getName(), signature); if (targetMethod == null) { - this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), - SuppressedBy.TARGET); + this.ap.printMessage(Kind.WARNING, "Cannot find target method \"" + nameRef.getName() + nameRef.getDesc() + "\" for " + subject + + " in " + target, elem.getElement(), elem.getAnnotation().asMirror(), SuppressedBy.TARGET); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 6d88dda8..ba36a3a4 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -40,6 +40,7 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; @@ -125,6 +126,11 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler public AnnotationHandle getAt() { return this.at; } + + public AnnotationMirror getAtErrorElement(CompilerEnvironment compilerEnvironment) { + // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work + return (compilerEnvironment == CompilerEnvironment.JDT ? this.getAt() : this.getAnnotation()).asMirror(); + } @Override public IAnnotationHandle getSelectorAnnotation() { @@ -183,33 +189,38 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } for (String reference : elem.getAnnotation().getList("method")) { - ITargetSelector targetSelector = TargetSelector.parse(reference, elem); - - try { - targetSelector.validate(); - } catch (InvalidMemberDescriptorException ex) { - elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); - } + this.registerInjectorTarget(elem, reference, TargetSelector.parse(reference, elem), elem + ".method=\"" + reference + "\""); + } + + for (IAnnotationHandle desc : elem.getAnnotation().getAnnotationList("target")) { + String subject = String.format("%s.target=@Desc(id = \"%s\")", elem, desc.getValue("id", "")); + this.registerInjectorTarget(elem, null, TargetSelector.parse(desc, elem), subject); + } + } + + private void registerInjectorTarget(AnnotatedElementInjector elem, String reference, ITargetSelector targetSelector, String subject) { + try { + targetSelector.validate(); + } catch (InvalidSelectorException ex) { + elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); + } - if (!(targetSelector instanceof ITargetSelectorRemappable)) { - continue; - } - - ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; - if (targetMember.getName() == null) { - continue; - } - - if (targetMember.getDesc() != null) { - this.validateReferencedTarget(elem.getElement(), elem.getAnnotation(), targetMember, elem.toString()); - } - - if (!elem.shouldRemap()) { - continue; - } - + if (!(targetSelector instanceof ITargetSelectorByName)) { + return; + } + + ITargetSelectorByName targetMember = (ITargetSelectorByName)targetSelector; + if (targetMember.getName() == null) { + return; + } + + if (targetMember.getDesc() != null) { + this.validateReferencedTarget(elem, reference, targetMember, subject); + } + + if (targetSelector instanceof ITargetSelectorRemappable && elem.shouldRemap()) { for (TypeHandle target : this.mixin.getTargets()) { - if (!this.registerInjector(elem, reference, targetMember, target)) { + if (!this.registerInjector(elem, reference, (ITargetSelectorRemappable)targetMember, target)) { break; } } @@ -290,91 +301,87 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", elem.getElement()); } - if (!elem.shouldRemap()) { - return; - } - - String type = InjectionPointData.parseType(elem.getAt().getValue("value")); - String target = elem.getAt().getValue("target"); - - if ("NEW".equals(type)) { - this.remapNewTarget(String.format(format, type + "."), target, elem); - this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem); - } else { - this.remapReference(String.format(format, type + "."), target, elem); - } - } - - protected final void remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) { + String reference = elem.getAt().getValue("target"); if (reference == null) { return; } - + ITargetSelector selector = TargetSelector.parse(reference, elem); - if (selector instanceof ITargetSelectorConstructor) { - ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; - String target = member.toCtorType(); - - if (target != null) { - String desc = member.toCtorDesc(); - MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); - ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); - if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) { - this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), - elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); - return; - } - - ObfuscationData mappings = new ObfuscationData(); - for (ObfuscationType type : remapped) { - MappingMethod mapping = remapped.get(type); - if (desc == null) { - mappings.put(type, mapping.getOwner()); - } else { - mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); - } - } + + try { + selector.validate(); + } catch (InvalidMemberDescriptorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment())); + } + + if (elem.shouldRemap()) { + String type = InjectionPointData.parseType(elem.getAt().getValue("value")); + if ("NEW".equals(type)) { + String classReference = elem.getAtArg("class"); + ITargetSelector classSelector = TargetSelector.parse(classReference, elem); - this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + this.remapNewTarget(String.format(format, type + "."), reference, selector, elem); + this.remapNewTarget(String.format(format, type + ".args[class]"), classReference, classSelector, elem); + } else { + this.remapReference(String.format(format, type + "."), reference, selector, elem); } } + } + + protected final void remapNewTarget(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) { + if (!(selector instanceof ITargetSelectorConstructor)) { + return; + } + + ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; + String target = member.toCtorType(); + + if (target != null) { + String desc = member.toCtorDesc(); + MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); + ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); + if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) { + this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), + elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); + return; + } + ObfuscationData mappings = new ObfuscationData(); + for (ObfuscationType type : remapped) { + MappingMethod mapping = remapped.get(type); + if (desc == null) { + mappings.put(type, mapping.getOwner()); + } else { + mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); + } + } + + this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + } + elem.notifyRemapped(); } - protected final void remapReference(String subject, String reference, AnnotatedElementInjectionPoint elem) { - if (reference == null) { + protected final void remapReference(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) { + if (!(selector instanceof ITargetSelectorRemappable)) { return; } - - ITargetSelector targetSelector = TargetSelector.parse(reference, elem); - if (!(targetSelector instanceof ITargetSelectorRemappable)) { - return; - } - ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; - - // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work - AnnotationMirror errorsOn = (this.ap.getCompilerEnvironment() == CompilerEnvironment.JDT ? elem.getAt() : elem.getAnnotation()).asMirror(); + ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)selector; + AnnotationMirror errorElement = elem.getAtErrorElement(this.ap.getCompilerEnvironment()); if (!targetMember.isFullyQualified()) { String missing = targetMember.getOwner() == null ? (targetMember.getDesc() == null ? "owner and signature" : "owner") : "signature"; - this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorsOn); + this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorElement); return; } - try { - targetMember.validate(); - } catch (InvalidMemberDescriptorException ex) { - this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), errorsOn); - } - try { if (targetMember.isField()) { ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); if (obfFieldData.isEmpty()) { if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, SuppressedBy.MAPPING); + errorElement, SuppressedBy.MAPPING); } return; } @@ -384,7 +391,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (obfMethodData.isEmpty()) { if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, SuppressedBy.MAPPING); + errorElement, SuppressedBy.MAPPING); } return; } @@ -394,7 +401,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler // Since references are fully-qualified, it shouldn't be possible for there to be multiple mappings, however // we catch and log the error in case something weird happens in the mapping provider this.ap.printMessage(Kind.ERROR, "Unexpected reference conflict for " + subject + ": " + reference + " -> " - + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorsOn); + + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorElement); return; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java index 8cf91fc3..40d68279 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java @@ -37,7 +37,6 @@ import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.ObfuscationUtil; @@ -281,7 +280,7 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment } } - return transformed ? new MemberInfo(method.getName(), owner, desc, method.getMatchCount() > 1) : null; + return transformed ? method.move(owner).transform(desc) : null; } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index 63890786..638c0ad2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -80,6 +80,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * * @return true if the annotation exists */ + @Override public boolean exists() { return this.annotation != null; } @@ -239,6 +240,12 @@ public final class AnnotationHandle implements IAnnotationHandle { return Collections.unmodifiableList(annotations); } + @Override + public Type getTypeValue(String key) { + TypeMirror typeMirror = this.getValue(key); + return typeMirror == null ? Type.VOID_TYPE : Type.getType(TypeUtils.getInternalName(typeMirror)); + } + @Override public List getTypeList(String key) { List list = this.getList(key); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index 225d544f..e85b9a20 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; @@ -509,7 +510,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return best match */ protected TNode findTarget(List> nodes) { - Result result = TargetSelector.run(this.target.configure("orphan"), nodes); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), nodes); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java index cde243e7..ed2b4b68 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -28,6 +28,7 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; @@ -102,7 +103,8 @@ class InvokerInfo extends AccessorInfo { } private MethodNode findTargetMethod() { - Result result = TargetSelector.run(this.target.configure("orphan"), ElementNode.methodList(this.classNode)); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), + ElementNode.methodList(this.classNode)); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java index 5a9613dd..50fd27d1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -111,4 +111,34 @@ public @interface Desc { */ public Class[] args() default { }; + /** + * The minimum number of times this selector should match. By default the + * selector is allowed to match no targets. When selecting fields or methods + * setting this value to anything other than 0 or 1 is pointless since the + * member can either be present or absent. However when matching method + * calls or field accesses (eg. when using this value inside + * {@link At#desc @At.desc}) this allows a minimum number of matches to + * be specified in order to provide early validation that the selector + * matched the correct number of candidates. To specify an exact number of + * matches, set {@link #max max} to the same value as min. Values + * less than zero are ignored since selectors cannot match a negative number + * of times. + */ + public int min() default 0; + + /** + * The maximum number of times this selector can match. By default the + * selector is allowed to match an unlimited number of targets. When + * selecting fields or methods, setting this value to anything other than 1 + * is pointless since the member can either be present or absent. However + * when matching method calls or field accesses (eg. when + * using this value inside {@link At#desc @At.desc}) this allows a + * maximum number of matches to be specified in order to limit the number of + * times that the selector can match candidates. To specify an exact number + * of matches, set max to the same value as {@link #min min}. + * Values less than 1 are treated as Integer.MAX_VALUE (the + * default) since setting a value of 0 or less has no meaning. + */ + public int max() default Integer.MAX_VALUE; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 5a2f332e..d9c371f0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -58,6 +58,7 @@ import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionExceptio import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.IMessageSink; @@ -720,7 +721,7 @@ public abstract class InjectionPoint { if (ipClass == null) { if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { try { - ipClass = (Class)Class.forName(type); + ipClass = (Class)MixinService.getService().getClassProvider().findClass(type); InjectionPoint.types.put(type, ipClass); } catch (Exception ex) { throw new InvalidInjectionException(context, data + " could not be loaded or is not a valid InjectionPoint", ex); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 633649ec..9a2b54f3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -620,12 +620,13 @@ public abstract class Injector { * @param exceptionType Type of exception to throw (binary name) * @param message Message to pass to the exception constructor */ - protected void throwException(InsnList insns, String exceptionType, String message) { + protected void throwException(InsnList insns, Extension extraStack, String exceptionType, String message) { insns.add(new TypeInsnNode(Opcodes.NEW, exceptionType)); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new LdcInsnNode(message)); insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, exceptionType, "", "(Ljava/lang/String;)V", false)); insns.add(new InsnNode(Opcodes.ATHROW)); + extraStack.add(3); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index 6e6d1967..efaf1860 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -774,7 +774,7 @@ public class RedirectInjector extends InvokeInjector { LabelNode nullCheckSucceeded = new LabelNode(); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded)); - this.throwException(insns, RedirectInjector.NPE, String.format("%s %s %s returned null for %s", + this.throwException(insns, extraStack, RedirectInjector.NPE, String.format("%s %s %s returned null for %s", this.annotationType, type, this, value)); insns.add(nullCheckSucceeded); extraStack.add(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index 406cceb4..ffb250e4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -35,10 +35,13 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -108,7 +111,12 @@ public class BeforeInvoke extends InjectionPoint { /** * */ - protected final IMixinContext context; + protected final IInjectionPointContext context; + + /** + * + */ + protected final IMixinContext mixin; /** * Logger reference @@ -127,9 +135,10 @@ public class BeforeInvoke extends InjectionPoint { this.ordinal = data.getOrdinal(); this.log = data.get("log", false); this.className = this.getClassName(); - this.context = data.getMixin(); - this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) - && !this.context.getReferenceMapper().isDefault(); + this.context = data.getContext(); + this.mixin = data.getMixin(); + this.allowPermissive = this.mixin.getOption(Option.REFMAP_REMAP) && this.mixin.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) + && !this.mixin.getReferenceMapper().isDefault(); } private String getClassName() { @@ -155,14 +164,14 @@ public class BeforeInvoke extends InjectionPoint { */ @Override public boolean find(String desc, InsnList insns, Collection nodes) { - this.log("{} is searching for an injection point in method with descriptor {}", this.className, desc); + this.log("{}->{} is searching for an injection point in method with descriptor {}", this.context, this.className, desc); boolean hasDescriptor = this.target instanceof ITargetSelectorByName && ((ITargetSelectorByName)this.target).getDesc() == null; boolean found = this.find(desc, insns, nodes, this.target, SearchType.STRICT); if (!found && hasDescriptor && this.allowPermissive) { this.logger.warn("STRICT match for {} using \"{}\" in {} returned 0 results, attempting permissive search. " - + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.context); + + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.mixin); found = this.find(desc, insns, nodes, this.target, SearchType.PERMISSIVE); } @@ -174,10 +183,10 @@ public class BeforeInvoke extends InjectionPoint { return false; } - ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector; + ITargetSelector target = (searchType == SearchType.PERMISSIVE ? selector.configure(Configure.PERMISSIVE) : selector) + .configure(Configure.SELECT_INSTRUCTION); - int ordinal = 0; - int found = 0; + int ordinal = 0, found = 0, matchCount = 0; ListIterator iter = insns.iterator(); while (iter.hasNext()) { @@ -185,23 +194,22 @@ public class BeforeInvoke extends InjectionPoint { if (this.matchesInsn(insn)) { MemberInfo nodeInfo = new MemberInfo(insn); - this.log("{} is considering insn {}", this.className, nodeInfo); + this.log("{}->{} is considering {}", this.context, this.className, nodeInfo); if (target.match(insn).isExactMatch()) { - this.log("{} > found a matching insn, checking preconditions...", this.className); + this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className); + if (++matchCount > selector.getMaxMatchCount()) { + break; + } if (this.matchesOrdinal(ordinal)) { - this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal); + this.log("{}->{} > > > found a matching insn at ordinal {}", this.context, this.className, ordinal); if (this.addInsn(insns, nodes, insn)) { found++; } - - if (this.ordinal == ordinal) { - break; - } } - + ordinal++; } } @@ -211,7 +219,12 @@ public class BeforeInvoke extends InjectionPoint { if (searchType == SearchType.PERMISSIVE && found > 1) { this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. " - + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found); + + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.mixin, found); + } + + if (matchCount < selector.getMinMatchCount()) { + throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)", + selector, selector.getMinMatchCount(), matchCount)); } return found > 0; @@ -231,7 +244,7 @@ public class BeforeInvoke extends InjectionPoint { } protected boolean matchesOrdinal(int ordinal) { - this.log("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal); + this.log("{}->{} > > comparing target ordinal {} with current ordinal {}", this.context, this.className, this.ordinal, ordinal); return this.ordinal == -1 || this.ordinal == ordinal; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index f385c897..642a41ab 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -25,6 +25,8 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; +import org.spongepowered.asm.mixin.injection.Desc; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.util.asm.ElementNode; @@ -40,6 +42,11 @@ import org.spongepowered.asm.util.asm.ElementNode; * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the * supported variants and examples.

* + *
+ * // An example explicit target selector
+ * Lfully/qualified/OwnerClass;methodName*(III)V + *
+ * *

Pattern Target Selectors (Regex Selectors)

* *

Pattern Target Selectors are handled internally using @@ -47,26 +54,48 @@ import org.spongepowered.asm.util.asm.ElementNode; * supported variants and examples. Pattern Selectors always end with a forward * slash character.

* + *
+ * // Matches candidates ending with "Bar" and which take a single int + *
+ * /bar$/ desc=/^\\(I\\)/
+ *
+ * // The same example but with "name" explicitly specified (optional) + *
+ * name=/bar$/ desc=/^\\(I\\)/
+ *
+ * // Matches candidates whose name contains "Entity"
+ * /Entity/ + *
+ * *

Dynamic Target Selectors

* *

Dynamic Target Selectors can be built-in or user-supplied types - * with their own specialised syntax or behaviour. Dynamic selectors are - * specified in the following format, and can be recognised by the fact that - * the selector string starts with "@":

+ * with their own specialised syntax or behaviour.

+ * + *

Built-in dynamic selectors:

+ * + *
    + *
  • {@link DynamicSelectorDesc @Desc Selector}: Selector which uses + * descriptors defined in {@link Desc @Desc} annotations
  • + *
+ * + *

Dynamic selectors are specified in the following format, and can be + * recognised by the fact that the selector string starts with "@": + *

* *
- *   // Built-in dynamic selector without argument string
- *   @SelectorId
+ * // Built-in dynamic selector without argument string
+ * @SelectorId
  *   
- *   // Built-in dynamic selector with empty argument string
- *   @SelectorId()
+ * // Built-in dynamic selector with empty argument string
+ * @SelectorId()
  *   
- *   // Built-in dynamic selector with argument
- *   @SelectorId(custom,argument,string,in,any,format)
+ * // Built-in dynamic selector with argument
+ * @SelectorId(custom,argument,string,in,any,format)
  *   
- *   // User-provided dynamic selector with argument. Note that
- *   // user-provided dynamic selectors are namespaced to avoid conflicts.
- *   @Namespace:SelectorId(some arguments)
+ * // User-provided dynamic selector with argument. Note that + * // user-provided dynamic selectors are namespaced to avoid conflicts. + * @Namespace:SelectorId(some arguments)
*
* *

The exact format of the argument string is specified by the dynamic @@ -76,6 +105,67 @@ import org.spongepowered.asm.util.asm.ElementNode; */ public interface ITargetSelector { + /** + * Available selector reconfigurations + */ + public enum Configure { + + /** + * Configure this selector for matching members in a class. Usually used + * to set defaults for match limits based on role. + */ + SELECT_MEMBER(0), + + /** + * Configure this selector for matching field and method instructions in + * a method body. Usually used to set defaults for match limits. + */ + SELECT_INSTRUCTION(0), + + /** + * Where supported, changes the owner selection to the specified value. + */ + MOVE(1), + + /** + * Where supported, changes the owner selection to match all owners, + * retaining other properties. + */ + ORPHAN(0), + + /** + * Where supported, changes the descriptor to the specified value. + */ + TRANSFORM(1), + + /** + * Where supported, changes the descriptor to match all target + * descriptors, retaining other properties + */ + PERMISSIVE(0), + + /** + * Where supported, removes the min and max limits for the selector, + * allowing it to return as many or as few matches as required. + */ + CLEAR_LIMITS(0); + + private int requiredArgs; + + private Configure(int requiredArgs) { + this.requiredArgs = requiredArgs; + } + + public void checkArgs(String... args) throws IllegalArgumentException { + int argc = args == null ? 0 : args.length; + if (argc < this.requiredArgs) { + throw new IllegalArgumentException("Insufficient arguments for " + this.name() + " mutation. Required " + this.requiredArgs + + " but received " + argc); + } + } + + } + /** * Get the next target selector in this path (or null if this * selector is the last selector in the chain. Called at recurse points in @@ -90,19 +180,22 @@ public interface ITargetSelector { * supplied arguments. Results from this method should be idempotent in * terms of the configuration of the returned object, but do not have to * necessarily return the same object if the callee already matches the - * supplied configuration, though this is generally the case. + * supplied configuration, or if the requested mutation is not supported by + * the selector, though this is generally the case. * - *

In other words, calling configure("foo") when this object is - * already configured according to "foo" may simply return this - * object, or might return an identically-configured copy.

+ *

In other words, calling configure(Configure.ORPHAN) when this + * object is already an orphan or does not support orphaning, may + * simply return this object, or might return an identically-configured + * copy.

* - *

Must not return null

+ *

Must not return null, defaults to returning unmodified selector.

* + * @param request Requested operation * @param args Configuration arguments * @return Configured selector, may return this selector if the specified * condition is already satisfied */ - public abstract ITargetSelector configure(String... args); + public abstract ITargetSelector configure(Configure request, String... args); /** * Perform basic sanity-check validation of the selector, checks that the @@ -126,9 +219,14 @@ public interface ITargetSelector { public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException; /** - * Number of candidates which this selector should match + * Minimum number of candidates this selector must match */ - public abstract int getMatchCount(); + public abstract int getMinMatchCount(); + + /** + * Maximum number of candidates this selector can match + */ + public abstract int getMaxMatchCount(); /** * Test whether this selector matches the supplied element node diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java index c1c9d803..ccfb1299 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java @@ -44,43 +44,6 @@ public interface ITargetSelectorByName extends ITargetSelector { */ public abstract String getDesc(); - /** - * Get whether this reference is fully qualified - * - * @return true if all components of this reference are non-null - */ - public abstract boolean isFullyQualified(); - - /** - * Get whether this target selector is definitely a field, the output of - * this method is undefined if {@link #isFullyQualified} returns false. - * - * @return true if this is definitely a field - */ - public abstract boolean isField(); - - /** - * Get whether this member represents a constructor - * - * @return true if member name is <init> - */ - public abstract boolean isConstructor(); - - /** - * Get whether this selector represents a class initialiser - * - * @return true if member name is <clinit> - */ - public abstract boolean isClassInitialiser(); - - /** - * Get whether this selector represents a constructor or class initialiser - * - * @return true if member name is <init> or - * <clinit> - */ - public abstract boolean isInitialiser(); - /** * Get a representation of this selector as a complete descriptor */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java index 234a5f43..e9ffee8e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -58,5 +59,20 @@ public interface ITargetSelectorDynamic extends ITargetSelector { public String value(); } + + /** + * Decoration for subclasses which indicates an annotation type from which + * the selector can be parsed. + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface SelectorAnnotation { + + /** + * Annotation type for the selector + */ + public Class value(); + + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java index 55780b59..9cc3253d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java @@ -33,7 +33,44 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; * service */ public interface ITargetSelectorRemappable extends ITargetSelectorByName { + + /** + * Get whether this reference is fully qualified + * + * @return true if all components of this reference are non-null + */ + public abstract boolean isFullyQualified(); + + /** + * Get whether this target selector is definitely a field, the output of + * this method is undefined if {@link #isFullyQualified} returns false. + * + * @return true if this is definitely a field + */ + public abstract boolean isField(); + + /** + * Get whether this member represents a constructor + * + * @return true if member name is <init> + */ + public abstract boolean isConstructor(); + /** + * Get whether this selector represents a class initialiser + * + * @return true if member name is <clinit> + */ + public abstract boolean isClassInitialiser(); + + /** + * Get whether this selector represents a constructor or class initialiser + * + * @return true if member name is <init> or + * <clinit> + */ + public abstract boolean isInitialiser(); + /** * Returns this selector as a {@link MappingField} or * {@link MappingMethod} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java index 519b90b4..42feb510 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -27,10 +27,21 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.util.asm.ElementNode; +/** + * Since the contract of {@link TargetSelector#parse} prohibits returing + * null, instances of this selector are returned when supplied arguments + * are unparseable in order to throw exceptions only during validation. + */ public class InvalidSelector implements ITargetSelector { + /** + * The original input string, used in error messages + */ private String input; + /** + * The cause of the parser failure, emitted from {@link #validate} + */ private Throwable cause; public InvalidSelector(Throwable cause) { @@ -45,17 +56,37 @@ public class InvalidSelector implements ITargetSelector { this.input = input; this.cause = cause; } + + @Override + public String toString() { + if (this.cause != null) { + return String.format("%s: %s", this.cause.getClass().getName(), this.cause.getMessage()); + } + return this.input; + } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #next() + */ @Override public ITargetSelector next() { return null; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #configure(ITargetSelector.Configure, java.lang.String[]) + */ @Override - public ITargetSelector configure(String... args) { + public ITargetSelector configure(Configure request, String... args) { return this; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #validate() + */ @Override public ITargetSelector validate() throws InvalidSelectorException { if (this.cause instanceof InvalidSelectorException) { @@ -71,22 +102,47 @@ public class InvalidSelector implements ITargetSelector { throw new InvalidSelectorException(message); } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #attach(ISelectorContext) + */ @Override public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { return this; } - + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMinMatchCount() + */ @Override - public int getMatchCount() { + public int getMinMatchCount() { return 0; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMaxMatchCount() + */ + @Override + public int getMaxMatchCount() { + return 0; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.spongepowered.asm.util.asm.ElementNode) + */ @Override public MatchResult match(ElementNode node) { this.validate(); return MatchResult.NONE; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.objectweb.asm.tree.AbstractInsnNode) + */ @Override public MatchResult match(AbstractInsnNode insn) { this.validate(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java index 7700e855..f3d77f03 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -121,7 +121,7 @@ public final class MemberMatcher implements ITargetSelector { * @param context selector context * @return parsed MemberMatcher */ - public static MemberMatcher parse(String input, ISelectorContext context) { + public static MemberMatcher parse(final String input, ISelectorContext context) { Matcher matcher = MemberMatcher.PATTERN.matcher(input); Pattern[] patterns = new Pattern[3]; Exception parseException = null; @@ -173,6 +173,11 @@ public final class MemberMatcher implements ITargetSelector { return this; } + @Override + public String toString() { + return this.input; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector * #next() @@ -187,7 +192,8 @@ public final class MemberMatcher implements ITargetSelector { * #configure(java.lang.String[]) */ @Override - public ITargetSelector configure(String... args) { + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); return this; } @@ -200,13 +206,22 @@ public final class MemberMatcher implements ITargetSelector { public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { return this; } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMinMatchCount() + */ + @Override + public int getMinMatchCount() { + return 0; + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #getMatchCount() + * #getMaxMatchCount() */ @Override - public int getMatchCount() { + public int getMaxMatchCount() { return Integer.MAX_VALUE; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index c255a165..f5a6815c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -24,26 +24,34 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.tools.Diagnostic.Kind; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; -import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.asm.util.logging.MessageRouter; import com.google.common.base.Strings; @@ -111,20 +119,42 @@ public final class TargetSelector { final Class type; - final Method parse; - + final Class annotation; + + final Method mdParseString, mdParseAnnotation; + DynamicSelectorEntry(String namespace, String id, Class type) throws NoSuchMethodException { this.namespace = namespace; this.id = id; this.type = type; - this.parse = type.getDeclaredMethod("parse", String.class, ISelectorContext.class); - if (!Modifier.isStatic(this.parse.getModifiers())) { + this.mdParseString = type.getDeclaredMethod("parse", String.class, ISelectorContext.class); + if (!Modifier.isStatic(this.mdParseString.getModifiers())) { throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static"); } - if (!ITargetSelectorDynamic.class.isAssignableFrom(this.parse.getReturnType())) { - throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + if (!ITargetSelectorDynamic.class.isAssignableFrom(this.mdParseString.getReturnType())) { + throw new MixinError("parse(String) method for dynamic target selector [" + this.type.getName() + "] must return an ITargetSelectorDynamic subtype"); } + + Class annotation = null; + Method mdParseAnnotation = null; + + SelectorAnnotation selectorAnnotation = type.getAnnotation(SelectorAnnotation.class); + if (selectorAnnotation != null) { + annotation = selectorAnnotation.value(); + mdParseAnnotation = type.getDeclaredMethod("parse", IAnnotationHandle.class, ISelectorContext.class); + + if (!Modifier.isStatic(mdParseAnnotation.getModifiers())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static"); + } + if (!ITargetSelectorDynamic.class.isAssignableFrom(mdParseAnnotation.getReturnType())) { + throw new MixinError("parse(Annotation) method for dynamic target selector [" + this.type.getName() + + "] must return an ITargetSelectorDynamic subtype"); + } + } + + this.annotation = annotation; + this.mdParseAnnotation = mdParseAnnotation; } String getCode() { @@ -132,8 +162,16 @@ public final class TargetSelector { } ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException { + return this.parse(input, context, this.mdParseString); + } + + ITargetSelectorDynamic parse(IAnnotationHandle input, ISelectorContext context) throws ReflectiveOperationException { + return this.parse(input, context, this.mdParseAnnotation); + } + + ITargetSelectorDynamic parse(Object input, ISelectorContext context, Method parseMethod) throws ReflectiveOperationException { try { - return (ITargetSelectorDynamic)this.parse.invoke(null, input, context); + return (ITargetSelectorDynamic)parseMethod.invoke(null, input, context); } catch (InvocationTargetException itex) { Throwable cause = itex.getCause(); if (cause instanceof MixinException) { @@ -234,6 +272,18 @@ public final class TargetSelector { TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry); } + /** + * Parse a target selector from the supplied annotation and perform + * validation + * + * @param annotation Annotation to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parseAndValidate(IAnnotationHandle annotation, ISelectorContext context) throws InvalidSelectorException { + return TargetSelector.parse(annotation, context).validate(); + } + /** * Parse a target selector from a string and perform validation * @@ -241,10 +291,98 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidMemberDescriptorException { + public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidSelectorException { return TargetSelector.parse(string, context).validate(); } + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors. + * + * @param selectors Selectors to parse + * @param context Selection context + * @return parsed collection of selectors, uses LinkedHashSet to preserve + * parse ordering + */ + public static Set parseAndValidate(Iterable selectors, ISelectorContext context) throws InvalidSelectorException { + Set parsed = TargetSelector.parse(selectors, context, new LinkedHashSet()); + for (ITargetSelector selector : parsed) { + selector.validate(); + } + return parsed; + } + + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors. + * + * @param selectors Selectors to parse + * @param context Selection context + * @return parsed collection of selectors, uses LinkedHashSet to preserve + * parse ordering + */ + public static Set parse(Iterable selectors, ISelectorContext context) { + return TargetSelector.parse(selectors, context, new LinkedHashSet()); + } + + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors and store them in the + * provided collection. + * + * @param selectors Selectors to parse + * @param context Selection context + * @param parsed Collection to add parsed selectors to, initialised as a + * LinkedHashSet if null + * @return the same collection passed in via the parsed parameter, + * for convenience + */ + public static Set parse(Iterable selectors, ISelectorContext context, Set parsed) { + if (parsed == null) { + parsed = new LinkedHashSet(); + } + if (selectors != null) { + for (Object selector : selectors) { + if (selector instanceof IAnnotationHandle) { + parsed.add(TargetSelector.parse((IAnnotationHandle)selector, context)); + } else if (selector instanceof AnnotationNode) { + parsed.add(TargetSelector.parse(Annotations.handleOf(selector), context)); + } else if (selector instanceof String) { + parsed.add(TargetSelector.parse((String)selector, context)); + } else if (selector instanceof Class) { + String desc = Type.getType((Class)selector).getDescriptor(); + parsed.add(TargetSelector.parse(desc, context)); + } else if (selector != null) { + parsed.add(TargetSelector.parse(selector.toString(), context)); + } + } + } + return parsed; + } + + /** + * Parse a target selector from the supplied annotation + * + * @param annotation String to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parse(IAnnotationHandle annotation, ISelectorContext context) { + for (DynamicSelectorEntry entry : TargetSelector.dynamicSelectors.values()) { + if (entry.annotation != null && Annotations.getDesc(entry.annotation).equals(annotation.getDesc())) { + try { + return entry.parse(annotation, context); + } catch (ReflectiveOperationException ex) { + return new InvalidSelector(ex.getCause()); + } catch (Exception ex) { + return new InvalidSelector(ex); + } + } + } + + return new InvalidSelector(new InvalidSelectorException("Dynamic selector for annotation " + annotation + " is not registered.")); + } + /** * Parse a target selector from a string * @@ -313,30 +451,30 @@ public final class TargetSelector { /** * Run query on supplied target nodes * - * @param target Target selector + * @param selector Target selector * @param nodes Node collection to enumerate * @param Node type * @return query result */ - public static Result run(ITargetSelector target, List> nodes) { + public static Result run(ITargetSelector selector, List> nodes) { List candidates = new ArrayList(); - TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates); + TNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates); return new Result(exactMatch, candidates); } /** * Run query on supplied target nodes * - * @param targets Target selector + * @param selector Target selector * @param nodes Node collection to enumerate * @param Node type * @return query result */ - public static Result run(Iterable targets, List> nodes) { + public static Result run(Iterable selector, List> nodes) { TNode exactMatch = null; List candidates = new ArrayList(); - for (ITargetSelector target : targets) { + for (ITargetSelector target : selector) { TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); if (exactMatch == null) { exactMatch = selectorExactMatch; @@ -346,11 +484,16 @@ public final class TargetSelector { return new Result(exactMatch, candidates); } - private static TNode runSelector(ITargetSelector target, List> nodes, List candidates) { + private static TNode runSelector(ITargetSelector selector, List> nodes, List candidates) { + int matchCount = 0; TNode exactMatch = null; for (ElementNode element : nodes) { - MatchResult match = target.match(element); + MatchResult match = selector.match(element); if (match.isMatch()) { + matchCount++; + if (matchCount > selector.getMaxMatchCount()) { + break; + } TNode node = element.get(); if (!candidates.contains(node)) { candidates.add(node); @@ -360,6 +503,12 @@ public final class TargetSelector { } } } + + if (matchCount < selector.getMinMatchCount()) { + throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)", + selector, selector.getMinMatchCount(), matchCount)); + } + return exactMatch; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java index 62dd7197..8257c664 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -39,6 +39,7 @@ import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.asm.IAnnotatedElement; import org.spongepowered.asm.util.asm.IAnnotationHandle; @@ -63,20 +64,20 @@ public final class DescriptorResolver { */ private final Set searched; - /** - * Selector context - */ - private final ISelectorContext context; - /** * The resolved descriptor */ private final IAnnotationHandle desc; + + /** + * Selector context + */ + private final ISelectorContext context; - Descriptor(Set searched, ISelectorContext context, IAnnotationHandle desc) { + Descriptor(Set searched, IAnnotationHandle desc, ISelectorContext context) { this.searched = searched; - this.context = context; this.desc = desc; + this.context = context; } /** @@ -119,7 +120,7 @@ public final class DescriptorResolver { if (this.desc == null) { return Type.VOID_TYPE; } - Type ownerClass = this.desc.getValue("owner", Type.VOID_TYPE); + Type ownerClass = this.desc.getTypeValue("owner"); return ownerClass == Type.VOID_TYPE ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass; } @@ -149,7 +150,18 @@ public final class DescriptorResolver { if (this.desc == null) { return Type.VOID_TYPE; } - return this.desc.getValue("ret", Type.VOID_TYPE); + return this.desc.getTypeValue("ret"); + } + + @Override + public Quantifier getMatches() { + if (this.desc == null) { + return Quantifier.DEFAULT; + } + + int min = Math.max(0, this.desc != null ? this.desc.getValue("min", 0) : 0); + Integer max = this.desc != null ? this.desc.getValue("max", null) : null; + return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1); } } @@ -244,8 +256,8 @@ public final class DescriptorResolver { private DescriptorResolver() { } - public static IResolvedDescriptor resolve(ISelectorContext context, IAnnotationHandle desc) { - return new Descriptor(Collections.emptySet(), context, desc); + public static IResolvedDescriptor resolve(IAnnotationHandle desc, ISelectorContext context) { + return new Descriptor(Collections.emptySet(), desc, context); } /** @@ -268,14 +280,13 @@ public final class DescriptorResolver { IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true)); observer.postResolve(); - return new Descriptor(observer.getSearched(), context, desc); + return new Descriptor(observer.getSearched(), desc, context); } /** * Recursive function which checks an element and then recurses to parent */ private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate) { - IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation()); observer.visit(coordinate, annotation, annotation.toString() + ".desc"); @@ -293,7 +304,8 @@ public final class DescriptorResolver { ISelectorContext root = DescriptorResolver.getRoot(context); String rootCoordinate = root.getSelectorCoordinate(false); - String mixinCoordinate = root != context && !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate; + String mixinCoordinate = (root != context || !coordinate.contains(".")) && !rootCoordinate.equals(coordinate) + ? rootCoordinate + "." + coordinate : coordinate; // Next check with the current coordinates on the mixin resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin"); @@ -386,7 +398,8 @@ public final class DescriptorResolver { } else if (element instanceof MixinTargetContext) { return Annotations.handleOf(Annotations.getVisible(((MixinTargetContext)element).getClassNode(), annotationClass)); } else if (element instanceof IAnnotatedElement) { - return ((IAnnotatedElement)element).getAnnotation(annotationClass); + IAnnotationHandle annotation = ((IAnnotatedElement)element).getAnnotation(annotationClass); + return annotation != null && annotation.exists() ? annotation : null; } else if (element == null) { return null; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index ed773f26..7175cab2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -34,13 +34,20 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Quantifier; +import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.IAnnotationHandle; +import com.google.common.base.Strings; + /** * A {@link ITargetSelector Target Selector} which matches candidates using * descriptors contained in {@link Desc @Desc} annotations. The descriptor @@ -137,7 +144,7 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle; *     @Inject(method = "@Desc", at = @At(value = * "INVOKE" target = "@Desc(?)")) *
- *     void myHandlerMethod(int arg, CallbackInfo ci) { + *     void myHandler(int arg, CallbackInfo ci) { *
* *

This will cause the resolver to pretty-print the considered coordinates @@ -160,7 +167,8 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle; * supports.

*/ @SelectorId("Desc") -public final class DynamicSelectorDesc extends DynamicSelectorAbstract { +@SelectorAnnotation(Desc.class) +public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName { /** * Parser/resolver error mesage, only stored if the descriptor is invalid so @@ -203,15 +211,24 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { */ private final String methodDesc; + /** + * Required matches + */ + private final Quantifier matches; + private DynamicSelectorDesc(IResolvedDescriptor desc) { - this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType()); + this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches()); + } + + private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) { + this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier); } private DynamicSelectorDesc(InvalidSelectorException ex) { - this(ex, null, null, null, null, null); + this(ex, null, null, null, null, null, Quantifier.NONE); } - private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType) { + private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches) { this.parseException = ex; this.id = id; @@ -219,7 +236,8 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { this.name = name; this.args = args; this.returnType = returnType; - this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; + this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; + this.matches = matches; } /** @@ -235,8 +253,22 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context); if (!descriptor.isResolved()) { String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : ""; - InvalidSelectorException ex = new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra); - return new DynamicSelectorDesc(ex); + return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra)); + } + return DynamicSelectorDesc.of(descriptor); + } + + /** + * Convert the supplied annotation into a selector instance + * + * @param context Selector context + * @param desc Annotation to parse + * @return selector + */ + public static DynamicSelectorDesc parse(IAnnotationHandle desc, ISelectorContext context) { + IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context); + if (!descriptor.isResolved()) { + return new DynamicSelectorDesc(new InvalidSelectorException("Invalid descriptor")); } return DynamicSelectorDesc.of(descriptor); } @@ -259,16 +291,16 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { /** * Convert the supplied annotation into a selector instance * - * @param context Selector context * @param desc Annotation to parse + * @param context Selector context * @return selector */ - public static DynamicSelectorDesc of(ISelectorContext context, IAnnotationHandle desc) { - IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context); + public static DynamicSelectorDesc of(IAnnotationHandle desc, ISelectorContext context) { + IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context); if (!descriptor.isResolved()) { return null; } - return DynamicSelectorDesc.of(context, descriptor.getAnnotation()); + return DynamicSelectorDesc.of(descriptor); } /** @@ -281,18 +313,61 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { return new DynamicSelectorDesc(desc); } + @Override + public String toString() { + StringBuilder sb = new StringBuilder("@Desc("); + boolean started = false; + if (!Strings.isNullOrEmpty(this.id)) { + sb.append("id = \"").append(this.id).append("\""); + started = true; + } + + if (this.owner != Type.VOID_TYPE) { + if (started) { + sb.append(", "); + } + sb.append("owner = ").append(SignaturePrinter.getTypeName(this.owner, false, false)).append(".class"); + started = true; + } + + if (started) { + sb.append(", "); + } + sb.append("name = \"").append(this.name).append("\""); + + if (this.args.length > 0) { + sb.append(", args = { "); + for (int i = 0; i < this.args.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(SignaturePrinter.getTypeName(this.args[i], false, false)).append(".class"); + } + sb.append(" }"); + } + + if (this.returnType != Type.VOID_TYPE) { + sb.append(", ret = ").append(SignaturePrinter.getTypeName(this.returnType, false, false)).append(".class"); + } + + sb.append(")"); + return sb.toString(); + } + public String getId() { return this.id; } - public Type getOwner() { - return this.owner; + @Override + public String getOwner() { + return this.owner.getInternalName(); } - + + @Override public String getName() { return this.name; } - + public Type[] getArgs() { return this.args; } @@ -300,7 +375,17 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { public Type getReturnType() { return this.returnType; } - + + @Override + public String getDesc() { + return this.methodDesc; + } + + @Override + public String toDescriptor() { + return new SignaturePrinter(this).setFullyQualified(true).toDescriptor(); + } + @Override public ITargetSelector validate() throws InvalidSelectorException { if (this.parseException != null) { @@ -313,10 +398,54 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { public ITargetSelector next() { return this; // Recurse } - + @Override - public int getMatchCount() { - return 1; + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); + switch (request) { + case SELECT_MEMBER: + if (this.matches.isDefault()) { + return new DynamicSelectorDesc(this, Quantifier.SINGLE); + } + break; + case SELECT_INSTRUCTION: + if (this.matches.isDefault()) { + return new DynamicSelectorDesc(this, Quantifier.ANY); + } + break; + case MOVE: + return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, + this.matches); + case CLEAR_LIMITS: + if (this.getMinMatchCount() != 0 || this.getMaxMatchCount() < Integer.MAX_VALUE) { + return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, + Quantifier.ANY); + } + break; + default: + break; + } + return this; + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMinMatchCount() { + return this.matches.getClampedMin(); + } + + @Override + public int getMaxMatchCount() { + return this.matches.getClampedMax(); + } + + @Override + public MatchResult matches(String owner, String name, String desc) { + return this.matches(owner, name, desc, this.methodDesc); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java index 5b1bc5e9..c6a99687 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.selectors.dynamic; import org.objectweb.asm.Type; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.asm.IAnnotationHandle; /** @@ -77,5 +78,10 @@ public interface IResolvedDescriptor { * if the descriptor was not resolved. */ public abstract Type getReturnType(); + + /** + * Get the specified matches values from the resolved descriptor. + */ + public abstract Quantifier getMatches(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java similarity index 61% rename from src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java rename to src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java index 70f6d2b3..7b3e5079 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java @@ -22,36 +22,30 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.injection.selectors.dynamic; +package org.spongepowered.asm.mixin.injection.selectors.throwables; -import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; -import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; /** - * Base class for dynamic selectors, just to reduce some boilerplate + * Exception to be thrown when a {@link ITargetSelector target selector} + * {@link ITargetSelector#getMinMatchCount min} or + * {@link ITargetSelector#getMaxMatchCount max} constraint is not met when + * running the selector */ -public abstract class DynamicSelectorAbstract implements ITargetSelectorDynamic { +public class SelectorConstraintException extends SelectorException { - @Override - public ITargetSelector configure(String... args) { - return this; + private static final long serialVersionUID = 1L; + + public SelectorConstraintException(ITargetSelector selector, String message) { + super(selector, message); } - @Override - public ITargetSelector validate() throws InvalidSelectorException { - return this; + public SelectorConstraintException(ITargetSelector selector, Throwable cause) { + super(selector, cause); } - @Override - public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { - return this; - } - - @Override - public int getMatchCount() { - return Integer.MAX_VALUE; + public SelectorConstraintException(ITargetSelector selector, String message, Throwable cause) { + super(selector, message, cause); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java new file mode 100644 index 00000000..f681e05f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java @@ -0,0 +1,59 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.throwables; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Exception to be thrown for error conditions raised by {@link ITargetSelector + * target selectors} + */ +public class SelectorException extends MixinException { + + private static final long serialVersionUID = 1L; + + private final ITargetSelector selector; + + public SelectorException(ITargetSelector selector, String message) { + super(message); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, Throwable cause) { + super(cause); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, String message, Throwable cause) { + super(message, cause); + this.selector = selector; + } + + public ITargetSelector getSelector() { + return this.selector; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java new file mode 100644 index 00000000..5227389e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Exceptions for selectors. + */ +package org.spongepowered.asm.mixin.injection.selectors.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 63ee06a7..1a5f83ce 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -30,8 +30,16 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import javax.tools.Diagnostic.Kind; @@ -51,9 +59,11 @@ import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.code.MethodSlice; import org.spongepowered.asm.mixin.injection.code.MethodSlices; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorException; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -293,13 +303,24 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected Set parseTargets() { Set selectors = new LinkedHashSet(); + TargetSelector.parse(Annotations.getValue(this.annotation, "method", false), this, selectors); + TargetSelector.parse(Annotations.getValue(this.annotation, "target", false), this, selectors); + + // Raise an error if we have no selectors + if (selectors.size() == 0) { + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", + this.annotationType, this.methodName)); + } + + Set attachedSelectors = new LinkedHashSet(); - for (String method : Annotations.getValue(this.annotation, "method", false)) { + // Validate and attach the parsed selectors + for (ITargetSelector selector : selectors) { try { - selectors.add(TargetSelector.parseAndValidate(method, this).attach(this)); + attachedSelectors.add(selector.validate().attach(this)); } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", - this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus())); + throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: %s. %s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus())); } catch (TargetNotSupportedException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s specifies a target class '%s', which is not supported", @@ -310,22 +331,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC ex.getMessage())); } } - - for (AnnotationNode target : Annotations.getValue(this.annotation, "target", false)) { - try { - selectors.add(DynamicSelectorDesc.of(this, Annotations.handleOf(target)).validate()); - } catch (InvalidSelectorException ex) { - throw new InvalidInjectionException(this, - String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName, - ex.getMessage())); - } - } - - if (selectors.size() == 0) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", - this.annotationType, this.methodName)); - } - return selectors; + + return attachedSelectors; } protected List readInjectionPoints() { @@ -383,8 +390,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC for (MethodNode targetMethod : this.targets) { Target target = this.mixin.getTargetMethod(targetMethod); InjectorTarget injectorTarget = new InjectorTarget(this, target); - this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); - injectorTarget.dispose(); + try { + this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); + } catch (SelectorException ex) { + throw new InvalidInjectionException(this, String.format("Injection validation failed: %s on %s: %s. %s%s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); + } finally { + injectorTarget.dispose(); + } } } @@ -544,27 +557,42 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1; for (ITargetSelector selector : selectors) { - int matchCount = selector.getMatchCount(); - for (int count = 0, pass = 0; pass < passes && count < 1; pass++) { + selector = selector.configure(Configure.SELECT_MEMBER, null); + + int matchCount = 0; + int maxCount = selector.getMaxMatchCount(); + + // Second pass ignores descriptor + ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); + if (permissiveSelector == selector) { + // Selector is already permissive, so skip the second pass + passes = 1; + } + + scan: for (int pass = 0; pass < passes && matchCount < 1; pass++) { + ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector; for (MethodNode target : this.classNode.methods) { - if (selector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + if (passSelector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + matchCount++; + boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null; - if (matchCount > 1 && (Bytecode.isStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { - continue; + if (maxCount <= 1 || ((this.isStatic || !Bytecode.isStatic(target)) && target != this.method && !isMixinMethod)) { + this.checkTarget(target); + this.targets.add(target); } - - this.checkTarget(target); - this.targets.add(target); - count++; - - if (count >= matchCount) { - break; + + if (matchCount >= maxCount) { + break scan; } } } - - // Second pass ignores descriptor - selector = selector.configure("permissive"); + } + + if (matchCount < selector.getMinMatchCount()) { + throw new InvalidInjectionException(this, new SelectorConstraintException(selector, String.format( + "Injection validation failed: %s for %s on %s did not match the required number of targets (required=%d, matched=%d). %s%s", + selector, this.annotationType, this.methodName, selector.getMinMatchCount(), matchCount, + this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()))); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index d7c620a3..cb4290a9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -288,7 +288,7 @@ public class InjectionPointData { if (desc != null) { String id = Annotations.getValue(desc, "id", "at"); if ("at".equalsIgnoreCase(id)) { - return DynamicSelectorDesc.of(this.context, Annotations.handleOf(desc)); + return DynamicSelectorDesc.of(Annotations.handleOf(desc), this.context); } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java index 0871898d..e65384b3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java @@ -264,7 +264,8 @@ public class InjectorGroupInfo { int min = this.getMinRequired(); int max = this.getMaxAllowed(); if (total < min) { - throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total)); + String only = total > 0 ? "only " : ""; + throw new InjectionValidationException(this, String.format("expected %d invocation(s) but %s%d succeeded", min, only, total)); } else if (total > max) { throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java index 82ffd7ee..c8320813 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java @@ -32,17 +32,25 @@ import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; public class InvalidMemberDescriptorException extends InvalidSelectorException { private static final long serialVersionUID = 1L; + private final String input; - public InvalidMemberDescriptorException(String message) { + public InvalidMemberDescriptorException(String input, String message) { super(message); + this.input = input; } - public InvalidMemberDescriptorException(Throwable cause) { + public InvalidMemberDescriptorException(String input, Throwable cause) { super(cause); + this.input = input; } - public InvalidMemberDescriptorException(String message, Throwable cause) { + public InvalidMemberDescriptorException(String input, String message, Throwable cause) { super(message, cause); + this.input = input; + } + + public String getInput() { + return this.input; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index fa59165c..36de13e2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -41,6 +41,7 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.asm.ElementNode; @@ -55,46 +56,163 @@ import com.google.common.base.Strings; * target members need to be specified as Strings in order to parse the String * representation to something useful.

* - *

Some examples:

- *
- *   // references a method or field called func_1234_a, if there are
- *   // multiple members with the same signature, matches the first occurrence
- *   func_1234_a
- *   
- *   // references a method or field called func_1234_a, if there are
- *   // multiple members with matching name, matches all occurrences
- *   func_1234_a*
- *   
- *   // references all methods which take 3 ints and return a bool
- *   *(III)Z
- *   
- *   // references a method called func_1234_a which takes 3 ints and
- *   // returns a bool
- *   func_1234_a(III)Z
- *   
- *   // references a field called field_5678_z which is a String
- *   field_5678_z:Ljava/lang/String;
- *   
- *   // references a ctor which takes a single String argument 
- *   <init>(Ljava/lang/String;)V
- *   
- *   // references a method called func_1234_a in class foo.bar.Baz
- *   Lfoo/bar/Baz;func_1234_a
- *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   Lcom/example/Dave;field_5678_z
- *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   // which is of type String
- *   Lcom/example/Dave;field_5678_z:Ljava/lang/String;
- *  
- *   // references a method called func_1234_a in class foo.bar.Baz which
- *   // takes three doubles and returns void
- *   Lfoo/bar/Baz;func_1234_a(DDD)V
- *   
- *   // alternate syntax for the same
- *   foo.bar.Baz.func_1234_a(DDD)V
- *
+ *

In general a MemberInfo consists of 4 parts, + * owner, name, quantifier + * and descriptor, all of which are optional: + *

+ * + *
OperationHandler signature
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
 OwnerNameQuantifier DescriptorResulting selector string
MethodLfully/qualified/OwnerClass;methodName{1,3} (III)VLfully/qualified/OwnerClass;methodName{1,3}(III)V
FieldLfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;Lfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;
+ * + *

Any part of the selector can be omitted, though they must appear in the + * correct order. Some examples:

+ * + *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with the same signature, matches the first occurrence
+ * func_1234_a
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences

+ * func_1234_a*
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences, matching less than 1 + *
+ * // occurrence is an error condition

+ * func_1234_a+
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches up to 3 occurrences

+ * func_1234_a{,3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches exactly 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches at least 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3,}
+ *
+ * // selects all members of any type and descriptor
+ * *
+ *
+ * // selects the first member of any type and descriptor
+ * {1}
+ *
+ * // selects all methods which take 3 ints and return a bool
+ * *(III)Z
+ *
+ * // selects the first 2 methods which take a bool and return void + *
+ * {2}(Z)V
+ *
+ * // selects a method called func_1234_a which takes 3 ints and returns a + * bool
+ * func_1234_a(III)Z
+ *
+ * // selects a field called field_5678_z which is a String
+ * field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a ctor which takes a single String argument
+ * <init>(Ljava/lang/String;)V
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz
+ * Lfoo/bar/Baz;func_1234_a + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave + *
+ * Lcom/example/Dave;field_5678_z + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave
+ * // which is of type String

+ * Lcom/example/Dave;field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz which
+ * // takes three doubles and returns void

+ * Lfoo/bar/Baz;func_1234_a(DDD)V
+ *
+ * // alternate syntax for the same
+ * foo.bar.Baz.func_1234_a(DDD)V + *
+ * + *

Notes

+ * + *
    + *
  • All whitespace in the selector string is stripped before the selector + * is parsed.
  • + *
  • Quantifiers for selectors can be used as a + * form of early validation (prior to injector require directives) + * that an injection point has matched a required number of targets or to + * limit the number of matches it can return.
  • + *
  • The syntax for quantifiers is based on the + * syntax for quantifiers in regular expressions, though more + * limited. In particular: + *
      + *
    • No quantifer is equivalent to the regex ? + * quantifier, in that undecorated selectors can match {0,1}, + * this is for backward compatibility reasons. Likewise ? is + * not supported since it's implied. To require exactly one match use + * {1}.
    • + *
    • The quantifiers * and + work the same as their + * regex counterparts.
    • + *
    + *
  • + *
*/ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor { @@ -114,9 +232,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec private final String desc; /** - * True to match all matching members, not just the first + * Required matches */ - private final boolean matchAll; + private final Quantifier matches; /** * Force this member to report as a field @@ -126,17 +244,27 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec /** * The actual String value passed into the {@link #parse} method */ - private final String unparsed; + private final String input; + + /** + * ctor + * + * @param name Member name, must not be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, Quantifier matches) { + this(name, null, null, matches, null); + } /** * ctor * * @param name Member name, must not be null - * @param matchAll true if this info should match all matching references, - * or only the first + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed */ - public MemberInfo(String name, boolean matchAll) { - this(name, null, null, matchAll); + public MemberInfo(String name, int minMatches, int maxMatches) { + this(name, null, null, new Quantifier(minMatches, maxMatches), null); } /** @@ -145,11 +273,23 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param name Member name, must not be null * @param owner Member owner, can be null otherwise must be in internal form * without L; - * @param matchAll true if this info should match all matching references, - * or only the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, boolean matchAll) { - this(name, owner, null, matchAll); + public MemberInfo(String name, String owner, Quantifier matches) { + this(name, owner, null, matches, null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed + */ + public MemberInfo(String name, String owner, int minMatches, int maxMatches) { + this(name, owner, null, new Quantifier(minMatches, maxMatches), null); } /** @@ -161,7 +301,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param desc Member descriptor, can be null */ public MemberInfo(String name, String owner, String desc) { - this(name, owner, desc, false); + this(name, owner, desc, Quantifier.DEFAULT, null); } /** @@ -171,10 +311,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, String desc, boolean matchAll) { - this(name, owner, desc, matchAll, null); + public MemberInfo(String name, String owner, String desc, Quantifier matches) { + this(name, owner, desc, matches, null); } /** @@ -184,9 +324,37 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed */ - public MemberInfo(String name, String owner, String desc, boolean matchAll, String unparsed) { + public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches) { + this(name, owner, desc, new Quantifier(minMatches, maxMatches), null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed + */ + public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches, String input) { + this(name, owner, desc, new Quantifier(minMatches, maxMatches), input); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, String owner, String desc, Quantifier matches, String input) { if (owner != null && owner.contains(".")) { throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format"); } @@ -194,9 +362,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = name; this.desc = desc; - this.matchAll = matchAll; + this.matches = matches; this.forceField = false; - this.unparsed = unparsed; + this.input = input; } /** @@ -206,9 +374,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param insn instruction node to copy values from */ public MemberInfo(AbstractInsnNode insn) { - this.matchAll = false; + this.matches = Quantifier.DEFAULT; this.forceField = false; - this.unparsed = null; + this.input = null; if (insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; @@ -234,9 +402,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = mapping.getOwner(); this.name = mapping.getSimpleName(); this.desc = mapping.getDesc(); - this.matchAll = false; + this.matches = Quantifier.SINGLE; this.forceField = mapping.getType() == IMapping.Type.FIELD; - this.unparsed = null; + this.input = null; } /** @@ -248,9 +416,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = setOwner ? method.getOwner() : remapped.owner; this.name = method.getSimpleName(); this.desc = method.getDesc(); - this.matchAll = remapped.matchAll; + this.matches = remapped.matches; this.forceField = false; - this.unparsed = null; + this.input = null; } /** @@ -263,9 +431,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = original.name; this.desc = original.desc; - this.matchAll = original.matchAll; + this.matches = original.matches; this.forceField = original.forceField; - this.unparsed = null; + this.input = null; } @Override @@ -289,8 +457,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } @Override - public int getMatchCount() { - return this.matchAll ? Integer.MAX_VALUE : 1; + public int getMinMatchCount() { + return this.matches.getClampedMin(); + } + + @Override + public int getMaxMatchCount() { + return this.matches.getClampedMax(); } /* (non-Javadoc) @@ -300,12 +473,12 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec public String toString() { String owner = this.owner != null ? "L" + this.owner + ";" : ""; String name = this.name != null ? this.name : ""; - String qualifier = this.matchAll ? "*" : ""; + String quantifier = this.matches.toString(); String desc = this.desc != null ? this.desc : ""; String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : ""); - return owner + name + qualifier + separator + desc; + return owner + name + quantifier + separator + desc; } - + /** * Return this MemberInfo as an SRG mapping * @@ -342,7 +515,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ @Override public String toCtorType() { - if (this.unparsed == null) { + if (this.input == null) { return null; } @@ -359,7 +532,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec return this.name; } - return this.desc != null ? this.desc : this.unparsed; + return this.desc != null ? this.desc : this.input; } /** @@ -478,52 +651,60 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * * @return fluent * - * @throws InvalidMemberDescriptorException if any validation check fails + * @throws InvalidSelectorException if any validation check fails */ @Override - public MemberInfo validate() throws InvalidMemberDescriptorException { + public MemberInfo validate() throws InvalidSelectorException { + // Parse emits a match count of 0 if the quantifier is incorrectly specified + if (this.getMaxMatchCount() == 0) { + throw new InvalidMemberDescriptorException(this.input, "Malformed quantifier in selector: " + this.input); + } + // Extremely naive class name validation, just to spot really egregious errors if (this.owner != null) { if (!this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) { - throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner); + throw new InvalidMemberDescriptorException(this.input, "Invalid owner: " + this.owner); } // We can't detect this situation 100% reliably, but we can take a // decent stab at it in order to detect really obvious cases where // the user types a dot instead of a semicolon - if (this.unparsed != null && this.unparsed.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { - throw new InvalidMemberDescriptorException("Malformed owner: " + this.owner + " If you are seeing this message unexpectedly and the" - + " owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + "; to suppress this error"); + if (this.input != null && this.input.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { + throw new InvalidMemberDescriptorException(this.input, "Malformed owner: " + this.owner + " If you are seeing this message" + + "unexpectedly and the owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + + "; to suppress this error"); } } // Also naive validation, we're looking for stupid errors here if (this.name != null && !this.name.matches("(?i)^?$")) { - throw new InvalidMemberDescriptorException("Invalid name: " + this.name); + throw new InvalidMemberDescriptorException(this.input, "Invalid name: " + this.name); } if (this.desc != null) { if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[*[\\w\\p{Sc}/;]+$")) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } if (this.isField()) { if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid field type in descriptor: " + this.desc); } } else { try { Type.getArgumentTypes(this.desc); } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } String retString = this.desc.substring(this.desc.indexOf(')') + 1); try { Type retType = Type.getType(retString); if (!retString.equals(retType.getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } } @@ -590,46 +771,68 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } ITargetSelectorByName other = (ITargetSelectorByName)obj; - boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField : other.isField(); - boolean otherMatchAll = other.getMatchCount() == Integer.MAX_VALUE; + boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField + : other instanceof ITargetSelectorRemappable ? ((ITargetSelectorRemappable)other).isField() : false; - return this.matchAll == otherMatchAll && this.forceField == otherForceField + return this.compareMatches(other) && this.forceField == otherForceField && Objects.equal(this.owner, other.getOwner()) && Objects.equal(this.name, other.getName()) && Objects.equal(this.desc, other.getDesc()); } + /** + * Compare local match count with match count of other selector + */ + private boolean compareMatches(ITargetSelectorByName other) { + if (other instanceof MemberInfo) { + return ((MemberInfo)other).matches.equals(this.matches); + } + return this.getMinMatchCount() == other.getMinMatchCount() && this.getMaxMatchCount() == other.getMaxMatchCount(); + } + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { - return Objects.hashCode(this.matchAll, this.owner, this.name, this.desc); + return Objects.hashCode(this.matches, this.owner, this.name, this.desc); } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #configure(java.lang.String[]) + * #mutate(java.lang.String[]) */ @Override - public ITargetSelector configure(String... args) { - ITargetSelectorRemappable configured = this; - for (String arg : args) { - if (arg == null) { - continue; - } - - if (arg.startsWith("move:")) { - configured = configured.move(Strings.emptyToNull(arg.substring(5))); - } else if (arg.startsWith("transform:")) { - configured = configured.transform(Strings.emptyToNull(arg.substring(10))); - } else if ("permissive".equals(arg)) { - configured = configured.transform(null); - } else if ("orphan".equals(arg)) { - configured = configured.move(null); - } + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); + switch (request) { + case SELECT_MEMBER: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE); + } + break; + case SELECT_INSTRUCTION: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY); + } + break; + case MOVE: + return this.move(Strings.emptyToNull(args[0])); + case ORPHAN: + return this.move(null); + case TRANSFORM: + return this.transform(Strings.emptyToNull(args[0])); + case PERMISSIVE: + return this.transform(null); + case CLEAR_LIMITS: + if (this.matches.getMin() != 0 || this.matches.getMax() < Integer.MAX_VALUE) { + return new MemberInfo(this.name, this.owner, this.desc, 0, Integer.MAX_VALUE); + } + break; + default: + break; } - return configured; + return this; } /* (non-Javadoc) @@ -667,7 +870,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec if ((newDesc == null && this.desc == null) || (newDesc != null && newDesc.equals(this.desc))) { return this; } - return new MemberInfo(this.name, this.owner, newDesc, this.matchAll); + return new MemberInfo(this.name, this.owner, newDesc, this.matches); } /** @@ -689,7 +892,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param context Selector context for this parse request * @return parsed MemberInfo */ - public static MemberInfo parse(String input, ISelectorContext context) { + public static MemberInfo parse(final String input, final ISelectorContext context) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); @@ -723,16 +926,40 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec name = ""; } - boolean matchAll = name.endsWith("*"); - if (matchAll) { + // Use default quantifier with negative max value. Used to indicate that + // an explicit quantifier was not parsed from the selector string, this + // allows us to provide backward-compatible behaviour for injection + // points vs. selecting target members which have different default + // semantics when omitting the quantifier. This is handled by consumers + // calling configure() with SELECT_MEMBER or SELECT_INSTRUCTION to + // promote the default case to a concrete case. + Quantifier quantifier = Quantifier.DEFAULT; + if (name.endsWith("*")) { + quantifier = Quantifier.ANY; name = name.substring(0, name.length() - 1); + } else if (name.endsWith("+")) { + quantifier = Quantifier.PLUS; + name = name.substring(0, name.length() - 1); + } else if (name.endsWith("}")) { + quantifier = Quantifier.NONE; // Assume invalid until quantifier is parsed + int bracePos = name.indexOf("{"); + if (bracePos >= 0) { + try { + quantifier = Quantifier.parse(name.substring(bracePos, name.length())); + name = name.substring(0, bracePos); + } catch (Exception ex) { + // Handled later in validate since matchCount will be 0 + } + } + } else if (name.indexOf("{") >= 0) { + quantifier = Quantifier.NONE; // Probably incomplete quantifier } if (name.isEmpty()) { name = null; } - return new MemberInfo(name, owner, desc, matchAll, input); + return new MemberInfo(name, owner, desc, quantifier, input); } /** 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 6a75f3ea..a41b76b4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -1034,6 +1034,13 @@ final class MixinConfig implements Comparable, IMixinConfig { public Level getLoggingLevel() { return this.verboseLogging ? Level.INFO : Level.DEBUG; } + + /** + * Get whether verbose logging is enabled + */ + public boolean isVerboseLogging() { + return this.verboseLogging; + } /** * Get whether this config's package matches the supplied class name 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 f18b3dbb..0193ff74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -1009,23 +1009,23 @@ class MixinInfo implements Comparable, IMixinInfo { if (this.isVirtual()) { this.logger.debug("Skipping virtual target {} for {}", target.name, this); } else { - this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this), false); } return null; } this.type.validateTarget(target.name, targetInfo); if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) { - this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this), true); } return targetInfo; } - private void handleTargetError(String message) { + private void handleTargetError(String message, boolean verboseOnly) { if (this.strict) { this.logger.error(message); throw new InvalidMixinException(this, message); } - this.logger.warn(message); + this.logger.log(verboseOnly && !this.parent.isVerboseLogging() ? Level.DEBUG : Level.WARN, message); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index a0931ecf..e3b30fd0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -48,6 +48,7 @@ import org.spongepowered.asm.mixin.transformer.meta.MixinProxy; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Bytecode.Visibility; /** * Performs post-processing tasks required for certain classes which pass @@ -170,6 +171,11 @@ class MixinPostProcessor implements MixinConfig.IListener { MixinClassNode mixinClassNode = mixin.getClassNode(0); ClassInfo targetClass = mixin.getTargets().get(0); + if (!Bytecode.hasFlag(mixinClassNode, Opcodes.ACC_PUBLIC)) { + Bytecode.setVisibility(mixinClassNode, Visibility.PUBLIC); + transformed = true; + } + for (MixinMethodNode methodNode : mixinClassNode.mixinMethods) { if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_STATIC)) { continue; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index b4ccbbc3..54506428 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -54,8 +54,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.struct.Target; -import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.struct.MemberRef; @@ -1194,9 +1194,9 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { activity.end(); } catch (InjectionValidationException ex) { InjectorGroupInfo group = ex.getGroup(); - throw new InjectionError( + throw new InvalidInjectionException(group.getMembers().iterator().next().getMixin(), String.format("Critical injection failure: Callback group %s in %s failed injection check: %s", - group, this.mixin, ex.getMessage())); + group, this.mixin, ex.getMessage()), ex); } catch (InvalidMixinException ex) { ex.prepend(this.activities); throw ex; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java index c72601de..f1768adc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java @@ -86,13 +86,29 @@ public class ExtensionCheckInterfaces implements IExtension { * Strict mode */ private boolean strict; + + /** + * True once the output dir and csv have been created, not triggered until + * something is written + */ + private boolean started = false; public ExtensionCheckInterfaces() { File debugOutputFolder = new File(Constants.DEBUG_OUTPUT_DIR, ExtensionCheckInterfaces.AUDIT_DIR); - debugOutputFolder.mkdirs(); this.csv = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_CSV_FILENAME); this.report = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_TXT_FILENAME); + } + + /** + * Delayed creation of CSV so the dir doesn't get created when the extension + * is inactive + */ + private void start() { + if (this.started) { + return; + } + this.started = true; this.csv.getParentFile().mkdirs(); try { @@ -137,6 +153,8 @@ public class ExtensionCheckInterfaces implements IExtension { */ @Override public void postApply(ITargetClassContext context) { + this.start(); + ClassInfo targetClassInfo = context.getClassInfo(); // If the target is abstract and strict mode is not enabled, skip this class diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index 08a27eb1..d248c593 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -55,7 +55,7 @@ import com.google.common.collect.Lists; public final class Annotations { /** - * Wrapper for AnnotationNode to support access via IAnnotationHandle + * Wrapper for {@link AnnotationNode} to support access via common interface */ public static class Handle implements IAnnotationHandle { @@ -66,13 +66,18 @@ public final class Annotations { this.annotation = annotation; } + @Override + public boolean exists() { + return true; + } + public AnnotationNode getNode() { return this.annotation; } @Override public String getDesc() { - return this.annotation.desc; + return Type.getType(this.annotation.desc).getInternalName(); } @Override @@ -87,6 +92,11 @@ public final class Annotations { return list; } + @Override + public Type getTypeValue(String key) { + return this.getValue(key, Type.VOID_TYPE); + } + @Override public List getTypeList(String key) { return this.getList(key); @@ -160,6 +170,16 @@ public final class Annotations { throw new IllegalArgumentException("Unsupported annotation type: " + annotation.getClass().getName()); } } + + /** + * Returns the bytecode descriptor of an annotation + * + * @param annotationType annotation + * @return annotation's descriptor + */ + public static String getDesc(Class annotationType) { + return Type.getType(annotationType).getInternalName(); + } /** * Returns the simple name of an annotation, mainly used for printing diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index c1b02b35..f4a33ba4 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -999,6 +999,17 @@ public final class Bytecode { return Bytecode.Visibility.PACKAGE; } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param visibility new visibility + */ + public static void setVisibility(ClassNode classNode, Visibility visibility) { + classNode.access = Bytecode.setVisibility(classNode.access, visibility.access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged @@ -1021,6 +1032,17 @@ public final class Bytecode { field.access = Bytecode.setVisibility(field.access, visibility.access); } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param access new visibility + */ + public static void setVisibility(ClassNode classNode, int access) { + classNode.access = Bytecode.setVisibility(classNode.access, access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged diff --git a/src/main/java/org/spongepowered/asm/util/Quantifier.java b/src/main/java/org/spongepowered/asm/util/Quantifier.java new file mode 100644 index 00000000..12141ec7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Quantifier.java @@ -0,0 +1,214 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; + +/** + * A regex-style quantifier, specified as a number or pair of numbers in braces. + */ +public final class Quantifier { + + /** + * Default quantifier, used when a quantifier was not specified + * (empty string) + */ + public static Quantifier DEFAULT = new Quantifier(0, -1); + + /** + * Invalid (matches none) + */ + public static Quantifier NONE = new Quantifier(0, 0); + + /** + * Single (matches zero or 1) + */ + public static Quantifier SINGLE = new Quantifier(0, 1); + + /** + * Default (matches any) + */ + public static Quantifier ANY = new Quantifier(0, Integer.MAX_VALUE); + + /** + * Plus (matches 1 or more) + */ + public static Quantifier PLUS = new Quantifier(1, Integer.MAX_VALUE); + + /** + * Minimum value, parsed from expression, 0 if unbounded + */ + private final int min; + + /** + * Maximum value, parsed from expression, Integer.MAX_VALUE if unbounded + */ + private final int max; + + public Quantifier(int min, int max) { + this.min = min; + this.max = max; + } + + /** + * Check whether this is a defaulted qualifier + */ + public boolean isDefault() { + return this.min == 0 && this.max < 0; + } + + /** + * Get the literal min value + */ + public int getMin() { + return this.min; + } + + /** + * Get the literal max value + */ + public int getMax() { + return this.max; + } + + /** + * Get the clamped min value + */ + public int getClampedMin() { + return Math.max(0, this.min); + } + + /** + * Get the clamped max value + */ + public int getClampedMax() { + return this.max < 0 ? 1 : Math.max(this.min, this.max); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + if (this.min == this.max) { + sb.append(this.min); + } else if (this.max < this.min) { + return ""; + } else { + if (this.min == 0) { + if (this.max == 1) { + return ""; + } else if (this.max == Integer.MAX_VALUE) { + return "*"; + } + } + if (this.min == 1 && this.max == Integer.MAX_VALUE) { + return "+"; + } + if (this.min > 0) { + sb.append(this.min); + } + if (this.min >= 0) { + sb.append(','); + } + if (this.max < Integer.MAX_VALUE) { + sb.append(this.max); + } + } + return sb.append('}').toString(); + } + + /** + * Parse a quantifier from the supplied string + * + * @param string string to parse + * @return parsed quantifier, malformed quantifiers return NONE + */ + public static Quantifier parse(String string) { + if (string == null || ((string = string.trim()).length() == 0)) { + return Quantifier.DEFAULT; + } + + if ("*".equals(string)) { + return Quantifier.ANY; + } + + if ("+".equals(string)) { + return Quantifier.PLUS; + } + + if (!string.startsWith("{") || !string.endsWith("}") || string.length() < 3) { + return Quantifier.NONE; // malformed + } + + String inner = string.substring(1, string.length() - 1).trim(); + if (inner.isEmpty()) { + return Quantifier.NONE; + } + + String strMin = inner; + String strMax = inner; + + int comma = inner.indexOf(','); + if (comma > -1) { + strMin = inner.substring(0, comma).trim(); + strMax = inner.substring(comma + 1).trim(); + } + + try { + int min = strMin.length() > 0 ? Integer.parseInt(strMin) : 0; + int max = strMax.length() > 0 ? Integer.parseInt(strMax) : Integer.MAX_VALUE; + return new Quantifier(min, max); + } catch (NumberFormatException ex) { + return Quantifier.NONE; + } + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Quantifier) { + Quantifier other = (Quantifier)obj; + return other.min == this.min && other.max == this.max; + } + + if (obj instanceof Number) { + int intValue = ((Number)obj).intValue(); + return (intValue == this.min) && (intValue == this.max); + } + + return false; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return 31 * this.min * this.max; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java index 2695337c..b38b42c7 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -27,12 +27,22 @@ package org.spongepowered.asm.util.asm; import java.util.List; import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; /** - * Interface for annotation handle since main classes may need to read info from - * mirror annotations in the AP + * Interface for annotation handle since some classes may need to read info from + * both ASM {@link AnnotationNode}s at runtime and mirror annotations in the AP + * at compile time. */ public interface IAnnotationHandle { + + /** + * Get whether the annotation inside the handle actually exists, if the + * contained element is null, returns false. + * + * @return true if the annotation exists + */ + public abstract boolean exists(); /** * Get the annotation descriptor @@ -48,7 +58,23 @@ public interface IAnnotationHandle { public abstract List getAnnotationList(String key); /** - * Retrieve an annotation key as a list of annotation Types + * Get an annotation value as an ASM {@link Type}. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. + * + * @param key key to fetch + * @return value + */ + public abstract Type getTypeValue(String key); + + /** + * Retrieve an annotation key as a list of Types. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. * * @param key key to fetch * @return list of types From b5200b0537095a53e0997e053069fe60bd1f8de3 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 18 Feb 2021 20:47:12 +0000 Subject: [PATCH 19/42] Allow injection points and dynamic selectors to be defined in mixin pkgs Temp implementation until access control is moved to service in 0.9 --- .../tools/obfuscation/AnnotatedMixin.java | 7 --- .../asm/mixin/injection/InjectionPoint.java | 5 +- .../injection/callback/CallbackInjector.java | 6 +- .../injection/invoke/ModifyArgInjector.java | 5 +- .../injection/invoke/ModifyArgsInjector.java | 5 +- .../invoke/ModifyConstantInjector.java | 4 +- .../injection/invoke/RedirectInjector.java | 9 ++- .../mixin/injection/struct/InjectionInfo.java | 2 +- .../asm/mixin/refmap/IMixinContext.java | 12 ---- .../asm/mixin/transformer/ClassInfo.java | 58 ++++++++++++++++++- .../asm/mixin/transformer/MixinConfig.java | 2 +- .../asm/mixin/transformer/MixinInfo.java | 2 +- .../asm/mixin/transformer/MixinProcessor.java | 26 +++++---- .../mixin/transformer/MixinTargetContext.java | 1 - .../asm/util/asm/IAnnotationHandle.java | 2 + 15 files changed, 98 insertions(+), 48 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index dc31d05b..901047fa 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -37,14 +37,12 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; -import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.struct.SelectorAnnotationContext; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.mixin.transformer.ext.Extensions; @@ -475,11 +473,6 @@ class AnnotatedMixin implements IMixinContext, IAnnotatedElement { throw new UnsupportedOperationException("Priority not available at compile time"); } - @Override - public Target getTargetMethod(MethodNode into) { - throw new UnsupportedOperationException("Target not available at compile time"); - } - @Override public IAnnotationHandle getAnnotation(Class annotationClass) { return AnnotationHandle.of(this.mixin, annotationClass); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index d9c371f0..b762c06f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -100,7 +100,8 @@ public abstract class InjectionPoint { /** * Namespace for this code. Final selectors will be specified as * <namespace>:<code> in order to avoid overlaps - * between consumer-provided injection points. + * between consumer-provided injection points. Uses namespace from + * parent config if not specified. */ public String namespace() default ""; @@ -719,7 +720,7 @@ public abstract class InjectionPoint { String type = data.getType(); Class ipClass = InjectionPoint.types.get(type.toUpperCase(Locale.ROOT)); if (ipClass == null) { - if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { + if (type.matches("^([A-Za-z_][A-Za-z0-9_]*[\\.\\$])+[A-Za-z_][A-Za-z0-9_]*$")) { try { ipClass = (Class)MixinService.getService().getClassProvider().findClass(type); InjectionPoint.types.put(type, ipClass); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index 9827cfb1..4d976bd8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -34,13 +34,14 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.Surrogate; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.Target.Extension; -import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Annotations; @@ -53,7 +54,8 @@ import org.spongepowered.asm.util.SignaturePrinter; import com.google.common.base.Strings; /** - * This class is responsible for generating the bytecode for injected callbacks + * This class is responsible for generating the bytecode for injected callbacks, + * for details of usage see {@link Inject @Inject}. */ public class CallbackInjector extends Injector { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java index 95a046b9..30a29cee 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java @@ -32,16 +32,17 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.Target.Extension; -import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Bytecode; /** * A bytecode injector which allows a single argument of a chosen method call to - * be altered. + * be altered. For details see javadoc for {@link ModifyArg @ModifyArg}. */ public class ModifyArgInjector extends InvokeInjector { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java index df75a876..051831a0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java @@ -31,17 +31,18 @@ import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; +import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.Target.Extension; -import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Bytecode; /** * A bytecode injector which allows a single argument of a chosen method call to - * be altered. + * be altered. For details see javadoc for {@link ModifyArgs @ModifyArgs}. */ public class ModifyArgsInjector extends InvokeInjector { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index a9ad8835..3ef551e6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -36,6 +36,7 @@ import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.util.InsnFinder; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; @@ -49,7 +50,8 @@ import org.spongepowered.asm.util.SignaturePrinter; /** * A bytecode injector which allows a specific constant value to be identified - * and replaced with a callback + * and replaced with a callback. For details see javadoc for + * {@link ModifyConstant @ModifyConstant}. */ public class ModifyConstantInjector extends RedirectInjector { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index efaf1860..3a5b5fc7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -58,7 +58,10 @@ import com.google.common.primitives.Ints; * method. For method redirects, the handler method signature must match the * hooked method precisely but prepended with an arg of the owning * object's type to accept the object instance the method was going to be - * invoked upon. For example when hooking the following call:

+ * invoked upon. For more details see the javadoc for the {@link Redirect + * @Redirect} annotation.

+ * + *

For example when hooking the following call:

* *
  *   int abc = 0;
@@ -79,8 +82,8 @@ import com.google.common.primitives.Ints;
  * methods it is sufficient that the signature simply match the hooked method.
  * 

* - *

For field redirections, see the details in {@link Redirect} for the - * required signature of the handler method.

+ *

For field redirections, see the details in {@link Redirect @Redirect} + * for the required signature of the handler method.

* *

For constructor redirections, the signature of the handler method should * match the constructor itself, return type should be of the type of object diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 1a5f83ce..428d436e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -557,7 +557,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1; for (ITargetSelector selector : selectors) { - selector = selector.configure(Configure.SELECT_MEMBER, null); + selector = selector.configure(Configure.SELECT_MEMBER); int matchCount = 0; int maxCount = selector.getMaxMatchCount(); diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java index fd12eddb..22ed77d1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java @@ -24,10 +24,8 @@ */ package org.spongepowered.asm.mixin.refmap; -import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.transformer.ext.Extensions; /** @@ -87,14 +85,4 @@ public interface IMixinContext { */ public abstract int getPriority(); - /** - * Obtain a {@link Target} method handle for a method in the target, this is - * used by consumers to manipulate the bytecode in a target method in a - * controlled manner. - * - * @param method method node to wrap - * @return target method - */ - public abstract Target getTargetMethod(MethodNode method); - } 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 097149e7..6180247b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -1143,6 +1143,47 @@ public final class ClassInfo { return this.getSuperClass(); } + /** + * 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(Class superClass) { + return this.hasSuperClass(superClass, Traversal.NONE, superClass.isInterface()); + } + + /** + * 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(Class superClass, Traversal traversal) { + return this.hasSuperClass(superClass, traversal, superClass.isInterface()); + } + + /** + * 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 + * @param includeInterfaces True to include interfaces in the lookup + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(Class superClass, Traversal traversal, boolean includeInterfaces) { + String internalName = org.objectweb.asm.Type.getInternalName(superClass); + if (ClassInfo.JAVA_LANG_OBJECT.equals(internalName)) { + return true; + } + + return this.findSuperClass(internalName, traversal) != null; + } + /** * Test whether this class has the specified superclass in its hierarchy * @@ -1151,7 +1192,7 @@ public final class ClassInfo { * anywhere */ public boolean hasSuperClass(String superClass) { - return this.hasSuperClass(superClass, Traversal.NONE); + return this.hasSuperClass(superClass, Traversal.NONE, false); } /** @@ -1163,10 +1204,23 @@ public final class ClassInfo { * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal) { + return this.hasSuperClass(superClass, traversal, false); + } + + /** + * 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 + * @param includeInterfaces True to include interfaces in the lookup + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(String superClass, Traversal traversal, boolean includeInterfaces) { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } - + return this.findSuperClass(superClass, traversal) != null; } 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 a41b76b4..b15e1ef1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -555,7 +555,7 @@ final class MixinConfig implements Comparable, IMixinConfig { Class injectionPointClass = this.findExtensionClass(className, InjectionPoint.class, "injection point"); if (injectionPointClass != null) { try { - injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); + injectionPointClass.getMethod("find", String.class, InsnList.class, Collection.class); } catch (NoSuchMethodException cnfe) { this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", className, this, cnfe); 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 0193ff74..7dec6d02 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -427,7 +427,7 @@ class MixinInfo implements Comparable, IMixinInfo { || inner.name.startsWith(this.validationClassNode.name + "$")) { if (innerClass.isProbablyStatic() && innerClass.isSynthetic()) { this.syntheticInnerClasses.add(inner.name); - } else { + } else if (!innerClass.isMixin()) { this.innerClasses.add(inner.name); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 68043f0e..977782fe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -42,6 +42,8 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; import org.spongepowered.asm.mixin.throwables.MixinApplyError; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -304,7 +306,6 @@ class MixinProcessor { return success; } - SortedSet mixins = null; MixinConfig packageOwnedByConfig = null; for (MixinConfig config : this.configs) { @@ -315,7 +316,20 @@ class MixinProcessor { } continue; } + } + + if (packageOwnedByConfig != null) { + // AMS - Temp passthrough for injection points and dynamic selectors. Moving to service in 0.9 + ClassInfo targetInfo = ClassInfo.fromClassNode(targetClassNode); + if (targetInfo.hasSuperClass(InjectionPoint.class) || targetInfo.hasSuperClass(ITargetSelectorDynamic.class)) { + return false; + } + throw new IllegalClassLoadError(this.getInvalidClassError(name, targetClassNode, packageOwnedByConfig)); + } + + SortedSet mixins = null; + for (MixinConfig config : this.configs) { if (config.hasMixinsFor(name)) { if (mixins == null) { mixins = new TreeSet(); @@ -325,10 +339,6 @@ class MixinProcessor { mixins.addAll(config.getMixinsFor(name)); } } - - if (packageOwnedByConfig != null) { - throw new IllegalClassLoadError(this.getInvalidClassError(name, targetClassNode, packageOwnedByConfig)); - } if (mixins != null) { // Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now @@ -373,12 +383,6 @@ class MixinProcessor { return String.format("Illegal classload request for %s. Mixin is defined in %s and cannot be referenced directly", name, ownedByConfig); } -// AnnotationNode proxy = Annotations.getInvisible(targetClassNode, Proxy.class); -// if (proxy != null) { -// return String.format("Illegal classload request for UNRESOLVED @Proxy %s. " -// + "The proxy was referenced outside a mixin or the mixin processor encountered an internal error.", name); -// } - AnnotationNode mixin = Annotations.getInvisible(targetClassNode, Mixin.class); if (mixin != null) { Variant variant = MixinInfo.getVariant(targetClassNode); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 54506428..32e0ae02 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -972,7 +972,6 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param method method to get a target handle for * @return new or existing target handle for the supplied method */ - @Override public Target getTargetMethod(MethodNode method) { return this.getTarget().getTargetMethod(method); } diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java index b38b42c7..a62bc28b 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -26,6 +26,8 @@ package org.spongepowered.asm.util.asm; import java.util.List; +import javax.lang.model.type.TypeMirror; + import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; From 57055a150e59daca338d8e03a6a27ef0a5bfa7e6 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 20 Feb 2021 14:40:08 +0000 Subject: [PATCH 20/42] Use correct (configured) selector in BeforeInvoke --- .../asm/mixin/injection/points/BeforeInvoke.java | 8 ++++---- .../asm/mixin/injection/points/BeforeStringInvoke.java | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index ffb250e4..e47ae8cc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -198,7 +198,7 @@ public class BeforeInvoke extends InjectionPoint { if (target.match(insn).isExactMatch()) { this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className); - if (++matchCount > selector.getMaxMatchCount()) { + if (++matchCount > target.getMaxMatchCount()) { break; } @@ -222,9 +222,9 @@ public class BeforeInvoke extends InjectionPoint { + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.mixin, found); } - if (matchCount < selector.getMinMatchCount()) { - throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)", - selector, selector.getMinMatchCount(), matchCount)); + if (matchCount < target.getMinMatchCount()) { + throw new SelectorConstraintException(target, String.format("%s did not match the required number of targets (required=%d, matched=%d)", + target, selector.getMinMatchCount(), matchCount)); } return found > 0; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java index 82318a1c..3f6373d8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java @@ -122,7 +122,7 @@ public class BeforeStringInvoke extends BeforeInvoke { if (insn instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) insn; if (node.cst instanceof String && this.ldcValue.equals(node.cst)) { - this.log("{} > found a matching LDC with value {}", this.className, node.cst); + this.log("{}->{} > found a matching LDC with value {}", this.context, this.className, node.cst); this.foundLdc = true; return; } @@ -133,7 +133,7 @@ public class BeforeStringInvoke extends BeforeInvoke { @Override protected boolean matchesOrdinal(int ordinal) { - this.log("{} > > found LDC \"{}\" = {}", this.className, this.ldcValue, this.foundLdc); + this.log("{}->{} > > found LDC \"{}\" = {}", this.context, this.className, this.ldcValue, this.foundLdc); return this.foundLdc && super.matchesOrdinal(ordinal); } } From e9f7d752f2cdf8892ea82717c1e8bc1f36f8895a Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 24 Feb 2021 22:18:08 +0000 Subject: [PATCH 21/42] Refactoring so that service impls don't need to camp on transformer pkg --- .../platform/MixinPlatformAgentFMLLegacy.java | 84 +++++++++---------- .../mojang/MixinServiceLaunchWrapper.java | 4 +- .../MixinServiceLaunchWrapperBootstrap.java | 4 +- .../asm/launch/MixinBootstrap.java | 41 ++++++++- .../mixin/transformer/IMixinTransformer.java | 51 +++++++++++ .../transformer/IMixinTransformerFactory.java | 42 ++++++++++ .../mixin/transformer/MixinTransformer.java | 28 ++++++- .../asm/service/IMixinInternal.java | 32 +++++++ .../asm/service/IMixinService.java | 9 ++ .../asm/service/MixinServiceAbstract.java | 58 ++++++++++--- .../org/spongepowered/asm/util/Locals.java | 3 +- .../modlauncher/MixinServiceModLauncher.java | 13 ++- .../MixinTransformationHandler.java | 40 +++++---- 13 files changed, 328 insertions(+), 81 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java create mode 100644 src/main/java/org/spongepowered/asm/service/IMixinInternal.java rename src/modlauncher/java/org/spongepowered/asm/{mixin/transformer => service/modlauncher}/MixinTransformationHandler.java (76%) diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java index ca195b70..56a34f45 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java @@ -140,11 +140,7 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl @Override public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) { - try { - this.clCoreModManager = MixinPlatformAgentFMLLegacy.getCoreModManagerClass(); - } catch (ClassNotFoundException ex) { - MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.", - ex.getMessage()); + if (this.getCoreModManagerClass() == null) { return AcceptResult.INVALID; } @@ -298,30 +294,6 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl public void prepare() { this.initInjectionState |= MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_INJECTION); } - - /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinPlatformAgent - * #initPrimaryContainer() - */ - @Override - public void initPrimaryContainer() { - if (this.clCoreModManager != null) { -// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider"); - this.injectRemapper(); - } - } - - private void injectRemapper() { - try { - MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS); - Class clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader); - Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create"); - IRemapper remapper = (IRemapper)mdCreate.invoke(null); - MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper); - } catch (Exception ex) { - MixinPlatformAgentAbstract.logger.debug("Failed instancing FML remapper adapter, things will probably go horribly for notch-obf'd mods!"); - } - } /* (non-Javadoc) * @see org.spongepowered.asm.launch.platform.IMixinPlatformAgent#inject() @@ -357,6 +329,30 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl return !MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_DEOBF); } + /** + * Attempt to get the FML CoreModManager, tries the post-1.8 namespace first + * and falls back to 1.7.10 if class lookup fails + */ + private Class getCoreModManagerClass() { + if (this.clCoreModManager != null) { + return this.clCoreModManager; + } + + try { + try { + this.clCoreModManager = Class.forName(GlobalProperties.getString( + GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS)); + } catch (ClassNotFoundException ex) { + this.clCoreModManager = Class.forName(MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS_LEGACY); + } + } catch (ClassNotFoundException ex) { + MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.", + ex.getMessage()); + } + + return this.clCoreModManager; + } + /** * Check whether a tweaker ending with tweakName has been enqueued * but not yet visited. @@ -373,19 +369,6 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl return false; } - /** - * Attempt to get the FML CoreModManager, tries the post-1.8 namespace first - * and falls back to 1.7.10 if class lookup fails - */ - private static Class getCoreModManagerClass() throws ClassNotFoundException { - try { - return Class.forName(GlobalProperties.getString( - GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS)); - } catch (ClassNotFoundException ex) { - return Class.forName(MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS_LEGACY); - } - } - @SuppressWarnings("unchecked") private static List getIgnoredMods(Class clCoreModManager) throws IllegalAccessException, InvocationTargetException { Method mdGetIgnoredMods = null; @@ -412,7 +395,22 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl */ @Override public void init() { - // Nothing to do here + if (this.getCoreModManagerClass() != null) { +// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider"); + this.injectRemapper(); + } + } + + private void injectRemapper() { + try { + MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS); + Class clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader); + Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create"); + IRemapper remapper = (IRemapper)mdCreate.invoke(null); + MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper); + } catch (Exception ex) { + MixinPlatformAgentAbstract.logger.debug("Failed instancing FML remapper adapter, things will probably go horribly for notch-obf'd mods!"); + } } /* (non-Javadoc) diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java index 82a11fb5..2ef4c898 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -81,7 +81,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I public static final Keys BLACKBOARD_KEY_TWEAKCLASSES = Keys.of("TweakClasses"); public static final Keys BLACKBOARD_KEY_TWEAKS = Keys.of("Tweaks"); - private static final String MIXIN_TWEAKER_CLASS = "org.spongepowered.asm.launch.MixinTweaker"; + private static final String MIXIN_TWEAKER_CLASS = MixinServiceAbstract.LAUNCH_PACKAGE + "MixinTweaker"; // Consts private static final String STATE_TWEAKER = MixinServiceAbstract.MIXIN_PACKAGE + "EnvironmentStateTweaker"; @@ -618,5 +618,5 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I return 0; } - + } diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java index 0b1aaaf4..bdb726ce 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java @@ -35,6 +35,7 @@ import net.minecraft.launchwrapper.Launch; public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstrap { private static final String SERVICE_PACKAGE = "org.spongepowered.asm.service."; + private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; private static final String MIXIN_UTIL_PACKAGE = "org.spongepowered.asm.util."; private static final String LEGACY_ASM_PACKAGE = "org.spongepowered.asm.lib."; @@ -61,7 +62,8 @@ public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstra // Essential ones Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.SERVICE_PACKAGE); - + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.LAUNCH_PACKAGE); + // Important ones Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.ASM_PACKAGE); Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.LEGACY_ASM_PACKAGE); diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index 87067c65..4f671910 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.launch; +import java.lang.reflect.Constructor; +import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; @@ -32,6 +34,9 @@ import org.spongepowered.asm.launch.platform.CommandLineOptions; import org.spongepowered.asm.launch.platform.MixinPlatformManager; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.mixin.throwables.MixinError; +import org.spongepowered.asm.service.IMixinInternal; +import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; /** @@ -63,11 +68,17 @@ public abstract class MixinBootstrap { */ public static final String VERSION = "0.8.3"; + /** + * Transformer factory + */ + private static final String MIXIN_TRANSFORMER_FACTORY_CLASS = "org.spongepowered.asm.mixin.transformer.MixinTransformer$Factory"; + /** * Log all the things */ private static final Logger logger = LogManager.getLogger("mixin"); + // These are Klass local, with luck this shouldn't be a problem private static boolean initialised = false; private static boolean initState = true; @@ -77,7 +88,7 @@ public abstract class MixinBootstrap { MixinService.boot(); MixinService.getService().prepare(); } - + /** * Platform manager instance */ @@ -134,6 +145,7 @@ public abstract class MixinBootstrap { } MixinBootstrap.registerSubsystem(MixinBootstrap.VERSION); + MixinBootstrap.offerInternals(); if (!MixinBootstrap.initialised) { MixinBootstrap.initialised = true; @@ -207,4 +219,31 @@ public abstract class MixinBootstrap { GlobalProperties.put(GlobalProperties.Keys.INIT, version); } + private static void offerInternals() { + IMixinService service = MixinService.getService(); + + try { + for (IMixinInternal internal : MixinBootstrap.getInternals()) { + service.offer(internal); + } + } catch (AbstractMethodError ex) { + // outdated service + ex.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + private static List getInternals() throws MixinError { + List internals = new ArrayList(); + try { + Class clTransformerFactory = (Class)Class.forName(MixinBootstrap.MIXIN_TRANSFORMER_FACTORY_CLASS); + Constructor ctor = clTransformerFactory.getDeclaredConstructor(); + ctor.setAccessible(true); + internals.add(ctor.newInstance()); + } catch (ReflectiveOperationException ex) { + throw new MixinError(ex); + } + return internals; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java index 183190c7..769ab93f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java @@ -52,6 +52,20 @@ public interface IMixinTransformer { */ public abstract List reload(String mixinClass, ClassNode classNode); + /** + * Called when the transformation reason is computing_frames. The only + * operation we care about here is adding interfaces to target classes but + * at the moment we don't have sufficient scaffolding to determine that + * without triggering re-entrance. Currently just a no-op in order to not + * cause a re-entrance crash under ModLauncher 7.0+. + * + * @param environment Current environment + * @param name Class transformed name + * @param classNode Class tree + * @return true if the class was transformed + */ + public abstract boolean computeFramesForClass(MixinEnvironment environment, String name, ClassNode classNode); + /** * Callback from the hotswap agent and LaunchWrapper Proxy, transform class * bytecode. This method delegates to class generation or class @@ -67,6 +81,43 @@ public interface IMixinTransformer { * @see ILegacyClassTransformer#transformClassBytes(String, String, byte[]) */ public abstract byte[] transformClassBytes(String name, String transformedName, byte[] basicClass); + + /** + * Apply mixins and postprocessors to the supplied class + * + * @param environment Current environment + * @param name Class transformed name + * @param classBytes Class bytecode + * @return Transformed bytecode + */ + public abstract byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes); + + /** + * Apply mixins and postprocessors to the supplied class + * + * @param environment Current environment + * @param name Class transformed name + * @param classNode Class tree + * @return true if the class was transformed + */ + public abstract boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode); + + /** + * Generate the specified mixin-synthetic class + * + * @param environment Current environment + * @param name Class name to generate + * @return Generated bytecode or null if no class was generated + */ + public abstract byte[] generateClass(MixinEnvironment environment, String name); + + /** + * @param environment Current environment + * @param name Class transformed name + * @param classNode Empty classnode to populate + * @return True if the class was generated successfully + */ + public abstract boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode); /** * Get the transformer extensions diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java new file mode 100644 index 00000000..7e3b10ed --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java @@ -0,0 +1,42 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 org.spongepowered.asm.launch.MixinInitialisationError; +import org.spongepowered.asm.service.IMixinInternal; + +/** + * Factory for the mixin transformer, concrete instances of this class are only + * provided to services since only the service should be able to decide when the + * mixin transformer is initialised. + */ +public interface IMixinTransformerFactory extends IMixinInternal { + + /** + * Create a new transformer. + */ + public abstract IMixinTransformer createTransformer() throws MixinInitialisationError; + +} 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 a9b09c74..183248c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -28,6 +28,7 @@ import java.lang.reflect.Constructor; import java.util.List; import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.launch.MixinInitialisationError; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -41,10 +42,26 @@ import org.spongepowered.asm.util.asm.ASM; /** * Transformer which manages the mixin configuration and application process */ -class MixinTransformer extends TreeTransformer implements IMixinTransformer { +final class MixinTransformer extends TreeTransformer implements IMixinTransformer { + + /** + * Impl of mixin transformer factory + */ + static class Factory implements IMixinTransformerFactory { + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory + * #createTransformer() + */ + @Override + public IMixinTransformer createTransformer() throws MixinInitialisationError { + return new MixinTransformer(); + } + + } private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; - + /** * Synthetic class registry */ @@ -70,7 +87,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { */ private final MixinClassGenerator generator; - public MixinTransformer() { + MixinTransformer() { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); Object globalMixinTransformer = environment.getActiveTransformer(); @@ -190,6 +207,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Class tree * @return true if the class was transformed */ + @Override public boolean computeFramesForClass(MixinEnvironment environment, String name, ClassNode classNode) { // TODO compute added interfaces return false; @@ -203,6 +221,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classBytes Class bytecode * @return Transformed bytecode */ + @Override public byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes) { ClassNode classNode = this.readClass(classBytes); if (this.processor.applyMixins(environment, name, classNode)) { @@ -219,6 +238,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Class tree * @return true if the class was transformed */ + @Override public boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode) { return this.processor.applyMixins(environment, name, classNode); } @@ -230,6 +250,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param name Class name to generate * @return Generated bytecode or null if no class was generated */ + @Override public byte[] generateClass(MixinEnvironment environment, String name) { ClassNode classNode = MixinTransformer.createEmptyClass(name); if (this.generator.generateClass(environment, name, classNode)) { @@ -244,6 +265,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Empty classnode to populate * @return True if the class was generated successfully */ + @Override public boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { return this.generator.generateClass(environment, name, classNode); } diff --git a/src/main/java/org/spongepowered/asm/service/IMixinInternal.java b/src/main/java/org/spongepowered/asm/service/IMixinInternal.java new file mode 100644 index 00000000..2e354fd9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/IMixinInternal.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.service; + +/** + * A mixin internal part, offered to services. + */ +public interface IMixinInternal { + +} diff --git a/src/main/java/org/spongepowered/asm/service/IMixinService.java b/src/main/java/org/spongepowered/asm/service/IMixinService.java index aa5c324f..a4f068c6 100644 --- a/src/main/java/org/spongepowered/asm/service/IMixinService.java +++ b/src/main/java/org/spongepowered/asm/service/IMixinService.java @@ -62,6 +62,15 @@ public interface IMixinService { */ public abstract Phase getInitialPhase(); + /** + * Called when the subsystem is offering internal components to the service, + * the service can determine whether to retain or ignore the component based + * on its own requirements. + * + * @param internal Internal component being offered + */ + public abstract void offer(IMixinInternal internal); + /** * Called at the end of subsystem boot */ diff --git a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java index 9e57708a..b5c6a246 100644 --- a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java +++ b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java @@ -26,7 +26,9 @@ package org.spongepowered.asm.service; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -50,6 +52,7 @@ public abstract class MixinServiceAbstract implements IMixinService { // Consts protected static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; protected static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin."; + protected static final String SERVICE_PACKAGE = "org.spongepowered.asm.service."; /** * Logger @@ -62,6 +65,11 @@ public abstract class MixinServiceAbstract implements IMixinService { */ protected final ReEntranceLock lock = new ReEntranceLock(1); + /** + * All internals offered to this service + */ + private final Map, IMixinInternal> internals = new HashMap, IMixinInternal>(); + /** * Service agent instances */ @@ -104,6 +112,46 @@ public abstract class MixinServiceAbstract implements IMixinService { public CompatibilityLevel getMaxCompatibilityLevel() { return null; } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService + * #offer(org.spongepowered.asm.service.IMixinInternal) + */ + @Override + public void offer(IMixinInternal internal) { + this.registerInternal(internal, internal.getClass()); + } + + @SuppressWarnings("unchecked") + private void registerInternal(IMixinInternal internal, Class clazz) { + for (Class iface : clazz.getInterfaces()) { + if (iface == IMixinInternal.class) { + this.internals.put((Class)clazz, internal); + } + this.registerInternal(internal, iface); + } + } + + @SuppressWarnings("unchecked") + protected final T getInternal(Class type) { + for (Class internalType : this.internals.keySet()) { + if (type.isAssignableFrom(internalType)) { + return (T)this.internals.get(internalType); + } + } + + return null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#init() + */ + @Override + public void init() { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + agent.init(); + } + } /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#beginPhase() @@ -120,16 +168,6 @@ public abstract class MixinServiceAbstract implements IMixinService { public void checkEnv(Object bootSource) { } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#init() - */ - @Override - public void init() { - for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { - agent.init(); - } - } - /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#getReEntranceLock() */ diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index f57974a6..0ae2e21d 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -454,7 +454,8 @@ public final class Locals { String desc = lastKnownType[j]; Type localType = local.getType(); if (localType != null) { - desc = "null".equals(localType.getInternalName()) ? Constants.OBJECT_DESC : localType.getDescriptor(); + desc = localType.getSort() >= Type.ARRAY && "null".equals(localType.getInternalName()) + ? Constants.OBJECT_DESC : localType.getDescriptor(); } localNodes[j] = new LocalVariableNode("var" + j, desc, null, label, null, j); diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java index c7782f6e..80791f9e 100644 --- a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java @@ -31,11 +31,12 @@ import org.spongepowered.asm.launch.IClassProcessor; import org.spongepowered.asm.launch.platform.container.ContainerHandleModLauncher; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; -import org.spongepowered.asm.mixin.transformer.MixinTransformationHandler; +import org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory; import org.spongepowered.asm.service.IClassBytecodeProvider; import org.spongepowered.asm.service.IClassProvider; import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.IMixinAuditTrail; +import org.spongepowered.asm.service.IMixinInternal; import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinServiceAbstract; import org.spongepowered.asm.util.IConsumer; @@ -114,6 +115,14 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { public void onStartup() { this.phaseConsumer.accept(Phase.DEFAULT); } + + @Override + public void offer(IMixinInternal internal) { + if (internal instanceof IMixinTransformerFactory) { + this.getTransformationHandler().offer((IMixinTransformerFactory)internal); + } + super.offer(internal); + } // TEMP @SuppressWarnings("deprecation") @@ -212,7 +221,7 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { /** * Get (or create) the transformation handler */ - private IClassProcessor getTransformationHandler() { + private MixinTransformationHandler getTransformationHandler() { if (this.transformationHandler == null) { this.transformationHandler = new MixinTransformationHandler(); } diff --git a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java similarity index 76% rename from src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java rename to src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java index 303efd2e..303e1c7e 100644 --- a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; +package org.spongepowered.asm.service.modlauncher; import java.util.EnumSet; @@ -32,9 +32,13 @@ import org.spongepowered.asm.launch.IClassProcessor; import org.spongepowered.asm.launch.MixinLaunchPlugin; import org.spongepowered.asm.launch.Phases; import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.transformer.IMixinTransformer; +import org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory; import org.spongepowered.asm.service.ISyntheticClassInfo; import org.spongepowered.asm.service.ISyntheticClassRegistry; +import com.google.common.base.Preconditions; + import cpw.mods.modlauncher.api.ITransformerActivity; import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; @@ -43,16 +47,16 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; * application, post processing and synthetic class generation */ public class MixinTransformationHandler implements IClassProcessor { - + /** - * Lock for initialising the transformer + * Mixin transformer factory, from service */ - private final Object initialisationLock = new Object(); + private IMixinTransformerFactory transformerFactory; /** * Transformer pipeline instance */ - private MixinTransformer transformer; + private IMixinTransformer transformer; /** * Synthetic class registry, used so the processor knows when to respond to @@ -60,6 +64,11 @@ public class MixinTransformationHandler implements IClassProcessor { */ private ISyntheticClassRegistry registry; + void offer(IMixinTransformerFactory transformerFactory) { + Preconditions.checkNotNull(transformerFactory, "transformerFactory"); + this.transformerFactory = transformerFactory; + } + /* (non-Javadoc) * @see org.spongepowered.asm.launch.IClassProcessor#handlesClass( * org.objectweb.asm.Type, boolean, java.lang.String) @@ -89,18 +98,13 @@ public class MixinTransformationHandler implements IClassProcessor { if (phase == Phase.BEFORE) { return false; } - - MixinTransformer transformer = null; + if (this.transformer == null) { - synchronized (this.initialisationLock) { - transformer = this.transformer; - if (transformer == null) { - transformer = this.transformer = new MixinTransformer(); - this.registry = transformer.getExtensions().getSyntheticClassRegistry(); - } + if (this.transformerFactory == null) { + throw new IllegalStateException("processClass called before transformer factory offered to transformation handler"); } - } else { - transformer = this.transformer; + this.transformer = this.transformerFactory.createTransformer(); + this.registry = this.transformer.getExtensions().getSyntheticClassRegistry(); } // Don't transform when the reason is mixin (side-loading in progress) @@ -111,14 +115,14 @@ public class MixinTransformationHandler implements IClassProcessor { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); ISyntheticClassInfo syntheticClass = this.registry.findSyntheticClass(classType.getClassName()); if (syntheticClass != null) { - return transformer.generateClass(environment, classType.getClassName(), classNode); + return this.transformer.generateClass(environment, classType.getClassName(), classNode); } if (ITransformerActivity.COMPUTING_FRAMES_REASON.equals(reason)) { - return transformer.computeFramesForClass(environment, classType.getClassName(), classNode); + return this.transformer.computeFramesForClass(environment, classType.getClassName(), classNode); } - return transformer.transformClass(environment, classType.getClassName(), classNode); + return this.transformer.transformClass(environment, classType.getClassName(), classNode); } } From 4e4c72ee223883ae2704535ba3d8266f49ed82f4 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 25 Feb 2021 18:29:32 +0000 Subject: [PATCH 22/42] Some more minor javadoc improvements, update README --- README.MD | 78 ++++++++++++++----- .../asm/mixin/injection/InjectionPoint.java | 66 +++++++++++++--- .../asm/mixin/injection/ModifyVariable.java | 29 ++++++- 3 files changed, 143 insertions(+), 30 deletions(-) diff --git a/README.MD b/README.MD index e35254d8..aaf554e8 100644 --- a/README.MD +++ b/README.MD @@ -3,32 +3,51 @@ ![Mixin Logo](docs/javadoc/resources/logo.png?raw=true) -**Mixin** is a trait/mixin framework for Java using [ASM](http://asm.ow2.org/) -and hooking into the runtime class-loading process via Mojang's -[LegacyLauncher](https://github.com/Mojang/LegacyLauncher) system. +**Mixin** is a trait/mixin framework for Java using [ASM](https://asm.ow2.io/) +and hooking into the runtime classloading process via a set of pluggable +built-in or user-provided services. Built-in services currently support Mojang's +[LegacyLauncher](https://github.com/Mojang/LegacyLauncher) system, though this +is deprecated in favour of [ModLauncher](https://github.com/cpw/modlauncher) by +cpw, which has greater extensibility and has support for Java 8 and later. ### Documentation -The main documentation for **Mixin** can be found in the [Wiki](../../wiki). +The main documentation for **Mixin** can be found in the +[Wiki](https://github.com/SpongePowered/Mixin/wiki). Additional documentation for individual features and annotations can be found in the extensive [Javadoc](http://jenkins.liteloader.com/job/Mixin/javadoc/). For -additional help use the channel [`#mixin` on the -Sponge Discord Server](https://discord.gg/tBcwxz2). +additional help use the channel [`#mixin` on the Sponge Discord Server](https://discord.gg/tBcwxz2). -### Building Mixin -**Mixin** uses the [Gradle](http://gradle.org/) build automation system. To -perform a build, use gradle version 4.9 and execute +### Binaries - gradle +Mixin binaries are available via [Jenkins](https://jenkins.liteloader.com/view/Other/job/Mixin/) +and are published to the following maven repositories: -from within the project root directory. *(If you do not have Gradle installed on -your system you can instead run the supplied Gradle wrapper `gradlew`)* +* https://repo.spongepowered.org/repository/maven-public/ - SNAPHOTs and RELEASE + builds +* https://files.minecraftforge.net/maven/ - RELEASE builds only -### Integration with Eclipse IDE +### Tooling -The **Mixin** project can be integrated easily with Eclipse using Buildship. -Simply choose `Import` -> `Gradle Project` and follow the prompts. +For handling obfuscation tasks, Mixin provides an [Annotation Processor](https://github.com/SpongePowered/Mixin/wiki/Using-the-Mixin-Annotation-Processor) +which works at compile time to generate obfuscation mappings for your toolchain +to apply. If using Gradle 5 or later, annotation processors are no longer +automatically loaded from `compile` configurations and must be specified +explicitly via `annotationProcessor` configurations. For this purpose, Mixin +provides "fat jar" artefacts containing all required dependencies via the +`:processor` classifier. For example if your build uses the dependency +`org.spongepowered:mixin:1.2.3` then your annotationProcessor configuration +should specify dependency `org.spongepowered:mixin:1.2.3:processor`. + +If you are using Mixin in a [Minecraft Forge](https://minecraftforge.net/) +project then the [MixinGradle](https://github.com/SpongePowered/MixinGradle) +plugin can be used to simplify the configuration of the Mixin Annotation +Processor. It provides a simple syntax for configuring the Mixin AP for your +project, see the [MixinGradle README](https://github.com/SpongePowered/MixinGradle/blob/master/README.md) +for how to configure MixinGradle. + +### Integration with Eclipse When developing using **Mixin**, you can use the **Mixin Annotation Processor** within Eclipse to provide context-sensitive errors and warnings to help you more @@ -45,11 +64,12 @@ easily troubleshoot your mixins. To do so: 7. Check the `Enable annotation processing` checkbox 8. Click the `New...` button next to the `Processor options` box * Set `Key` to **reobfSrgFile** - * Set `Value` to the fully-qualified path to the `mcp-srg.srg` file (for Sponge - this can be found in `Sponge/build/srgs/mcp-srg.srg`) + * Set `Value` to the fully-qualified path to the `mcp-srg.srg` file (the + location of the mapping file varies by platform, if you are unsure where to + find it please follow the discord link below). 9. Click `OK` to apply the changes -### Integration with IntelliJ IDEA IDE +### Integration with IntelliJ IDEA Enhanced functionality for working with **Mixin** in IntelliJ IDEA is available via the [Minecraft Development for IntelliJ IDEA](https://plugins.jetbrains.com/idea/plugin/8327) @@ -57,6 +77,11 @@ plugin developed by [DemonWav](https://github.com/demonwav). ### Version History +[Specifying the `minVersion` property in your configurations](https://github.com/SpongePowered/Mixin/wiki/PSA-Forward-Compatibility-Features-in-Mixin) +is extrememly important. The following version history can be used to determine +when features were introduced (and sometimes when major bugs are squashed) in +order to help you determine which `minVersion` you should specify. + @@ -67,13 +92,28 @@ plugin developed by [DemonWav](https://github.com/demonwav). - + + + + + + diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index b762c06f..e5fff052 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -78,15 +78,63 @@ import com.google.common.collect.ImmutableList.Builder; * using intersection (and) or union (or) relationships to allow multiple * strategies to be easily combined.

* - *

You are free to create your own injection point subclasses, but take note - * that it is allowed for a single InjectionPoint instance to be used for - * multiple injections and thus implementing classes MUST NOT cache the insn - * list, event, or nodes instance passed to the {@link #find find} method, as - * each call to {@link #find find} must be considered a separate functional - * contract and the InjectionPoint's lifespan is not linked to the discovery - * lifespan, therefore it is important that the InjectionPoint implementation is - * fully stateless and that calls to {@link #find find} are idempotent. - *

+ *

Built-in Injection Points

+ * + *

The following built-in Injection Points are available:

+ * + *
    + *
  • {@link MethodHead HEAD} - Selects the first insn
  • + *
  • {@link BeforeReturn RETURN} - Selects RETURN insns
  • + *
  • {@link BeforeFinalReturn TAIL} - Selects the last RETURN insn
  • + *
  • {@link BeforeInvoke INVOKE} - Selects method invocations
  • + *
  • {@link AfterInvoke INVOKE_ASSIGN} - Selects STORE insns after method + * invocations which return a value
  • + *
  • {@link BeforeFieldAccess FIELD} - Selects field access insns
  • + *
  • {@link BeforeNew NEW} - Selects object constructions
  • + *
  • {@link BeforeStringInvoke INVOKE_STRING} - Selects method invocations + * where a specific string is passed to the invocation.
  • + *
  • {@link JumpInsnPoint JUMP} - Selects branching (jump) instructions
  • + *
  • {@link BeforeConstant CONSTANT} - Selects constant values
  • + *
+ * + *

Additionally, the two special injection points are available which are + * only supported for use with {@link ModifyVariable @ModifyVariable}:

+ * + *
    + *
  • {@link BeforeLoadLocal LOAD} - Selects xLOAD insns matching the + * ModifyVariable discriminators.
  • + *
  • {@link AfterStoreLocal STORE} - Selects xSTORE insns matching the + * ModifyVariable discriminators.
  • + *
+ * + *

See the javadoc for each type for more details on the scheme used by each + * injection point.

+ * + *

Custom Injection Points

+ * + *

You are free to create your own injection point subclasses. Once defined, + * they can be used by your mixins in one of two ways:

+ * + *
    + *
  1. Specify the fully-qualified name of the injection point class in the + * {@link At#value @At.value}.
  2. + *
  3. Decorate your injection point class with {@link AtCode @AtCode} + * annotation which specifies a namespace and shortcode for the injection + * point, and register the class in your mixin config. You can then specify + * the namespaced code (eg. MYMOD:CUSTOMPOINT) in {@link At#value + * @At.value}.
  4. + *
+ * + *

When writing custom injection points, note that the general contract of + * injection points is that they be entirely - or at least behaviourally - + * stateless. It is allowed for a single InjectionPoint instance to be + * used by the mixin processor for multiple injections and thus implementing + * classes MUST NOT cache the insn list, event, or nodes instance + * passed to the {@link #find find} method, as each call to {@link #find find} + * must be considered a separate contract and the InjectionPoint's lifespan is + * not linked to the discovery lifespan. It is therefore important that the + * InjectionPoint implementation is fully stateless and that calls to + * {@link #find find} are idempotent.

*/ public abstract class InjectionPoint { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 5dd71cfe..a525f02a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -30,6 +30,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; +import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -57,7 +59,9 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * *

The injector has two operating modes, explicit and implicit * , and can operate either on the entire LVT or on the {@link #argsOnly - * ethod arguments only}.

+ * method arguments only}.

+ * + *

Explicit mode

* *

In explicit mode, the variable to capture can be specified by * specifying values for the discriminator arguments {@link #ordinal}, @@ -65,12 +69,32 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * order to attempt to locate the variable to capture. If no local variable * matches any discriminators, the capture fails.

* + *

Implicit mode

+ * *

If no values for the capture discrimiators are specified, the injector * operates in implicit mode. If exactly one variable of the capture * type exists in the target LVT, then capture will succeed. However, if more * than one variable of the required type is encountered in the LVT then an * {@link InvalidInjectionException} is thrown.

* + *

Context-sensitive injection points

+ * + *

Normally the {@link InjectionPoint injection points} specified by {@link + * #at} are independent of the injector being used. With ModifyVariable + * there are two special injection points which consume the discriminator from + * the annotation:

+ * + *
    + *
  • {@link BeforeLoadLocal LOAD} - matches xLOAD insns for + * the variable matched by the discriminator in the target method.
  • + *
  • {@link AfterStoreLocal STORE} - matches xSTORE insns for + * the variable matched by the discriminator in the target method.
  • + *
+ * + *

See the javadoc for each injection point for details.

+ * + *

Notes

+ * *

Like other injectors, the callback signature can optionally include the * target method arguments by simply appending them to the handler method * signature.

@@ -108,7 +132,8 @@ public @interface ModifyVariable { * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. * - * @return {@link At} which identifies the target method invocation + * @return {@link At} which identifies the location to inject inside the + * target method. */ public At at(); From 088e8bcf61b0b95528a7d9042d1678ab603377f2 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 1 Mar 2021 23:40:24 +0000 Subject: [PATCH 23/42] Fix some deprecations --- .../asm/launch/platform/MixinConnectorManager.java | 2 +- .../org/spongepowered/asm/launch/platform/MixinContainer.java | 2 +- .../spongepowered/asm/launch/platform/MixinPlatformManager.java | 1 - src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java | 2 +- .../org/spongepowered/asm/mixin/transformer/PluginHandle.java | 2 +- .../org/spongepowered/asm/service/MixinServiceAbstract.java | 2 +- 6 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java index 36a26c5b..01973cb6 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java @@ -80,7 +80,7 @@ public class MixinConnectorManager { } try { - IMixinConnector connector = connectorClass.newInstance(); + IMixinConnector connector = connectorClass.getDeclaredConstructor().newInstance(); this.connectors.add(connector); MixinConnectorManager.logger.info("Successfully loaded Mixin Connector [" + connectorClassName + "]"); } catch (ReflectiveOperationException ex) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 6477b329..91e10f22 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -70,7 +70,7 @@ public class MixinContainer { String simpleName = clazz.getSimpleName(); MixinContainer.logger.debug("Instancing new {} for {}", simpleName, this.handle); - IMixinPlatformAgent agent = clazz.newInstance(); + IMixinPlatformAgent agent = clazz.getDeclaredConstructor().newInstance(); AcceptResult acceptAction = agent.accept(manager, this.handle); if (acceptAction == AcceptResult.ACCEPTED) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java index 2bb0634c..b4e327eb 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java @@ -297,7 +297,6 @@ public class MixinPlatformManager { */ final void addConnector(String connectorClass) { this.connectors.addConnector(connectorClass); - } } diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 952888bf..9a409533 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -1070,7 +1070,7 @@ public final class MixinEnvironment implements ITokenProvider { @SuppressWarnings("unchecked") Class providerClass = (Class)this.service.getClassProvider().findClass(providerName, true); - IEnvironmentTokenProvider provider = providerClass.newInstance(); + IEnvironmentTokenProvider provider = providerClass.getDeclaredConstructor().newInstance(); this.registerTokenProvider(provider); } catch (Throwable th) { MixinEnvironment.logger.error("Error instantiating " + providerName, th); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java index 31565a5f..3a8ef03b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java @@ -94,7 +94,7 @@ class PluginHandle { if (!Strings.isNullOrEmpty(pluginClassName)) { try { Class pluginClass = service.getClassProvider().findClass(pluginClassName, true); - plugin = (IMixinConfigPlugin)pluginClass.newInstance(); + plugin = (IMixinConfigPlugin)pluginClass.getDeclaredConstructor().newInstance(); } catch (Throwable th) { PluginHandle.logger.error("Error loading companion plugin class [{}] for mixin config [{}]. The plugin may be out of date: {}:{}", pluginClassName, parent, th.getClass().getSimpleName(), th.getMessage(), th); diff --git a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java index b5c6a246..1babae68 100644 --- a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java +++ b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java @@ -230,7 +230,7 @@ public abstract class MixinServiceAbstract implements IMixinService { try { @SuppressWarnings("unchecked") Class agentClass = (Class)this.getClassProvider().findClass(agentClassName, false); - IMixinPlatformAgent agent = agentClass.newInstance(); + IMixinPlatformAgent agent = agentClass.getDeclaredConstructor().newInstance(); if (agent instanceof IMixinPlatformServiceAgent) { this.serviceAgents.add((IMixinPlatformServiceAgent)agent); } From 29c6cc03f482964254a8eebf36d26eaf322d50f7 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 17 Mar 2021 02:33:05 +0000 Subject: [PATCH 24/42] Some refactoring and finalise contract impl of ITargetSelector::next --- .../asm/mixin/gen/AccessorInfo.java | 2 +- .../asm/mixin/gen/InvokerInfo.java | 2 +- .../asm/mixin/injection/Desc.java | 6 + .../injection/callback/CallbackInjector.java | 2 +- .../mixin/injection/code/InjectorTarget.java | 30 +- ...nlyInsnList.java => InsnListReadOnly.java} | 4 +- .../asm/mixin/injection/code/MethodSlice.java | 8 +- .../injection/selectors/ElementNode.java | 682 ++++++++++++++++++ .../injection/selectors/ITargetSelector.java | 1 - .../injection/selectors/InvalidSelector.java | 1 - .../injection/selectors/MemberMatcher.java | 3 +- .../injection/selectors/TargetSelector.java | 41 +- .../selectors/dynamic/DescriptorResolver.java | 10 +- .../dynamic/DynamicSelectorDesc.java | 81 ++- .../dynamic/IResolvedDescriptor.java | 9 +- .../mixin/injection/struct/InjectionInfo.java | 106 ++- .../mixin/injection/struct/MemberInfo.java | 114 ++- .../asm/mixin/struct/MemberRef.java | 72 +- .../asm/mixin/transformer/ClassInfo.java | 2 +- .../transformer/MixinApplicatorStandard.java | 2 +- .../org/spongepowered/asm/util/Handles.java | 82 +++ .../asm/util/asm/ElementNode.java | 303 -------- 22 files changed, 1045 insertions(+), 518 deletions(-) rename src/main/java/org/spongepowered/asm/mixin/injection/code/{ReadOnlyInsnList.java => InsnListReadOnly.java} (98%) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java create mode 100644 src/main/java/org/spongepowered/asm/util/Handles.java delete mode 100644 src/main/java/org/spongepowered/asm/util/asm/ElementNode.java diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index e85b9a20..52672d85 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -39,6 +39,7 @@ import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; @@ -49,7 +50,6 @@ import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; -import org.spongepowered.asm.util.asm.ElementNode; import com.google.common.base.Joiner; import com.google.common.base.Strings; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java index ed2b4b68..b65d0c15 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -27,6 +27,7 @@ package org.spongepowered.asm.mixin.gen; import org.objectweb.asm.Type; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; @@ -36,7 +37,6 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; -import org.spongepowered.asm.util.asm.ElementNode; /** * Information about an invoker diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java index 50fd27d1..97ec046b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -111,6 +111,12 @@ public @interface Desc { */ public Class[] args() default { }; + /** + * The next elements of this descriptor path, evaluated in order for each + * recurse point. + */ + // public Next[] next() default { }; + /** * The minimum number of times this selector should match. By default the * selector is allowed to match no targets. When selecting fields or methods diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index 4d976bd8..ea8802ff 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -457,7 +457,7 @@ public class CallbackInjector extends Injector { MethodNode callbackMethod = this.methodNode; if (!callback.checkDescriptor(this.methodNode.desc)) { - if (this.info.getTargets().size() > 1) { + if (this.info.getTargetCount() > 1) { return; // Look for a match in other targets before failing } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java index 23c053c7..9347f3a7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java @@ -32,6 +32,7 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.util.Annotations; @@ -50,15 +51,26 @@ public class InjectorTarget { /** * Cache of slices */ - private final Map cache = new HashMap(); + private final Map cache = new HashMap(); /** * Target method data */ private final Target target; + /** + * Selector which selected this method + */ + private final ITargetSelector selector; + + /** + * Name of the mixin which merged the target, if any + */ private final String mergedBy; + /** + * Priority of the mixin which merged the target, if any + */ private final int mergedPriority; /** @@ -67,9 +79,10 @@ public class InjectorTarget { * @param context owner * @param target target */ - public InjectorTarget(ISliceContext context, Target target) { + public InjectorTarget(ISliceContext context, Target target, ITargetSelector selector) { this.context = context; this.target = target; + this.selector = selector; AnnotationNode merged = Annotations.getVisible(target.method, MixinMerged.class); this.mergedBy = Annotations.getValue(merged, "mixin"); @@ -95,6 +108,13 @@ public class InjectorTarget { return this.target.method; } + /** + * Get the selector which selected this target + */ + public ITargetSelector getSelector() { + return this.selector; + } + /** * Get whether this target method was merged by another mixin */ @@ -125,14 +145,14 @@ public class InjectorTarget { * @return insn slice */ public InsnList getSlice(String id) { - ReadOnlyInsnList slice = this.cache.get(id); + InsnListReadOnly slice = this.cache.get(id); if (slice == null) { MethodSlice sliceInfo = this.context.getSlice(id); if (sliceInfo != null) { slice = sliceInfo.getSlice(this.target.method); } else { // No slice exists so just wrap the method insns - slice = new ReadOnlyInsnList(this.target.method.instructions); + slice = new InsnListReadOnly(this.target.method.instructions); } this.cache.put(id, slice); } @@ -154,7 +174,7 @@ public class InjectorTarget { * Dispose all cached instruction lists */ public void dispose() { - for (ReadOnlyInsnList insns : this.cache.values()) { + for (InsnListReadOnly insns : this.cache.values()) { insns.dispose(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java similarity index 98% rename from src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java rename to src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java index 528ebac6..70c86574 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java @@ -34,11 +34,11 @@ import org.objectweb.asm.tree.InsnList; * instances so that custom InjectionPoint implementations cannot modify the * insn list whilst inspecting it. */ -class ReadOnlyInsnList extends InsnList { +class InsnListReadOnly extends InsnList { private InsnList insnList; - public ReadOnlyInsnList(InsnList insns) { + public InsnListReadOnly(InsnList insns) { this.insnList = insns; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java index 4de644ca..77b28703 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -57,7 +57,7 @@ public final class MethodSlice { * identified by start and end to be accessed. In essence * this class provides a view of the underlying InsnList. */ - static final class InsnListSlice extends ReadOnlyInsnList { + static final class InsnListSlice extends InsnListReadOnly { /** * ListIterator for the slice view, wraps an iterator returned by the @@ -359,7 +359,7 @@ public final class MethodSlice { * @param method method to slice * @return read only slice */ - public ReadOnlyInsnList getSlice(MethodNode method) { + public InsnListReadOnly getSlice(MethodNode method) { int max = method.instructions.size() - 1; int start = this.find(method, this.from, 0, 0, this.name + "(from)"); int end = this.find(method, this.to, max, start, this.name + "(to)"); @@ -373,7 +373,7 @@ public final class MethodSlice { } if (start == 0 && end == max) { - return new ReadOnlyInsnList(method.instructions); + return new InsnListReadOnly(method.instructions); } return new InsnListSlice(method.instructions, start, end); @@ -398,7 +398,7 @@ public final class MethodSlice { } Deque nodes = new LinkedList(); - ReadOnlyInsnList insns = new ReadOnlyInsnList(method.instructions); + InsnListReadOnly insns = new InsnListReadOnly(method.instructions); boolean result = injectionPoint.find(method.desc, insns, nodes); Selector select = injectionPoint.getSelector(); if (nodes.size() != 1 && select == Selector.ONE) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java new file mode 100644 index 00000000..52ac2036 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java @@ -0,0 +1,682 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.objectweb.asm.Handle; +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.InsnList; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.util.Handles; + +import com.google.common.base.Strings; + +/** + * Wrapper for all node types supported by {@link ITargetSelector target + * selectors} ({@link FieldNode}, {@link MethodNode}, {@link FieldInsnNode}, + * {@link MethodInsnNode} and {@link InvokeDynamicInsnNode}) which allows access + * to common properties of things which are basically "arbitrary node with + * owner, name and descriptor" + * + * @param node type + */ +public abstract class ElementNode { + + /** + * ElementNode for MethodNode + */ + static class ElementNodeMethod extends ElementNode { + + private final ClassNode owner; + + private final MethodNode method; + + ElementNodeMethod(ClassNode owner, MethodNode method) { + this.owner = owner; + this.method = method; + } + + @Override + public boolean isMethod() { + return true; + } + + @Override + public MethodNode getMethod() { + return this.method; + } + + @Override + public String getOwner() { + return this.owner != null ? this.owner.name : null; + } + + @Override + public String getName() { + return this.method.name; + } + + @Override + public String getDesc() { + return this.method.desc; + } + + @Override + public String getSignature() { + return this.method.signature; + } + + @Override + public MethodNode get() { + return this.method; + } + + @Override + public boolean equals(Object obj) { + return this.method.equals(obj); + } + + @Override + public int hashCode() { + return this.method.hashCode(); + } + + } + + /** + * ElementNode for FieldNode + */ + static class ElementNodeField extends ElementNode { + + private final ClassNode owner; + + private final FieldNode field; + + ElementNodeField(ClassNode owner, FieldNode field) { + this.owner = owner; + this.field = field; + } + + @Override + public boolean isField() { + return true; + } + + @Override + public FieldNode getField() { + return this.field; + } + + @Override + public String getOwner() { + return this.owner != null ? this.owner.name : null; + } + + @Override + public String getName() { + return this.field.name; + } + + @Override + public String getDesc() { + return this.field.desc; + } + + @Override + public String getSignature() { + return this.field.signature; + } + + @Override + public FieldNode get() { + return this.field; + } + + @Override + public boolean equals(Object obj) { + return this.field.equals(obj); + } + + @Override + public int hashCode() { + return this.field.hashCode(); + } + + } + + /** + * ElementNode for MethodInsnNode + */ + static class ElementNodeMethodInsn extends ElementNode { + + private MethodInsnNode insn; + + ElementNodeMethodInsn(MethodInsnNode method) { + this.insn = method; + } + + @Override + public boolean isMethod() { + return true; + } + + @Override + public AbstractInsnNode getInsn() { + return this.insn; + } + + @Override + public String getOwner() { + return this.insn.owner; + } + + @Override + public String getName() { + return this.insn.name; + } + + @Override + public String getDesc() { + return this.insn.desc; + } + + @Override + public String getSignature() { + return null; + } + + @Override + public MethodInsnNode get() { + return this.insn; + } + + @Override + public boolean equals(Object obj) { + return this.insn.equals(obj); + } + + @Override + public int hashCode() { + return this.insn.hashCode(); + } + + } + + /** + * ElementNode for InvokeDynamicInsnNode + */ + static class ElementNodeInvokeDynamicInsn extends ElementNode { + + private InvokeDynamicInsnNode insn; + + private Type samMethodType; + + private Handle implMethod; + + private Type instantiatedMethodType; + + ElementNodeInvokeDynamicInsn(InvokeDynamicInsnNode invokeDynamic) { + this.insn = invokeDynamic; + + if (invokeDynamic.bsmArgs != null && invokeDynamic.bsmArgs.length > 1) { + Object samMethodType = invokeDynamic.bsmArgs[0]; + Object implMethod = invokeDynamic.bsmArgs[1]; + Object instantiatedMethodType = invokeDynamic.bsmArgs[2]; + if (samMethodType instanceof Type && implMethod instanceof Handle && instantiatedMethodType instanceof Type) { + this.samMethodType = (Type)samMethodType; + this.implMethod = (Handle)implMethod; + this.instantiatedMethodType = (Type)instantiatedMethodType; + } + } + } + + @Override + public boolean isMethod() { + return this.implMethod == null || !Handles.isField(this.implMethod); + } + + @Override + public AbstractInsnNode getInsn() { + return this.insn; + } + + @Override + public String getOwner() { + return this.implMethod != null ? this.implMethod.getOwner() : this.insn.name; + } + + @Override + public String getName() { + return this.insn.name; + } + + @Override + public String getSyntheticName() { + return this.implMethod != null ? this.implMethod.getName() : this.insn.name; + } + + @Override + public String getDesc() { + return this.implMethod != null ? this.implMethod.getDesc() : this.insn.desc; + } + + @Override + public String getDelegateDesc() { + return this.samMethodType != null ? this.samMethodType.getDescriptor() : this.getDesc(); + } + + @Override + public String getImplDesc() { + return this.instantiatedMethodType != null ? this.instantiatedMethodType.getDescriptor() : this.getDesc(); + } + + @Override + public String getSignature() { + return null; + } + + @Override + public InvokeDynamicInsnNode get() { + return this.insn; + } + + @Override + public boolean equals(Object obj) { + return this.insn.equals(obj); + } + + @Override + public int hashCode() { + return this.insn.hashCode(); + } + + } + + /** + * ElementNode for FieldInsnNode + */ + static class ElementNodeFieldInsn extends ElementNode { + + private FieldInsnNode insn; + + ElementNodeFieldInsn(FieldInsnNode field) { + this.insn = field; + } + + @Override + public boolean isField() { + return true; + } + + @Override + public AbstractInsnNode getInsn() { + return this.insn; + } + + @Override + public String getOwner() { + return this.insn.owner; + } + + @Override + public String getName() { + return this.insn.name; + } + + @Override + public String getDesc() { + return this.insn.desc; + } + + @Override + public String getSignature() { + return null; + } + + @Override + public FieldInsnNode get() { + return this.insn; + } + + @Override + public boolean equals(Object obj) { + return this.insn.equals(obj); + } + + @Override + public int hashCode() { + return this.insn.hashCode(); + } + + } + + /** + * Wrapper iterator for method insns + */ + static class ElementNodeIterator implements Iterator> { + + private final Iterator iter; + + private final boolean filterDynamic; + + ElementNodeIterator(Iterator iter, boolean filterDynamic) { + this.iter = iter; + this.filterDynamic = filterDynamic; + } + + @Override + public boolean hasNext() { + return this.iter.hasNext(); + } + + @Override + public ElementNode next() { + AbstractInsnNode elem = this.iter.next(); + return !this.filterDynamic || (elem != null && elem.getOpcode() == Opcodes.INVOKEDYNAMIC) ? ElementNode.of(elem) : null; + } + + } + + /** + * Wrapper for InsnList which returns node iterator + */ + static class ElementNodeIterable implements Iterable> { + + private final Iterable iterable; + + private final boolean filterDynamic; + + public ElementNodeIterable(Iterable iterable, boolean filterDynamic) { + this.iterable = iterable; + this.filterDynamic = filterDynamic; +} + + @Override + public Iterator> iterator() { + return new ElementNodeIterator(this.iterable.iterator(), this.filterDynamic); + } + + } + + /** + * Get whether this element is a method + */ + public boolean isMethod() { + return false; + } + + /** + * get whether this element is a field + */ + public boolean isField() { + return false; + } + + /** + * get whether this element is an instruction + */ + public boolean isInsn() { + return false; + } + + /** + * Get the {@link MethodNode} if this member is a method, otherwise returns + * null + */ + public MethodNode getMethod() { + return null; + } + + /** + * Get the {@link FieldNode} if this member is a field, otherwise returns + * null + */ + public FieldNode getField() { + return null; + } + + /** + * Get the {@link AbstractInsnNode instruction} if this member is an insn, + * otherwise returns null + */ + public AbstractInsnNode getInsn() { + return null; + } + + /** + * Get the element owner's name, if this element has an owner, otherwise + * returns null + */ + public abstract String getOwner(); + + /** + * Get the element name + */ + public abstract String getName(); + + /** + * Get the synthetic element name. For INVOKEDYNAMIC elements this is the + * real name of the lambda method implementing the delegate. + */ + public String getSyntheticName() { + return this.getName(); + } + + /** + * Get the element descriptor. For INVOKEDYNAMIC this is the full descriptor + * of the lambda (including prepended captures). + */ + public abstract String getDesc(); + + /** + * For INVOKEDYNAMIC elements, returns original descriptor of the delegate. + */ + public String getDelegateDesc() { + return this.getDesc(); + } + + /** + * For INVOKEDYNAMIC elements, returns specialised descriptor of the + * delegate (lambda descriptor without prepended captures), can be the same + * as the delegate descriptor or more specialised. + */ + public String getImplDesc() { + return this.getDesc(); + } + + /** + * Get the element signature, can be null + */ + public abstract String getSignature(); + + /** + * Returns the node with horrible duck typing + */ + public abstract TNode get(); + + @Override + public String toString() { + String desc = Strings.nullToEmpty(this.getDesc()); + if (!desc.isEmpty() && this.isField()) { + desc = ":" + desc; + } + String owner = Strings.nullToEmpty(this.getOwner()); + if (!owner.isEmpty()) { + owner = "L" + owner + ";"; + } + return String.format("%s%%s", owner, Strings.nullToEmpty(this.getName()), desc); + } + + /** + * Create an ElementNode wrapper for the supplied method node + * + * @param owner class which owns the method or null + * @param method Method node to wrap + * @return ElementNode + */ + public static ElementNode of(ClassNode owner, MethodNode method) { + return new ElementNodeMethod(owner, method); + } + + /** + * Create an ElementNode wrapper for the supplied field node + * + * @param owner class which owns the field or null + * @param field Field node to wrap + * @return ElementNode + */ + public static ElementNode of(ClassNode owner, FieldNode field) { + return new ElementNodeField(owner, field); + } + + /** + * Create an ElementNode wrapper for the supplied node object + * + * @param owner class which owns the node or null + * @param node Node to wrap + * @param Node type + * @return ElementNode + * @throws IllegalArgumentException if the supplied argument is not a + * {@link MethodNode} or {@link FieldNode} + */ + @SuppressWarnings("unchecked") + public static ElementNode of(ClassNode owner, TNode node) { + if (node instanceof ElementNode) { + return (ElementNode)node; + } else if (node instanceof MethodNode) { + return (ElementNode)new ElementNodeMethod(owner, (MethodNode)node); + } else if (node instanceof FieldNode) { + return (ElementNode)new ElementNodeField(owner, (FieldNode)node); + } else if (node instanceof MethodInsnNode) { + return (ElementNode)new ElementNodeMethodInsn((MethodInsnNode)node); + } else if (node instanceof InvokeDynamicInsnNode) { + return (ElementNode)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node); + } else if (node instanceof FieldInsnNode) { + return (ElementNode)new ElementNodeFieldInsn((FieldInsnNode)node); + } + throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName()); + } + + /** + * Create an ElementNode wrapper for the supplied node object + * + * @param node Node to wrap + * @param Node type + * @return ElementNode + * @throws IllegalArgumentException if the supplied argument is not a + * {@link MethodNode} or {@link FieldNode} + */ + @SuppressWarnings("unchecked") + public static ElementNode of(TNode node) { + if (node instanceof MethodInsnNode) { + return (ElementNode)new ElementNodeMethodInsn((MethodInsnNode)node); + } else if (node instanceof InvokeDynamicInsnNode) { + return (ElementNode)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node); + } else if (node instanceof FieldInsnNode) { + return (ElementNode)new ElementNodeFieldInsn((FieldInsnNode)node); + } + return null; + } + + /** + * Convert the supplied list of nodes to a list of wrapped ElementNodes + * + * @param owner Owner of the supplied nodes, can be null + * @param list List of nodes + * @param Node type + * @return List of wrapped nodes + */ + public static List> listOf(ClassNode owner, List list) { + List> nodes = new ArrayList>(); + for (TNode node : list) { + nodes.add(ElementNode.of(owner, node)); + } + return nodes; + } + + /** + * Get a list of wrapped ElementNodes for the fields of the supplied owner + * class + * + * @param owner Class to get fields, must not be null + * @return List of wrapped nodes + */ + public static List> fieldList(ClassNode owner) { + List> fields = new ArrayList>(); + for (FieldNode field : owner.fields) { + fields.add(new ElementNodeField(owner, field)); + } + return fields; + } + + /** + * Get a list of wrapped ElementNodes for the methods of the supplied owner + * class + * + * @param owner Class to get methods, must not be null + * @return List of wrapped nodes + */ + public static List> methodList(ClassNode owner) { + List> methods = new ArrayList>(); + for (MethodNode method : owner.methods) { + methods.add(new ElementNodeMethod(owner, method)); + } + return methods; + } + + /** + * Get a wrapped version of the supplied insn list which returns element + * nodes for each (supported) instruction (FieldInsnNode, MethodInsnNode and + * InvokeDynamicInsnNode). + * + * @param insns Insn list to wrap + * @return Wrapper for insn list + */ + public static Iterable> insnList(InsnList insns) { + return new ElementNodeIterable(insns, false); + } + + /** + * Get a wrapped version of the supplied insn list which returns element + * nodes for every INVOKEDYNAMIC instruction only + * + * @param insns Insn list to wrap + * @return Wrapper for insn list + */ + public static Iterable> dynamicInsnList(InsnList insns) { + return new ElementNodeIterable(insns, true); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 642a41ab..00e62ead 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -28,7 +28,6 @@ import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.mixin.injection.Desc; import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.util.asm.ElementNode; /** * Target Selectors are used to identify target members in a class, with the diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java index 42feb510..33238a66 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -25,7 +25,6 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; -import org.spongepowered.asm.util.asm.ElementNode; /** * Since the contract of {@link TargetSelector#parse} prohibits returing diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java index f3d77f03..25f331de 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -31,7 +31,6 @@ import java.util.regex.PatternSyntaxException; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; -import org.spongepowered.asm.util.asm.ElementNode; /** * A {@link ITargetSelector Target Selector} which matches an element of @@ -231,7 +230,7 @@ public final class MemberMatcher implements ITargetSelector { */ @Override public MatchResult match(ElementNode node) { - return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); + return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc()); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index f5a6815c..2d7e61ce 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -29,6 +29,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -50,7 +51,6 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.util.Annotations; -import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.asm.util.logging.MessageRouter; @@ -71,14 +71,14 @@ public final class TargetSelector { /** * Any exact match returned by the query */ - public final TNode exactMatch; + public final ElementNode exactMatch; /** * All candidates returned by the query */ - public final List candidates; + public final List> candidates; - Result(TNode exactMatch, List candidates) { + Result(ElementNode exactMatch, List> candidates) { this.exactMatch = exactMatch; this.candidates = candidates; } @@ -98,10 +98,10 @@ public final class TargetSelector { public TNode getSingleResult(boolean strict) { int resultCount = this.candidates.size(); if (this.exactMatch != null) { - return this.exactMatch; + return this.exactMatch.get(); } if (resultCount == 1 || !strict) { - return this.candidates.get(0); + return this.candidates.get(0).get(); } throw new IllegalStateException((resultCount == 0 ? "No" : "Multiple") + " candidates were found"); } @@ -456,9 +456,9 @@ public final class TargetSelector { * @param Node type * @return query result */ - public static Result run(ITargetSelector selector, List> nodes) { - List candidates = new ArrayList(); - TNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates); + public static Result run(ITargetSelector selector, Iterable> nodes) { + List> candidates = new ArrayList>(); + ElementNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates); return new Result(exactMatch, candidates); } @@ -470,12 +470,12 @@ public final class TargetSelector { * @param Node type * @return query result */ - public static Result run(Iterable selector, List> nodes) { - TNode exactMatch = null; - List candidates = new ArrayList(); + public static Result run(Iterable selector, Iterable> nodes) { + ElementNode exactMatch = null; + List> candidates = new ArrayList>(); for (ITargetSelector target : selector) { - TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); + ElementNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); if (exactMatch == null) { exactMatch = selectorExactMatch; } @@ -484,22 +484,23 @@ public final class TargetSelector { return new Result(exactMatch, candidates); } - private static TNode runSelector(ITargetSelector selector, List> nodes, List candidates) { + private static ElementNode runSelector(ITargetSelector selector, Iterable> nodes, + List> candidates) { int matchCount = 0; - TNode exactMatch = null; - for (ElementNode element : nodes) { + ElementNode exactMatch = null; + for (Iterator> iterator = nodes.iterator(); iterator.hasNext();) { + ElementNode element = iterator.next(); MatchResult match = selector.match(element); if (match.isMatch()) { matchCount++; if (matchCount > selector.getMaxMatchCount()) { break; } - TNode node = element.get(); - if (!candidates.contains(node)) { - candidates.add(node); + if (!candidates.contains(element)) { + candidates.add(element); } if (exactMatch == null && match.isExactMatch()) { - exactMatch = node; + exactMatch = element; } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java index 8257c664..cd8ff753 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -121,7 +121,10 @@ public final class DescriptorResolver { return Type.VOID_TYPE; } Type ownerClass = this.desc.getTypeValue("owner"); - return ownerClass == Type.VOID_TYPE ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass; + if (ownerClass != Type.VOID_TYPE) { + return ownerClass; + } + return this.context != null ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass; } @Override @@ -164,6 +167,11 @@ public final class DescriptorResolver { return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1); } + @Override + public List getNext() { + return this.desc != null ? this.desc.getAnnotationList("next") : Collections.emptyList(); + } + } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index 7175cab2..e3f48c9b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.injection.selectors.dynamic; +import java.util.List; + import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; @@ -32,6 +34,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Desc; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; @@ -43,7 +46,6 @@ import org.spongepowered.asm.mixin.injection.selectors.MatchResult; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; -import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.base.Strings; @@ -168,7 +170,26 @@ import com.google.common.base.Strings; */ @SelectorId("Desc") @SelectorAnnotation(Desc.class) -public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName { +public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName { + + /** + * Next selector + */ + final class Next extends DynamicSelectorDesc { + + private final int index; + + Next(int index, IResolvedDescriptor next) { + super(null, null, next.getOwner(), next.getName(), next.getArgs(), next.getReturnType(), next.getMatches(), null); + this.index = index; + } + + @Override + public ITargetSelector next() { + return DynamicSelectorDesc.this.next(this.index + 1); + } + + } /** * Parser/resolver error mesage, only stored if the descriptor is invalid so @@ -216,28 +237,40 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge */ private final Quantifier matches; + /** + * Annotation for next, parsed on demand + */ + private final List next; + private DynamicSelectorDesc(IResolvedDescriptor desc) { - this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches()); + this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches(), + desc.getNext()); } private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) { - this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier); + this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier, desc.next); + } + + private DynamicSelectorDesc(DynamicSelectorDesc desc, Type owner) { + this(desc.parseException, desc.id, owner, desc.name, desc.args, desc.returnType, desc.matches, desc.next); } private DynamicSelectorDesc(InvalidSelectorException ex) { - this(ex, null, null, null, null, null, Quantifier.NONE); + this(ex, null, null, null, null, null, Quantifier.NONE, null); } - private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches) { + protected DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches, + List then) { this.parseException = ex; this.id = id; this.owner = owner; - this.name = name; + this.name = Strings.emptyToNull(name); this.args = args; this.returnType = returnType; this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; this.matches = matches; + this.next = then; } /** @@ -333,7 +366,9 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge if (started) { sb.append(", "); } - sb.append("name = \"").append(this.name).append("\""); + if (this.name != null) { + sb.append("value = \"").append(this.name).append("\""); + } if (this.args.length > 0) { sb.append(", args = { "); @@ -396,9 +431,19 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge @Override public ITargetSelector next() { - return this; // Recurse + return this.next(0); } + protected ITargetSelector next(int index) { + if (index >= 0 && index < this.next.size()) { + IAnnotationHandle nextAnnotation = this.next.get(index); + IResolvedDescriptor descriptor = DescriptorResolver.resolve(nextAnnotation, null); + return new Next(index, descriptor); + } + + return null; + } + @Override public ITargetSelector configure(Configure request, String... args) { request.checkArgs(args); @@ -414,12 +459,10 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge } break; case MOVE: - return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, - this.matches); + return new DynamicSelectorDesc(this, Type.getObjectType(args[0])); case CLEAR_LIMITS: if (this.getMinMatchCount() != 0 || this.getMaxMatchCount() < Integer.MAX_VALUE) { - return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, - Quantifier.ANY); + return new DynamicSelectorDesc(this, Quantifier.ANY); } break; default: @@ -457,9 +500,9 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge if (node == null) { return MatchResult.NONE; } else if (node.isMethod()) { - return this.matches(node.getOwnerName(), node.getName(), node.getDesc(), this.methodDesc); + return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.methodDesc); } else { - return this.matches(node.getOwnerName(), node.getName(), node.getDesc(), this.returnType.getInternalName()); + return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.returnType.getInternalName()); } } @@ -482,12 +525,14 @@ public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITarge private MatchResult matches(String owner, String name, String desc, String compareWithDesc) { if (!compareWithDesc.equals(desc)) { return MatchResult.NONE; - } else if (!this.owner.getInternalName().equals(owner)) { + } else if (this.owner != Type.VOID_TYPE && !this.owner.getInternalName().equals(owner)) { return MatchResult.NONE; - } else if (this.name.equals(name)) { + } else if (this.name != null && this.name.equals(name)) { return MatchResult.EXACT_MATCH; - } else if (this.name.equalsIgnoreCase(name)) { + } else if (this.name != null && this.name.equalsIgnoreCase(name)) { return MatchResult.MATCH; + } else if (this.name == null) { + return MatchResult.EXACT_MATCH; } return MatchResult.NONE; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java index c6a99687..39a0860f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.injection.selectors.dynamic; +import java.util.List; + import org.objectweb.asm.Type; import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.asm.IAnnotationHandle; @@ -33,7 +35,7 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle; * descriptor was not resolved then {@link #isResolved} returns false. */ public interface IResolvedDescriptor { - + /** * Get whether the descriptor was successfully resolved */ @@ -83,5 +85,10 @@ public interface IResolvedDescriptor { * Get the specified matches values from the resolved descriptor. */ public abstract Quantifier getMatches(); + + /** + * Get the values specified for next, if any + */ + public abstract List getNext(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 428d436e..8e233442 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -30,10 +30,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; -import java.util.Deque; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -58,6 +56,7 @@ import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.code.MethodSlice; import org.spongepowered.asm.mixin.injection.code.MethodSlices; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; @@ -77,7 +76,6 @@ import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.ASM; -import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.logging.MessageRouter; @@ -162,6 +160,33 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } } + /** + * Selected target, paired with the selector which identified it + */ + static class SelectedTarget { + + private final ITargetSelector root; + + final ITargetSelector selector; + + final MethodNode method; + + SelectedTarget(ITargetSelector root, ITargetSelector selector, MethodNode method) { + this.root = root; + this.selector = selector; + this.method = method; + } + + SelectedTarget(ITargetSelector selector, MethodNode method) { + this(null, selector, method); + } + + ITargetSelector getRoot() { + return this.root != null ? this.root : this.selector; + } + + } + /** * Default conform prefix for handler methods */ @@ -194,10 +219,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC */ protected final boolean isStatic; + /** + * Target selector(s) + */ + protected final Set selectors = new LinkedHashSet(); + /** * Target method(s) */ - protected final Deque targets = new ArrayDeque(); + protected final List targets = new ArrayList(); /** * Method slice descriptors parsed from the annotation @@ -296,12 +326,13 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC List injectionPoints = this.readInjectionPoints(); this.parseRequirements(); - this.findMethods(this.parseTargets()); + this.parseSelectors(); + this.findTargets(); this.parseInjectionPoints(injectionPoints); this.injector = this.parseInjector(this.annotation); } - protected Set parseTargets() { + protected void parseSelectors() { Set selectors = new LinkedHashSet(); TargetSelector.parse(Annotations.getValue(this.annotation, "method", false), this, selectors); TargetSelector.parse(Annotations.getValue(this.annotation, "target", false), this, selectors); @@ -312,12 +343,10 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC this.annotationType, this.methodName)); } - Set attachedSelectors = new LinkedHashSet(); - // Validate and attach the parsed selectors for (ITargetSelector selector : selectors) { try { - attachedSelectors.add(selector.validate().attach(this)); + this.selectors.add(selector.validate().attach(this)); } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: %s. %s", this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus())); @@ -331,8 +360,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC ex.getMessage())); } } - - return attachedSelectors; } protected List readInjectionPoints() { @@ -387,9 +414,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC */ public void prepare() { this.targetNodes.clear(); - for (MethodNode targetMethod : this.targets) { - Target target = this.mixin.getTargetMethod(targetMethod); - InjectorTarget injectorTarget = new InjectorTarget(this, target); + for (SelectedTarget targetMethod : this.targets) { + Target target = this.mixin.getTargetMethod(targetMethod.method); + InjectorTarget injectorTarget = new InjectorTarget(this, target, targetMethod.selector); try { this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); } catch (SelectorException ex) { @@ -459,12 +486,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } /** - * Get methods being injected into + * Get number of methods being injected into * - * @return methods being injected into + * @return count of methods being injected into */ - public Collection getTargets() { - return this.targets; + public int getTargetCount() { + return this.targets.size(); } /** @@ -543,20 +570,26 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } /** - * Finds methods in the target class which match searchFor - * - * @param selectors members to search for + * Find methods in the target class which match the parsed selectors */ - private void findMethods(Set selectors) { + protected void findTargets() { this.targets.clear(); + this.findRootTargets(); + this.validateTargets(); + } + /** + * Evaluate the root selectors parsed from this injector, find the root + * targets and store them in the {@link #targets} collection. + */ + private void findRootTargets() { // When remapping refmap is enabled this implies we are in a development // environment. In certain circumstances including the descriptor for // the method may actually fail, so we will do a second pass without the // descriptor if this happens. int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1; - for (ITargetSelector selector : selectors) { + for (ITargetSelector selector : this.selectors) { selector = selector.configure(Configure.SELECT_MEMBER); int matchCount = 0; @@ -564,12 +597,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC // Second pass ignores descriptor ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); - if (permissiveSelector == selector) { - // Selector is already permissive, so skip the second pass - passes = 1; - } + int selectorPasses = (permissiveSelector == selector) ? 1 : passes; - scan: for (int pass = 0; pass < passes && matchCount < 1; pass++) { + scan: for (int pass = 0; pass < selectorPasses && matchCount < 1; pass++) { ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector; for (MethodNode target : this.classNode.methods) { if (passSelector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { @@ -578,7 +608,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null; if (maxCount <= 1 || ((this.isStatic || !Bytecode.isStatic(target)) && target != this.method && !isMixinMethod)) { this.checkTarget(target); - this.targets.add(target); + this.targets.add(new SelectedTarget(passSelector, target)); } if (matchCount >= maxCount) { @@ -595,7 +625,13 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()))); } } - + } + + /** + * Post-search validation that some targets were found, we can fail-fast if + * no targets were actually identified + */ + protected void validateTargets() { this.targetCount = this.targets.size(); if (this.targetCount > 0) { return; @@ -604,17 +640,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if ((this.mixin.getOption(Option.DEBUG_INJECTORS) && this.expectedCallbackCount > 0)) { throw new InvalidInjectionException(this, String.format("Injection validation failed: %s annotation on %s could not find any targets matching %s in %s. %s%s", - this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } else if (this.requiredCallbackCount > 0) { throw new InvalidInjectionException(this, String.format("Critical injection failure: %s annotation on %s could not find any targets matching %s in %s. %s%s", - this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } } - private void checkTarget(MethodNode target) { + protected void checkTarget(MethodNode target) { AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class); if (merged == null) { return; @@ -641,7 +677,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : ""; } - + /** * Parse an injector from the specified method (if an injector annotation is * present). If no injector annotation is present then null is @@ -733,7 +769,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } return sb.toString(); } - + /** * Register an injector info class. The supplied class must be decorated * with an {@link AnnotationType} annotation for registration purposes. diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index 36de13e2..ee629a16 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -28,6 +28,7 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; @@ -43,7 +44,6 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; -import org.spongepowered.asm.util.asm.ElementNode; import com.google.common.base.Objects; import com.google.common.base.Strings; @@ -216,6 +216,11 @@ import com.google.common.base.Strings; */ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor { + /** + * Separator for elements in the path + */ + private static final String ARROW = "->"; + /** * Member owner in internal form but without L;, can be null */ @@ -246,6 +251,11 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ private final String input; + /** + * The actual String value passed into the {@link #parse} method + */ + private final String tail; + /** * ctor * @@ -253,18 +263,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param matches Quantifier specifying the number of matches required */ public MemberInfo(String name, Quantifier matches) { - this(name, null, null, matches, null); - } - - /** - * ctor - * - * @param name Member name, must not be null - * @param minMatches Min number of matches required - * @param maxMatches Max number of matches allowed - */ - public MemberInfo(String name, int minMatches, int maxMatches) { - this(name, null, null, new Quantifier(minMatches, maxMatches), null); + this(name, null, null, matches, null, null); } /** @@ -276,20 +275,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param matches Quantifier specifying the number of matches required */ public MemberInfo(String name, String owner, Quantifier matches) { - this(name, owner, null, matches, null); - } - - /** - * ctor - * - * @param name Member name, must not be null - * @param owner Member owner, can be null otherwise must be in internal form - * without L; - * @param minMatches Min number of matches required - * @param maxMatches Max number of matches allowed - */ - public MemberInfo(String name, String owner, int minMatches, int maxMatches) { - this(name, owner, null, new Quantifier(minMatches, maxMatches), null); + this(name, owner, null, matches, null, null); } /** @@ -301,7 +287,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param desc Member descriptor, can be null */ public MemberInfo(String name, String owner, String desc) { - this(name, owner, desc, Quantifier.DEFAULT, null); + this(name, owner, desc, Quantifier.DEFAULT, null, null); } /** @@ -314,35 +300,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param matches Quantifier specifying the number of matches required */ public MemberInfo(String name, String owner, String desc, Quantifier matches) { - this(name, owner, desc, matches, null); - } - - /** - * ctor - * - * @param name Member name, must not be null - * @param owner Member owner, can be null otherwise must be in internal form - * without L; - * @param desc Member descriptor, can be null - * @param minMatches Min number of matches required - * @param maxMatches Max number of matches allowed - */ - public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches) { - this(name, owner, desc, new Quantifier(minMatches, maxMatches), null); - } - - /** - * ctor - * - * @param name Member name, must not be null - * @param owner Member owner, can be null otherwise must be in internal form - * without L; - * @param desc Member descriptor, can be null - * @param minMatches Min number of matches required - * @param maxMatches Max number of matches allowed - */ - public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches, String input) { - this(name, owner, desc, new Quantifier(minMatches, maxMatches), input); + this(name, owner, desc, matches, null, null); } /** @@ -354,7 +312,20 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param desc Member descriptor, can be null * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, String desc, Quantifier matches, String input) { + public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail) { + this(name, owner, desc, matches, tail, null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail, String input) { if (owner != null && owner.contains(".")) { throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format"); } @@ -364,6 +335,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.desc = desc; this.matches = matches; this.forceField = false; + this.tail = tail; this.input = input; } @@ -377,6 +349,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.matches = Quantifier.DEFAULT; this.forceField = false; this.input = null; + this.tail = null; if (insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; @@ -404,6 +377,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.desc = mapping.getDesc(); this.matches = Quantifier.SINGLE; this.forceField = mapping.getType() == IMapping.Type.FIELD; + this.tail = null; this.input = null; } @@ -418,6 +392,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.desc = method.getDesc(); this.matches = remapped.matches; this.forceField = false; + this.tail = null; this.input = null; } @@ -433,12 +408,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.desc = original.desc; this.matches = original.matches; this.forceField = original.forceField; + this.tail = original.tail; this.input = null; } @Override public ITargetSelector next() { - return null; // Not supported yet + return Strings.isNullOrEmpty(this.tail) ? null : MemberInfo.parse(this.tail, null); } @Override @@ -476,7 +452,8 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec String quantifier = this.matches.toString(); String desc = this.desc != null ? this.desc : ""; String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : ""); - return owner + name + quantifier + separator + desc; + String tail = this.tail != null ? " " + MemberInfo.ARROW + " " + this.tail : ""; + return owner + name + quantifier + separator + desc + tail; } /** @@ -718,7 +695,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ @Override public MatchResult match(ElementNode node) { - return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); + return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc()); } /* (non-Javadoc) @@ -808,12 +785,12 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec switch (request) { case SELECT_MEMBER: if (this.matches.isDefault()) { - return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE); + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE, this.tail); } break; case SELECT_INSTRUCTION: if (this.matches.isDefault()) { - return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY); + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail); } break; case MOVE: @@ -826,7 +803,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec return this.transform(null); case CLEAR_LIMITS: if (this.matches.getMin() != 0 || this.matches.getMax() < Integer.MAX_VALUE) { - return new MemberInfo(this.name, this.owner, this.desc, 0, Integer.MAX_VALUE); + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail); } break; default: @@ -896,6 +873,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); + String tail = null; + + int arrowPos = name.indexOf(MemberInfo.ARROW); + if (arrowPos > -1) { + tail = name.substring(arrowPos + 2); + name = name.substring(0, arrowPos); + } if (context != null) { name = context.remap(name); @@ -959,7 +943,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec name = null; } - return new MemberInfo(name, owner, desc, quantifier, input); + return new MemberInfo(name, owner, desc, quantifier, tail, input); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java index b8baec32..f2461fb7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java @@ -29,12 +29,13 @@ import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Handles; /** * Reference to a field or method that also includes invocation instructions. * - *

To instances are defined to be equal if they both refer to the same method - * and have the same invocation instructions.

+ *

Two instances are defined to be equal if they both refer to the same + * member and have the same invocation instructions.

*/ public abstract class MemberRef { @@ -209,26 +210,12 @@ public abstract class MemberRef { @Override public boolean isField() { - switch (this.handle.getTag()) { - case Opcodes.H_INVOKEVIRTUAL: - case Opcodes.H_INVOKESTATIC: - case Opcodes.H_INVOKEINTERFACE: - case Opcodes.H_INVOKESPECIAL: - case Opcodes.H_NEWINVOKESPECIAL: - return false; - case Opcodes.H_GETFIELD: - case Opcodes.H_GETSTATIC: - case Opcodes.H_PUTFIELD: - case Opcodes.H_PUTSTATIC: - return true; - default: - throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); - } + return Handles.isField(this.handle); } @Override public int getOpcode() { - int opcode = MemberRef.opcodeFromTag(this.handle.getTag()); + int opcode = Handles.opcodeFromTag(this.handle.getTag()); if (opcode == 0) { throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); } @@ -237,12 +224,11 @@ public abstract class MemberRef { @Override public void setOpcode(int opcode) { - int tag = MemberRef.tagFromOpcode(opcode); + int tag = Handles.tagFromOpcode(opcode); if (tag == 0) { throw new MixinTransformerError("Invalid opcode " + Bytecode.getOpcodeName(opcode) + " for method handle " + this.handle + "."); } - boolean itf = tag == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.objectweb.asm.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), itf); + this.setHandle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -252,8 +238,7 @@ public abstract class MemberRef { @Override public void setOwner(String owner) { - boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), itf); + this.setHandle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -263,8 +248,7 @@ public abstract class MemberRef { @Override public void setName(String name) { - boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), itf); + this.setHandle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -274,23 +258,14 @@ public abstract class MemberRef { @Override public void setDesc(String desc) { - boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, itf); + this.setHandle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, this.handle.isInterface()); } + + public void setHandle(int tag, String owner, String name, String desc, boolean isInterface) { + this.handle = new org.objectweb.asm.Handle(tag, owner, name, desc, isInterface); + } + } - - private static final int[] H_OPCODES = { - 0, // invalid - Opcodes.GETFIELD, // H_GETFIELD - Opcodes.GETSTATIC, // H_GETSTATIC - Opcodes.PUTFIELD, // H_PUTFIELD - Opcodes.PUTSTATIC, // H_PUTSTATIC - Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL - Opcodes.INVOKESTATIC, // H_INVOKESTATIC - Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL - Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL - Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE - }; /** * Whether this member is a field. @@ -357,8 +332,8 @@ public abstract class MemberRef { @Override public String toString() { - String name = Bytecode.getOpcodeName(this.getOpcode()); - return String.format("%s for %s.%s%s%s", name, this.getOwner(), this.getName(), this.isField() ? ":" : "", this.getDesc()); + return String.format("%s for %s.%s%s%s", Bytecode.getOpcodeName(this.getOpcode()), this.getOwner(), this.getName(), this.isField() ? ":" : "", + this.getDesc()); } @Override @@ -379,17 +354,4 @@ public abstract class MemberRef { return this.toString().hashCode(); } - static int opcodeFromTag(int tag) { - return (tag >= 0 && tag < MemberRef.H_OPCODES.length) ? MemberRef.H_OPCODES[tag] : 0; - } - - static int tagFromOpcode(int opcode) { - for (int tag = 1; tag < MemberRef.H_OPCODES.length; tag++) { - if (MemberRef.H_OPCODES[tag] == opcode) { - return tag; - } - } - return 0; - } - } 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 6180247b..6ed2e166 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -251,7 +251,7 @@ public final class ClassInfo { return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); } } - + /** * Information about a member in this class */ diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 0ab8774d..c94ca2ce 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -1140,7 +1140,7 @@ class MixinApplicatorStandard { */ protected final FieldNode findTargetField(FieldNode searchFor) { for (FieldNode target : this.targetClass.fields) { - if (target.name.equals(searchFor.name)) { + if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc)) { return target; } } diff --git a/src/main/java/org/spongepowered/asm/util/Handles.java b/src/main/java/org/spongepowered/asm/util/Handles.java new file mode 100644 index 00000000..55709f2b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Handles.java @@ -0,0 +1,82 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 org.objectweb.asm.Handle; +import org.objectweb.asm.Opcodes; + +/** + * Utility class for working with method and field handles + */ +public final class Handles { + + private static final int[] H_OPCODES = { + 0, // invalid + Opcodes.GETFIELD, // H_GETFIELD + Opcodes.GETSTATIC, // H_GETSTATIC + Opcodes.PUTFIELD, // H_PUTFIELD + Opcodes.PUTSTATIC, // H_PUTSTATIC + Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL + Opcodes.INVOKESTATIC, // H_INVOKESTATIC + Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL + Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL + Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE + }; + + private Handles() { + } + + public static boolean isField(Handle handle) { + switch (handle.getTag()) { + case Opcodes.H_INVOKEVIRTUAL: + case Opcodes.H_INVOKESTATIC: + case Opcodes.H_INVOKEINTERFACE: + case Opcodes.H_INVOKESPECIAL: + case Opcodes.H_NEWINVOKESPECIAL: + return false; + case Opcodes.H_GETFIELD: + case Opcodes.H_GETSTATIC: + case Opcodes.H_PUTFIELD: + case Opcodes.H_PUTSTATIC: + return true; + default: + throw new IllegalArgumentException("Invalid tag " + handle.getTag() + " for method handle " + handle + "."); + } + } + + public static int opcodeFromTag(int tag) { + return (tag >= 0 && tag < Handles.H_OPCODES.length) ? Handles.H_OPCODES[tag] : 0; + } + + public static int tagFromOpcode(int opcode) { + for (int tag = 1; tag < Handles.H_OPCODES.length; tag++) { + if (Handles.H_OPCODES[tag] == opcode) { + return tag; + } + } + return 0; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java b/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java deleted file mode 100644 index aa213c3e..00000000 --- a/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * This file is part of Mixin, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * 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.asm; - -import java.util.ArrayList; -import java.util.List; - -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldNode; -import org.objectweb.asm.tree.MethodNode; - -/** - * Holder for {@link FieldNode} and {@link MethodNode} for consumers which can - * handle both types (since they have a lot in common), with common accessors - * for overlapping properties. - * - * @param node type - */ -public abstract class ElementNode { - - /** - * ElementNode for MethodNode - */ - static class ElementNodeMethod extends ElementNode { - - private MethodNode method; - - ElementNodeMethod(ClassNode owner, MethodNode method) { - super(owner); - this.method = method; - } - - @Override - public boolean isMethod() { - return true; - } - - @Override - public MethodNode getMethod() { - return this.method; - } - - @Override - public String getName() { - return this.method.name; - } - - @Override - public String getDesc() { - return this.method.desc; - } - - @Override - public String getSignature() { - return this.method.signature; - } - - @Override - public MethodNode get() { - return this.method; - } - - @Override - public String toString() { - return String.format("MethodElement[%s%s]", this.method.name, this.method.desc); - } - - } - - /** - * ElementNode for FieldNode - */ - static class ElementNodeField extends ElementNode { - - private FieldNode field; - - ElementNodeField(ClassNode owner, FieldNode field) { - super(owner); - this.field = field; - } - - @Override - public boolean isField() { - return true; - } - - @Override - public FieldNode getField() { - return this.field; - } - - @Override - public String getName() { - return this.field.name; - } - - @Override - public String getDesc() { - return this.field.desc; - } - - @Override - public String getSignature() { - return this.field.signature; - } - - @Override - public FieldNode get() { - return this.field; - } - - @Override - public String toString() { - return String.format("FieldElement[%s:%s]", this.field.name, this.field.desc); - } - - } - - /** - * The class which owns this element, can be null - */ - private final ClassNode owner; - - protected ElementNode(ClassNode owner) { - this.owner = owner; - } - - /** - * Get whether this element is a method - */ - public boolean isMethod() { - return false; - } - - /** - * get whether this element is a field - */ - public boolean isField() { - return false; - } - - /** - * Get the {@link MethodNode} if this member is a method, otherwise returns - * null - */ - public MethodNode getMethod() { - return null; - } - - /** - * Get the {@link FieldNode} if this member is a field, otherwise returns - * null - */ - public FieldNode getField() { - return null; - } - - /** - * Get the element's owner, can be null - */ - public ClassNode getOwner() { - return this.owner; - } - - /** - * Get the element owner's name, if this element has an owner, otherwise - * returns null - */ - public String getOwnerName() { - return this.owner != null ? this.owner.name : null; - } - - /** - * Get the element name - */ - public abstract String getName(); - - /** - * Get the element descriptor - */ - public abstract String getDesc(); - - /** - * Get the element signature, can be null - */ - public abstract String getSignature(); - - /** - * Returns the node with horrible duck typing - */ - public abstract TNode get(); - - /** - * Create an ElementNode wrapper for the supplied method node - * - * @param owner class which owns the method or null - * @param method Method node to wrap - * @return ElementNode - */ - public static ElementNode of(ClassNode owner, MethodNode method) { - return new ElementNodeMethod(owner, method); - } - - /** - * Create an ElementNode wrapper for the supplied field node - * - * @param owner class which owns the field or null - * @param field Field node to wrap - * @return ElementNode - */ - public static ElementNode of(ClassNode owner, FieldNode field) { - return new ElementNodeField(owner, field); - } - - /** - * Create an ElementNode wrapper for the supplied node object - * - * @param owner class which owns the node or null - * @param node Node to wrap - * @param Node type - * @return ElementNode - * @throws IllegalArgumentException if the supplied argument is not a - * {@link MethodNode} or {@link FieldNode} - */ - @SuppressWarnings("unchecked") - public static ElementNode of(ClassNode owner, TNode node) { - if (node instanceof MethodNode) { - return (ElementNode)new ElementNodeMethod(owner, (MethodNode)node); - } else if (node instanceof FieldNode) { - return (ElementNode)new ElementNodeField(owner, (FieldNode)node); - } - throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName()); - } - - /** - * Convert the supplied list of nodes to a list of wrapped ElementNodes - * - * @param owner Owner of the supplied nodes, can be null - * @param list List of nodes - * @param Node type - * @return List of wrapped nodes - */ - public static List> listOf(ClassNode owner, List list) { - List> nodes = new ArrayList>(); - for (TNode node : list) { - nodes.add(ElementNode.of(owner, node)); - } - return nodes; - } - - /** - * Get a list of wrapped ElementNodes for the fields of the supplied owner - * class - * - * @param owner Class to get fields, must not be null - * @return List of wrapped nodes - */ - public static List> fieldList(ClassNode owner) { - List> fields = new ArrayList>(); - for (FieldNode field : owner.fields) { - fields.add(new ElementNodeField(owner, field)); - } - return fields; - } - - /** - * Get a list of wrapped ElementNodes for the methods of the supplied owner - * class - * - * @param owner Class to get methods, must not be null - * @return List of wrapped nodes - */ - public static List> methodList(ClassNode owner) { - List> methods = new ArrayList>(); - for (MethodNode method : owner.methods) { - methods.add(new ElementNodeMethod(owner, method)); - } - return methods; - } - -} From b1cd46c8c4960eae026bcd6dd9bafb59cafa4d52 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 17 Mar 2021 21:21:09 +0000 Subject: [PATCH 25/42] Remove now-redundant overload for match --- .../mixin/injection/points/BeforeInvoke.java | 3 +- .../injection/selectors/ElementNode.java | 30 ++++++++++++++----- .../injection/selectors/ITargetSelector.java | 9 ------ .../injection/selectors/InvalidSelector.java | 12 -------- .../injection/selectors/MemberMatcher.java | 20 ------------- .../dynamic/DynamicSelectorDesc.java | 19 ------------ .../mixin/injection/struct/MemberInfo.java | 16 ---------- 7 files changed, 24 insertions(+), 85 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index e47ae8cc..d531fec0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -38,6 +38,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.selectors.ElementNode; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; @@ -196,7 +197,7 @@ public class BeforeInvoke extends InjectionPoint { MemberInfo nodeInfo = new MemberInfo(insn); this.log("{}->{} is considering {}", this.context, this.className, nodeInfo); - if (target.match(insn).isExactMatch()) { + if (target.match(ElementNode.of(insn)).isExactMatch()) { this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className); if (++matchCount > target.getMaxMatchCount()) { break; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java index 52ac2036..1d4de64b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java @@ -39,7 +39,6 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.util.Handles; import com.google.common.base.Strings; @@ -188,7 +187,7 @@ public abstract class ElementNode { } @Override - public boolean isMethod() { + public boolean isInsn() { return true; } @@ -263,8 +262,13 @@ public abstract class ElementNode { } @Override - public boolean isMethod() { - return this.implMethod == null || !Handles.isField(this.implMethod); + public boolean isInvokeDynamic() { + return true; + } + + @Override + public boolean isInsn() { + return true; } @Override @@ -336,7 +340,7 @@ public abstract class ElementNode { } @Override - public boolean isField() { + public boolean isInsn() { return true; } @@ -431,26 +435,36 @@ public abstract class ElementNode { } /** - * Get whether this element is a method + * Get whether this element is a method, implies getMethod() will return + * a value */ public boolean isMethod() { return false; } /** - * get whether this element is a field + * get whether this element is a field, implies getField() will return + * a value */ public boolean isField() { return false; } /** - * get whether this element is an instruction + * get whether this element is an instruction, implies getInsn() will return + * a value */ public boolean isInsn() { return false; } + /** + * get whether this element is an INVOKEDYNAMIC insn + */ + public boolean isInvokeDynamic() { + return false; + } + /** * Get the {@link MethodNode} if this member is a method, otherwise returns * null diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 00e62ead..20212a7e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.injection.selectors; -import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.mixin.injection.Desc; import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; @@ -235,13 +234,5 @@ public interface ITargetSelector { * @return true if this selector can match the supplied field */ public abstract MatchResult match(ElementNode node); - - /** - * Test whether this selector matches the supplied instruction node - * - * @param insn instruction node to test - * @return true if this selector can match the supplied instruction - */ - public abstract MatchResult match(AbstractInsnNode insn); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java index 33238a66..6d7fb435 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -24,8 +24,6 @@ */ package org.spongepowered.asm.mixin.injection.selectors; -import org.objectweb.asm.tree.AbstractInsnNode; - /** * Since the contract of {@link TargetSelector#parse} prohibits returing * null, instances of this selector are returned when supplied arguments @@ -138,14 +136,4 @@ public class InvalidSelector implements ITargetSelector { return MatchResult.NONE; } - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #match(org.objectweb.asm.tree.AbstractInsnNode) - */ - @Override - public MatchResult match(AbstractInsnNode insn) { - this.validate(); - return MatchResult.NONE; - } - } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java index 25f331de..2ab8dd4f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -28,10 +28,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.MethodInsnNode; - /** * A {@link ITargetSelector Target Selector} which matches an element of * candidate members using a regular expression. This selector is not remappable @@ -233,22 +229,6 @@ public final class MemberMatcher implements ITargetSelector { return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc()); } - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #matches(org.objectweb.asm.tree.AbstractInsnNode) - */ - @Override - public MatchResult match(AbstractInsnNode insn) { - if (insn instanceof MethodInsnNode) { - MethodInsnNode method = (MethodInsnNode)insn; - return this.matches(method.owner, method.name, method.desc); - } else if (insn instanceof FieldInsnNode) { - FieldInsnNode field = (FieldInsnNode)insn; - return this.matches(field.owner, field.name, field.desc); - } - return MatchResult.NONE; - } - private MatchResult matches(String... args) { MatchResult result = MatchResult.NONE; // boolean exactOnly = true; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index e3f48c9b..a1768f3b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -27,9 +27,6 @@ package org.spongepowered.asm.mixin.injection.selectors.dynamic; import java.util.List; import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Desc; import org.spongepowered.asm.mixin.injection.Inject; @@ -506,22 +503,6 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec } } - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #matches(org.objectweb.asm.tree.AbstractInsnNode) - */ - @Override - public MatchResult match(AbstractInsnNode insn) { - if (insn instanceof MethodInsnNode) { - MethodInsnNode method = (MethodInsnNode)insn; - return this.matches(method.owner, method.name, method.desc, this.methodDesc); - } else if (insn instanceof FieldInsnNode) { - FieldInsnNode field = (FieldInsnNode)insn; - return this.matches(field.owner, field.name, field.desc, this.returnType.getInternalName()); - } - return MatchResult.NONE; - } - private MatchResult matches(String owner, String name, String desc, String compareWithDesc) { if (!compareWithDesc.equals(desc)) { return MatchResult.NONE; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index ee629a16..0bd081b5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -698,22 +698,6 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc()); } - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #matches(org.objectweb.asm.tree.AbstractInsnNode) - */ - @Override - public MatchResult match(AbstractInsnNode insn) { - if (insn instanceof MethodInsnNode) { - MethodInsnNode method = (MethodInsnNode)insn; - return this.matches(method.owner, method.name, method.desc); - } else if (insn instanceof FieldInsnNode) { - FieldInsnNode field = (FieldInsnNode)insn; - return this.matches(field.owner, field.name, field.desc); - } - return MatchResult.NONE; - } - /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector * #matches(java.lang.String, java.lang.String, java.lang.String) From 9109a19d5e7d68d11bbea5cd7c4981d28fe4f9e7 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 13 Apr 2021 21:22:35 +0100 Subject: [PATCH 26/42] Fixes for regressions related to selectors, fixes #479, fixes #480 --- .../injection/selectors/ElementNode.java | 124 +++++++++++++----- .../dynamic/DynamicSelectorDesc.java | 6 +- .../org/spongepowered/asm/util/Locals.java | 3 +- 3 files changed, 96 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java index 1d4de64b..e72ea285 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java @@ -39,6 +39,7 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.util.Handles; import com.google.common.base.Strings; @@ -53,6 +54,69 @@ import com.google.common.base.Strings; */ public abstract class ElementNode { + /** + * Element node type, returned by getType so consumers don't need + * to do instanceof checks, and allows switching on element type in a more + * expressive way + */ + public static enum NodeType { + + /** + * None or unknown type + */ + UNDEFINED(false, false, false), + + /** + * A method node + */ + METHOD(true, false, false), + + /** + * A field node + */ + FIELD(false, true, false), + + /** + * An invoke instruction + */ + METHOD_INSN(false, false, true), + + /** + * A get or put field instruction + */ + FIELD_INSN(false, false, true), + + /** + * An INVOKEDYNAMIC instruction + */ + INVOKEDYNAMIC_INSN(false, false, true); + + /** + * Whether this node holds a method, implies that calling getMethod + * will return a value + */ + public final boolean hasMethod; + + /** + * Whether this node holds a field, implies that calling getField + * will return a value + */ + public final boolean hasField; + + /** + * Whether this node holds an insn, implies that calling getInsn + * will return a value + */ + public final boolean hasInsn; + + private NodeType(boolean isMethod, boolean isField, boolean isInsn) { + this.hasMethod = isMethod; + this.hasField = isField; + this.hasInsn = isInsn; + } + + } + /** * ElementNode for MethodNode */ @@ -68,8 +132,8 @@ public abstract class ElementNode { } @Override - public boolean isMethod() { - return true; + public NodeType getType() { + return NodeType.METHOD; } @Override @@ -128,6 +192,11 @@ public abstract class ElementNode { this.field = field; } + @Override + public NodeType getType() { + return NodeType.FIELD; + } + @Override public boolean isField() { return true; @@ -187,8 +256,8 @@ public abstract class ElementNode { } @Override - public boolean isInsn() { - return true; + public NodeType getType() { + return NodeType.METHOD_INSN; } @Override @@ -262,13 +331,13 @@ public abstract class ElementNode { } @Override - public boolean isInvokeDynamic() { - return true; + public NodeType getType() { + return NodeType.INVOKEDYNAMIC_INSN; } @Override - public boolean isInsn() { - return true; + public boolean isField() { + return this.implMethod != null && Handles.isField(this.implMethod); } @Override @@ -340,10 +409,15 @@ public abstract class ElementNode { } @Override - public boolean isInsn() { - return true; + public NodeType getType() { + return NodeType.FIELD_INSN; } + @Override + public boolean isField() { + return true; + } + @Override public AbstractInsnNode getInsn() { return this.insn; @@ -435,35 +509,19 @@ public abstract class ElementNode { } /** - * Get whether this element is a method, implies getMethod() will return - * a value - */ - public boolean isMethod() { - return false; - } - - /** - * get whether this element is a field, implies getField() will return - * a value + * Get whether this element is a field type and the descriptor is a bare + * type descriptor without arguments. Otherwise assumes the descriptor is a + * method descriptor. */ public boolean isField() { return false; } /** - * get whether this element is an instruction, implies getInsn() will return - * a value + * Get the type of this ElementNode, the return value can be used to + * determine which accessor ({@link #getMethod}, {@link #getField} */ - public boolean isInsn() { - return false; - } - - /** - * get whether this element is an INVOKEDYNAMIC insn - */ - public boolean isInvokeDynamic() { - return false; - } + public abstract NodeType getType(); /** * Get the {@link MethodNode} if this member is a method, otherwise returns @@ -550,7 +608,7 @@ public abstract class ElementNode { if (!owner.isEmpty()) { owner = "L" + owner + ";"; } - return String.format("%s%%s", owner, Strings.nullToEmpty(this.getName()), desc); + return String.format("%s%s%s", owner, Strings.nullToEmpty(this.getName()), desc); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index a1768f3b..a1315850 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -496,10 +496,10 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec public MatchResult match(ElementNode node) { if (node == null) { return MatchResult.NONE; - } else if (node.isMethod()) { - return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.methodDesc); - } else { + } else if (node.isField()) { return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.returnType.getInternalName()); + } else { + return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.methodDesc); } } diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 0ae2e21d..e0dcb008 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -173,7 +173,8 @@ public final class Locals { if (storeInsn != null) { LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); frame[storeInsn.var] = storedLocal; - if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && Type.getType(storedLocal.desc).getSize() == 2) { + if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && storedLocal.desc != null + && Type.getType(storedLocal.desc).getSize() == 2) { frame[storeInsn.var + 1] = null; // TOP } storeInsn = null; From 6f5dce173b44b7be55252cd5dfcca6f064ad2c99 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 14 Apr 2021 19:31:06 +0100 Subject: [PATCH 27/42] Fix for the fix for computing frames which now fixes #481 and fixes #482 --- .../injection/points/BeforeConstant.java | 2 +- .../injection/struct/InjectionNodes.java | 2 +- .../asm/mixin/transformer/ClassInfo.java | 3 +- .../org/spongepowered/asm/util/Bytecode.java | 18 ++++++++-- .../org/spongepowered/asm/util/Locals.java | 34 +++++++++++++++---- 5 files changed, 47 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index 8cab6c01..e93769b2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -236,7 +236,7 @@ public class BeforeConstant extends InjectionPoint { if (matchesInsn) { this.log(" BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal); if (this.ordinal == -1 || this.ordinal == ordinal) { - this.log(" BeforeConstant found {}", Bytecode.describeNode(insn).trim()); + this.log(" BeforeConstant found {}", Bytecode.describeNode(insn, false)); nodes.add(insn); found = true; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java index 235d7f17..16d87323 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java @@ -205,7 +205,7 @@ public class InjectionNodes extends ArrayList { */ @Override public String toString() { - return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget).replaceAll("\\s+", " ")); + return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget, false)); } } 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 6ed2e166..e72486ca 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -248,7 +248,8 @@ public final class ClassInfo { */ @Override public String toString() { - return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); + return String.format("FrameData[index=%d, type=%s, locals=%d size=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals, + this.size); } } diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index f4a33ba4..1fec392f 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -413,15 +413,27 @@ public final class Bytecode { * @return human-readable description of node */ public static String describeNode(AbstractInsnNode node) { + return Bytecode.describeNode(node, true); + } + + /** + * Gets a description of the supplied node for debugging purposes + * + * @param node node to describe + * @param listFormat format the returned string so that returned nodes line + * up (node names aligned to 14 chars) + * @return human-readable description of node + */ + public static String describeNode(AbstractInsnNode node, boolean listFormat) { if (node == null) { - return String.format(" %-14s ", "null"); + return listFormat ? String.format(" %-14s ", "null") : "null"; } if (node instanceof LabelNode) { return String.format("[%s]", ((LabelNode)node).getLabel()); } - String out = String.format(" %-14s ", node.getClass().getSimpleName().replace("Node", "")); + String out = String.format(listFormat ? " %-14s " : "%s ", node.getClass().getSimpleName().replace("Node", "")); if (node instanceof JumpInsnNode) { out += String.format("[%s] [%s]", Bytecode.getOpcodeName(node), ((JumpInsnNode)node).label.getLabel()); } else if (node instanceof VarInsnNode) { @@ -445,6 +457,8 @@ public final class Bytecode { out += (((IntInsnNode)node).operand); } else if (node instanceof FrameNode) { out += String.format("[%s] ", Bytecode.getOpcodeName(((FrameNode)node).type, "H_INVOKEINTERFACE", -1)); + } else if (node instanceof TypeInsnNode) { + out += String.format("[%s] %s", Bytecode.getOpcodeName(node), ((TypeInsnNode)node).desc); } else { out += String.format("[%s] ", Bytecode.getOpcodeName(node)); } diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index e0dcb008..035a8b80 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -135,7 +135,11 @@ public final class Locals { */ public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node) { for (int i = 0; i < 3 && (node instanceof LabelNode || node instanceof LineNumberNode); i++) { - node = Locals.nextNode(method.instructions, node); + AbstractInsnNode nextNode = Locals.nextNode(method.instructions, node); + if (nextNode instanceof FrameNode) { // Do not ffwd over frames + break; + } + node = nextNode; } ClassInfo classInfo = ClassInfo.forName(classNode.name); @@ -166,6 +170,7 @@ public final class Locals { int frameSize = local; int frameIndex = -1; int lastFrameSize = local; + int knownFrameSize = local; VarInsnNode storeInsn = null; for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { @@ -173,9 +178,11 @@ public final class Locals { if (storeInsn != null) { LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); frame[storeInsn.var] = storedLocal; + knownFrameSize = Math.max(knownFrameSize, storeInsn.var + 1); if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && storedLocal.desc != null && Type.getType(storedLocal.desc).getSize() == 2) { frame[storeInsn.var + 1] = null; // TOP + knownFrameSize = Math.max(knownFrameSize, storeInsn.var + 2); } storeInsn = null; } @@ -187,12 +194,12 @@ public final class Locals { break handleFrame; } + int frameNodeSize = Locals.computeFrameSize(frameNode); FrameData frameData = frameIndex < frames.size() ? frames.get(frameIndex) : null; if (frameData != null) { if (frameData.type == Opcodes.F_FULL) { - frameSize = Math.min(frameSize, frameData.locals); - lastFrameSize = frameSize; + knownFrameSize = lastFrameSize = frameSize = Math.min(frameNodeSize, frameData.size); } else { frameSize = Locals.getAdjustedFrameSize(frameSize, frameData); } @@ -200,17 +207,25 @@ public final class Locals { frameSize = Locals.getAdjustedFrameSize(frameSize, frameNode); } - if (frameNode.type == Opcodes.F_CHOP || frameNode.type == Opcodes.F_NEW) { + // Sanity check + if (frameSize < 0) { + throw new IllegalStateException(String.format("Locals entered an invalid state evaluating %s::%s%s at instruction %d (%s). " + + "Initial frame size is %d, calculated a frame size of %d with %s", classNode.name, method.name, method.desc, + method.instructions.indexOf(insn), Bytecode.describeNode(insn, false), initialFrameSize, frameSize, frameData)); + } + + if ((frameData == null && (frameNode.type == Opcodes.F_CHOP || frameNode.type == Opcodes.F_NEW)) + || (frameData != null && frameData.type == Opcodes.F_CHOP)) { for (int framePos = frameSize; framePos < frame.length; framePos++) { frame[framePos] = null; } - lastFrameSize = frameSize; + knownFrameSize = lastFrameSize = frameSize; break handleFrame; } int framePos = frameNode.type == Opcodes.F_APPEND ? lastFrameSize : 0; lastFrameSize = frameSize; - + // localPos tracks the location in the frame node's locals list, which doesn't leave space for TOP entries for (int localPos = 0; framePos < frame.length; framePos++, localPos++) { // Get the local at the current position in the FrameNode's locals list @@ -239,7 +254,11 @@ public final class Locals { } } else if (localType == null) { if (framePos >= initialFrameSize && framePos >= frameSize && frameSize > 0) { - frame[framePos] = null; + if (framePos < knownFrameSize) { + frame[framePos] = Locals.getLocalVariableAt(classNode, method, insn, framePos); + } else { + frame[framePos] = null; + } } } else if (localType instanceof LabelNode) { // Uninitialised @@ -253,6 +272,7 @@ public final class Locals { boolean isLoad = insn.getOpcode() >= Opcodes.ILOAD && insn.getOpcode() <= Opcodes.SALOAD; if (isLoad) { frame[varNode.var] = Locals.getLocalVariableAt(classNode, method, insn, varNode.var); + knownFrameSize = Math.max(knownFrameSize, varNode.var + Type.getType(frame[varNode.var].desc).getSize()); } else { // Update the LVT for the opcode AFTER this one, since we always want to know // the frame state BEFORE the *current* instruction to match the contract of From b496c02efe69f438f3d42bcb3ced91292ea4d5b3 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 15 Apr 2021 17:35:08 +0100 Subject: [PATCH 28/42] Remap At targets more intelligently, fixes #483 --- .../AnnotatedMixinElementHandlerInjector.java | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index ba36a3a4..435c6385 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -43,7 +43,6 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; -import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -232,7 +231,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (desc == null) { Kind error = this.mixin.isMultiTarget() ? Kind.ERROR : Kind.WARNING; if (target.isSimulated()) { - elem.printMessage(this.ap, Kind.NOTE, elem + " target '" + reference + "' in @Pseudo mixin will not be obfuscated"); + elem.printMessage(this.ap, Kind.OTHER, elem + " target '" + reference + "' in @Pseudo mixin will not be obfuscated"); } else if (target.isImaginary()) { elem.printMessage(this.ap, error, elem + " target requires method signature because enclosing type information for " + target + " is unavailable"); @@ -301,29 +300,36 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", elem.getElement()); } - String reference = elem.getAt().getValue("target"); - if (reference == null) { - return; + ITargetSelector targetSelector = null; + String targetReference = elem.getAt().getValue("target"); + if (targetReference != null) { + targetSelector = TargetSelector.parse(targetReference, elem); + try { + targetSelector.validate(); + } catch (InvalidSelectorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment())); + } } - ITargetSelector selector = TargetSelector.parse(reference, elem); - - try { - selector.validate(); - } catch (InvalidMemberDescriptorException ex) { - this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment())); + String type = InjectionPointData.parseType(elem.getAt().getValue("value", "")); + + ITargetSelector classSelector = null; + String classReference = elem.getAtArg("class"); + if ("NEW".equals(type) && classReference != null) { + classSelector = TargetSelector.parse(classReference, elem); + try { + classSelector.validate(); + } catch (InvalidSelectorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment())); + } } if (elem.shouldRemap()) { - String type = InjectionPointData.parseType(elem.getAt().getValue("value")); if ("NEW".equals(type)) { - String classReference = elem.getAtArg("class"); - ITargetSelector classSelector = TargetSelector.parse(classReference, elem); - - this.remapNewTarget(String.format(format, type + "."), reference, selector, elem); + this.remapNewTarget(String.format(format, type + "."), targetReference, targetSelector, elem); this.remapNewTarget(String.format(format, type + ".args[class]"), classReference, classSelector, elem); } else { - this.remapReference(String.format(format, type + "."), reference, selector, elem); + this.remapReference(String.format(format, type + "."), targetReference, targetSelector, elem); } } } @@ -366,6 +372,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (!(selector instanceof ITargetSelectorRemappable)) { return; } + ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)selector; AnnotationMirror errorElement = elem.getAtErrorElement(this.ap.getCompilerEnvironment()); From 8a5c69134d5c74a0b856ee83dff6ee35745d0fd6 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 15 Apr 2021 18:05:10 +0100 Subject: [PATCH 29/42] Add 'quiet' option to AP to silence informational messages --- .../spongepowered/tools/obfuscation/AnnotatedMixins.java | 8 +++++++- .../spongepowered/tools/obfuscation/SupportedOptions.java | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index d4845674..f9ddfaff 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -138,6 +138,11 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * configured via the build script (eg. when using AP with MCP) */ private Properties properties; + + /** + * No informational messages, I'm hunting wabbits + */ + private boolean beVewyVewyQuiet; /** * Private constructor, get instances using {@link #getMixinsForEnvironment} @@ -145,6 +150,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider private AnnotatedMixins(ProcessingEnvironment processingEnv) { this.env = this.detectEnvironment(processingEnv); this.processingEnv = processingEnv; + this.beVewyVewyQuiet = this.env == CompilerEnvironment.JDT || "true".equalsIgnoreCase(this.getOption(SupportedOptions.QUIET)); MessageRouter.setMessager(processingEnv.getMessager()); @@ -555,7 +561,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider */ @Override public void printMessage(Kind kind, CharSequence msg) { - if (this.env == CompilerEnvironment.JAVAC || kind != Kind.NOTE) { + if (!this.beVewyVewyQuiet || kind != Kind.NOTE) { this.processingEnv.getMessager().printMessage(kind, msg); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java index 7369df7f..dbe88ca2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -47,6 +47,7 @@ public final class SupportedOptions { public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile"; public static final String MAPPING_TYPES = "mappingTypes"; public static final String PLUGIN_VERSION = "pluginVersion"; + public static final String QUIET = "quiet"; private SupportedOptions() {} @@ -65,7 +66,8 @@ public final class SupportedOptions { SupportedOptions.DEFAULT_OBFUSCATION_ENV, SupportedOptions.DEPENDENCY_TARGETS_FILE, SupportedOptions.MAPPING_TYPES, - SupportedOptions.PLUGIN_VERSION + SupportedOptions.PLUGIN_VERSION, + SupportedOptions.QUIET ); options.addAll( ObfuscationServices.getInstance().getSupportedOptions() From 5c9d20fe22a29808d4c18d960970770a05dbc071 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 15 Apr 2021 18:29:06 +0100 Subject: [PATCH 30/42] Detect side using getDist if launch handler name doesn't impl side Closes #473 --- .../MixinPlatformAgentMinecraftForge.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java index 700897d5..37bf650f 100644 --- a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java +++ b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java @@ -24,8 +24,10 @@ */ package org.spongepowered.asm.launch.platform; +import java.lang.reflect.Method; import java.util.Collection; import java.util.Locale; +import java.util.Optional; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.util.Constants; @@ -33,12 +35,18 @@ import org.spongepowered.asm.util.Constants; import cpw.mods.modlauncher.Environment; import cpw.mods.modlauncher.Launcher; import cpw.mods.modlauncher.api.IEnvironment; +import cpw.mods.modlauncher.api.ILaunchHandlerService; /** * Platform agent for minecraft forge under ModLauncher, only detects the side */ public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent { + /** + * getDist method name in launch handler + */ + private static final String GET_DIST_METHOD = "getDist"; + /* (non-Javadoc) * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent * #init() @@ -72,6 +80,22 @@ public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract if (launchTarget.contains("client")) { return Constants.SIDE_CLIENT; } + Optional launchHandler = environment.findLaunchHandler(launchTarget); + if (launchHandler.isPresent()) { + ILaunchHandlerService service = launchHandler.get(); + try { + Method mdGetDist = service.getClass().getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_DIST_METHOD); + String strDist = mdGetDist.invoke(service).toString().toLowerCase(Locale.ROOT); + if (strDist.contains("server")) { + return Constants.SIDE_SERVER; + } + if (strDist.contains("client")) { + return Constants.SIDE_CLIENT; + } + } catch (Exception ex) { + return null; + } + } return null; } From c820b3d2e055585967a8dea6bf15b6cf9c8ad20c Mon Sep 17 00:00:00 2001 From: Patrick Hofmann Date: Sat, 17 Apr 2021 22:36:56 -0500 Subject: [PATCH 31/42] Allows < and > to be written as characters instead of unicode codes --- .../spongepowered/tools/obfuscation/json/MappingWriterJson.java | 2 +- .../org/spongepowered/asm/mixin/refmap/ReferenceMapper.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java b/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java index df4c1594..d2f5713e 100644 --- a/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java +++ b/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java @@ -79,7 +79,7 @@ public class MappingWriterJson extends MappingWriter { try { writer = this.openFileWriter(output, type + " output"); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); + Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); gson.toJson(mappings, writer); } catch (IOException ex) { ex.printStackTrace(); diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java index 03913639..c8161339 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -246,7 +246,7 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { * @param writer Writer to write to */ public void write(Appendable writer) { - new GsonBuilder().setPrettyPrinting().create().toJson(this, writer); + new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(this, writer); } /** From 09b23eae8c9e14b44825fb3032eb6c4104ec3d20 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 17 Apr 2021 13:02:48 +0100 Subject: [PATCH 32/42] Better descriptor validation and trap unexpected desc errors, fixes #461 --- .../mixin/injection/struct/MemberInfo.java | 10 ++++++- .../asm/util/SignaturePrinter.java | 28 +++++++++++++++---- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index 0bd081b5..60909ce0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -667,7 +667,11 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } } else { try { - Type.getArgumentTypes(this.desc); + for (Type argType : Type.getArgumentTypes(this.desc)) { + // getInternalName is a useful litmus test for improperly-formatted types which parse out of + // the descriptor correctly but are actually invalid, for example unterminated class names + argType.getInternalName(); + } } catch (Exception ex) { throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } @@ -675,6 +679,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec String retString = this.desc.substring(this.desc.indexOf(')') + 1); try { Type retType = Type.getType(retString); + int sort = retType.getSort(); + if (sort >= Type.ARRAY) { + retType.getInternalName(); // sanity check + } if (!retString.equals(retType.getDescriptor())) { throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + this.desc); diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index 400a6b86..303a8513 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -238,9 +238,9 @@ public class SignaturePrinter { private StringBuilder appendType(StringBuilder sb, Type type, String name) { switch (type.getSort()) { case Type.ARRAY: - return SignaturePrinter.appendArraySuffix(this.appendType(sb, type.getElementType(), name), type); + return SignaturePrinter.appendArraySuffix(this.appendType(sb, SignaturePrinter.getElementType(type), name), type); case Type.OBJECT: - return this.appendType(sb, type.getClassName(), name); + return this.appendType(sb, SignaturePrinter.getClassName(type), name); default: sb.append(SignaturePrinter.getTypeName(type, false, this.fullyQualified)); if (name != null) { @@ -263,7 +263,7 @@ public class SignaturePrinter { } return sb; } - + /** * Get the source code name for the specified type * @@ -310,9 +310,10 @@ public class SignaturePrinter { case Type.FLOAT: return box ? "Float" : "float"; case Type.LONG: return box ? "Long" : "long"; case Type.DOUBLE: return box ? "Double" : "double"; - case Type.ARRAY: return SignaturePrinter.getTypeName(type.getElementType(), box, fullyQualified) + SignaturePrinter.arraySuffix(type); + case Type.ARRAY: + return SignaturePrinter.getTypeName(SignaturePrinter.getElementType(type), box, fullyQualified) + SignaturePrinter.arraySuffix(type); case Type.OBJECT: - String typeName = type.getClassName(); + String typeName = SignaturePrinter.getClassName(type); if (!fullyQualified) { typeName = typeName.substring(typeName.lastIndexOf('.') + 1); } @@ -322,11 +323,26 @@ public class SignaturePrinter { } } + private static Type getElementType(Type type) { + try { + return type.getElementType(); + } catch (Exception ex) { + return Type.getObjectType("InvalidType"); + } + } + + private static String getClassName(Type type) { + try { + return type.getClassName(); + } catch (Exception ex) { + return "InvalidType"; + } + } + private static String arraySuffix(Type type) { return Strings.repeat("[]", type.getDimensions()); } - private static StringBuilder appendArraySuffix(StringBuilder sb, Type type) { for (int i = 0; i < type.getDimensions(); i++) { sb.append("[]"); From 5f51f16bb5effcd1bf60a66ca8a873ddf8630985 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 20 Apr 2021 19:15:36 +0100 Subject: [PATCH 33/42] Do not strip checkcasts for local 0 in static methods, fixes #471 --- .../asm/mixin/transformer/MixinTargetContext.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 32e0ae02..510b4aad 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -666,7 +666,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { if (typeInsn.getOpcode() == Opcodes.CHECKCAST && typeInsn.desc.equals(this.getTarget().getClassRef()) && lastNode.getOpcode() == Opcodes.ALOAD - && ((VarInsnNode)lastNode).var == 0) { + && ((VarInsnNode)lastNode).var == 0 + && !Bytecode.isStatic(method)) { iter.remove(); return; } From 6e807085d8e809abfe711a9c830de0999e1a250c Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 26 Apr 2021 13:04:21 +0100 Subject: [PATCH 34/42] Fix for the original fix for #480, which actually fixes #480 --- src/main/java/org/spongepowered/asm/util/Locals.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 035a8b80..570125de 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -272,7 +272,8 @@ public final class Locals { boolean isLoad = insn.getOpcode() >= Opcodes.ILOAD && insn.getOpcode() <= Opcodes.SALOAD; if (isLoad) { frame[varNode.var] = Locals.getLocalVariableAt(classNode, method, insn, varNode.var); - knownFrameSize = Math.max(knownFrameSize, varNode.var + Type.getType(frame[varNode.var].desc).getSize()); + int varSize = frame[varNode.var].desc != null ? Type.getType(frame[varNode.var].desc).getSize() : 1; + knownFrameSize = Math.max(knownFrameSize, varNode.var + varSize); } else { // Update the LVT for the opcode AFTER this one, since we always want to know // the frame state BEFORE the *current* instruction to match the contract of From 6994e816224c82fd31e033b1db282c7e0e9cd300 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 27 Apr 2021 13:28:12 +0100 Subject: [PATCH 35/42] Use correct class key for lookup into refmap --- .../org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index 0bcf67a8..4fb3c7fd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -69,7 +69,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { public String remap(String reference) { if (this.context != null) { IReferenceMapper referenceMapper = this.context.getReferenceMapper(); - return referenceMapper != null ? referenceMapper.remap(this.context.getClassName(), reference) : reference; + return referenceMapper != null ? referenceMapper.remap(this.context.getClassRef(), reference) : reference; } return reference; } From 99a51998c0b9270c7e85102cc37854f46dc132ea Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 5 Jun 2021 15:55:17 +0100 Subject: [PATCH 36/42] Avoid cross-contaminating injector-added locals by when capturing locals Fixes #493 Adds a preinject pass to local-capturing injectors so they see only valid locals. Also decorate mixin-added locals to safeguard against accidental leakage. --- .../injection/callback/CallbackInjector.java | 30 ++++++---- .../asm/mixin/injection/code/Injector.java | 54 +++++++++++++++++- .../modify/ModifyVariableInjector.java | 32 +++++++++-- .../mixin/injection/struct/InjectionInfo.java | 9 +++ .../asm/mixin/injection/struct/Target.java | 56 ++++++++++++++----- .../mixin/transformer/MixinTargetContext.java | 9 ++- .../org/spongepowered/asm/util/Bytecode.java | 52 +++++++++++++++++ .../org/spongepowered/asm/util/Locals.java | 15 ++++- 8 files changed, 223 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index ea8802ff..75c864c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -326,6 +326,11 @@ public class CallbackInjector extends Injector { } + /** + * Decorator key for local variables decoration + */ + private static final String LOCALS_KEY = "locals"; + /** * True if cancellable */ @@ -417,6 +422,19 @@ public class CallbackInjector extends Injector { myNodes.add(injectionNode); this.totalInjections++; } + + @Override + protected void preInject(Target target, InjectionNode node) { + if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) { + LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget()); + for (int j = 0; j < locals.length; j++) { + if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) { + locals[j] = null; + } + } + node.decorate(CallbackInjector.LOCALS_KEY, locals); + } + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector @@ -425,17 +443,7 @@ public class CallbackInjector extends Injector { */ @Override protected void inject(Target target, InjectionNode node) { - LocalVariableNode[] locals = null; - - if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) { - locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget()); - for (int j = 0; j < locals.length; j++) { - if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) { - locals[j] = null; - } - } - } - + LocalVariableNode[] locals = node.getDecoration(CallbackInjector.LOCALS_KEY); this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals())); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 9a2b54f3..ecc0162c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -247,6 +247,18 @@ public abstract class Injector { myNodes.add(target.addInjectionNode(node)); } + /** + * Performs pre-injection checks and tasks on the specified target + * + * @param target target potentially being injected into + * @param nodes selected target nodes + */ + public final void preInject(Target target, List nodes) { + for (InjectionNode node : nodes) { + this.preInject(target, node); + } + } + /** * Performs the injection on the specified target * @@ -381,6 +393,10 @@ public abstract class Injector { this.checkTargetModifiers(target, true); } + protected void preInject(Target target, InjectionNode node) { + // stub + } + protected abstract void inject(Target target, InjectionNode node); protected void postInject(Target target, InjectionNode node) { @@ -439,7 +455,7 @@ public abstract class Injector { this.pushArgs(args, insns, argMap, startArg, endArg); return this.invokeHandler(insns); } - + /** * Store args on the stack starting at the end and working back to position * specified by start, return the generated argMap @@ -451,8 +467,24 @@ public abstract class Injector { * @return the generated argmap */ protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) { + return this.storeArgs(target, args, insns, start, null, null); + } + + /** + * Store args on the stack starting at the end and working back to position + * specified by start, return the generated argMap + * + * @param target target method + * @param args argument types + * @param insns instruction list to generate insns into + * @param start Starting index + * @param from The label marking the start of the region for the locals + * @param to The label marking the end of the region for the stored locals + * @return the generated argmap + */ + protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start, LabelNode from, LabelNode to) { int[] argMap = target.generateArgMap(args, start); - this.storeArgs(args, insns, argMap, start, args.length); + this.storeArgs(target, args, insns, argMap, start, args.length, from, to); return argMap; } @@ -465,9 +497,25 @@ public abstract class Injector { * @param start Starting index * @param end Ending index */ - protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { + protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end) { + this.storeArgs(target, args, insns, argMap, start, end, null, null); + } + + /** + * Store args on the stack to their positions allocated based on argMap + * + * @param args argument types + * @param insns instruction list to generate insns into + * @param argMap generated argmap containing local indices for all args + * @param start Starting index + * @param end Ending index + * @param from The label marking the start of the region for the locals + * @param to The label marking the end of the region for the stored locals + */ + protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end, LabelNode from, LabelNode to) { for (int arg = end - 1; arg >= start; arg--) { insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg])); + target.addLocalVariable(argMap[arg], String.format("injectorAllocatedLocal%d", argMap[arg]), args[arg].getDescriptor(), from, to); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 4d02c557..147d9076 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -43,6 +43,7 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.Target.Extension; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.util.Bytecode; @@ -55,7 +56,7 @@ import org.spongepowered.asm.util.SignaturePrinter; * {@link ModifyVariable}. */ public class ModifyVariableInjector extends Injector { - + /** * Target context information */ @@ -93,11 +94,16 @@ public class ModifyVariableInjector extends Injector { } + /** + * Decorator key for Context decoration + */ + private static final String LOCALS_CONTEXT_KEY = "localcontext"; + /** * True to consider only method args */ private final LocalVariableDiscriminator discriminator; - + /** * @param info Injection info * @param discriminator discriminator @@ -136,6 +142,12 @@ public class ModifyVariableInjector extends Injector { } } + @Override + protected void preInject(Target target, InjectionNode node) { + Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget()); + node.decorate(ModifyVariableInjector.LOCALS_CONTEXT_KEY, context); + } + /** * Do the injection */ @@ -145,15 +157,27 @@ public class ModifyVariableInjector extends Injector { throw new InvalidInjectionException(this.info, "Variable modifier target for " + this + " was removed by another injector"); } - Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget()); + Context context = node.getDecoration(ModifyVariableInjector.LOCALS_CONTEXT_KEY); + if (context == null) { + throw new InjectionError(String.format( + "%s injector target is missing CONTEXT decoration for %s. PreInjection failure or illegal internal state change", + this.annotationType, this.info)); + } if (this.discriminator.printLVT()) { this.printLocals(target, context); } - + this.checkTargetForNode(target, node, RestrictTargetLevel.ALLOW_ALL); InjectorData handler = new InjectorData(target, "handler", false); + + if (this.returnType == Type.VOID_TYPE) { + throw new InvalidInjectionException(this.info, String.format( + "%s %s method %s from %s has an invalid signature, cannot return a VOID type.", + this.annotationType, handler, this, this.info.getMixin())); + } + this.validateParams(handler, this.returnType, this.returnType); Extension extraStack = target.extendStack(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 8e233442..bb686fb5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -428,6 +428,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } } + /** + * Perform pre-injection checks and tasks + */ + public void preInject() { + for (Entry> entry : this.targetNodes.entrySet()) { + this.injector.preInject(entry.getKey(), entry.getValue()); + } + } + /** * Perform injections */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java index aa1b27e9..971a8d59 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; @@ -45,6 +44,7 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.Locals.SyntheticLocalVariableNode; /** * Information about the current injection target, mainly just convenience @@ -751,13 +751,7 @@ public class Target implements Comparable, Iterable { * @param desc local variable type */ public void addLocalVariable(int index, String name, String desc) { - if (this.start == null) { - this.start = new LabelNode(new Label()); - this.end = new LabelNode(new Label()); - this.insns.insert(this.start); - this.insns.add(this.end); - } - this.addLocalVariable(index, name, desc, this.start, this.end); + this.addLocalVariable(index, name, desc, null, null); } /** @@ -766,14 +760,50 @@ public class Target implements Comparable, Iterable { * @param index local variable index * @param name local variable name * @param desc local variable type - * @param start start of range - * @param end end of range + * @param from start of range + * @param to end of range */ - private void addLocalVariable(int index, String name, String desc, LabelNode start, LabelNode end) { + public void addLocalVariable(int index, String name, String desc, LabelNode from, LabelNode to) { + if (from == null) { + from = this.getStartLabel(); + } + + if (to == null) { + to = this.getEndLabel(); + } + if (this.method.localVariables == null) { this.method.localVariables = new ArrayList(); } - this.method.localVariables.add(new LocalVariableNode(name, desc, null, start, end, index)); + + for (Iterator iter = this.method.localVariables.iterator(); iter.hasNext();) { + LocalVariableNode local = iter.next(); + if (local != null && local.index == index && from == local.start && to == local.end) { + iter.remove(); + } + } + + this.method.localVariables.add(new SyntheticLocalVariableNode(name, desc, null, from, to, index)); } - + + /** + * Get a label which marks the very start of the method + */ + private LabelNode getStartLabel() { + if (this.start == null) { + this.insns.insert(this.start = new LabelNode()); + } + return this.start; + } + + /** + * Get a label which marks the very end of the method + */ + private LabelNode getEndLabel() { + if (this.end == null) { + this.insns.add(this.end = new LabelNode()); + } + return this.end; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 510b4aad..eb16f91f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -1277,7 +1277,14 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { this.activities.clear(); try { - Activity applyActivity = this.activities.begin("Inject"); + Activity applyActivity = this.activities.begin("PreInject"); + Activity preInjectActivity = this.activities.begin("?"); + for (InjectionInfo injectInfo : this.injectors) { + preInjectActivity.next(injectInfo.toString()); + injectInfo.preInject(); + } + + applyActivity.next("Inject"); Activity injectActivity = this.activities.begin("?"); for (InjectionInfo injectInfo : this.injectors) { injectActivity.next(injectInfo.toString()); diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 1fec392f..2bf45cfb 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -659,6 +659,58 @@ public final class Bytecode { } } +// /** +// * Generate required APPEND frame nodes for the listed types and append them +// * to the supplied instruction list +// * +// * @param insns Insnlist to append to +// * @param types frame types to append +// */ +// public static void extendFrame(InsnList insns, Type[] types) { +// int offset = 0; +// Object[] locals = new Object[3]; +// +// for (int index = 0; index < types.length; index++) { +// +// Type type = types[index]; +// int size = type.getSize(); +// if (offset + size <= 3) { +// if (type.getSort() < Type.ARRAY) { +// locals[offset] = type.getSort(); +// } else { +// locals[offset] = type.getInternalName(); +// } +// if (size > 1) { +// locals[offset + 1] = null; +// } +// offset += size; +// } else { +// insns.add(new FrameNode(Opcodes.F_APPEND, offset, locals, 0, null)); +// offset = 0; +// } +// } +// +// if (offset > 0) { +// insns.add(new FrameNode(Opcodes.F_APPEND, offset, locals, 0, null)); +// } +// } +// +// /** +// * Generate required CHOP frame nodes for the listed types and append them +// * to the supplied insn list +// * +// * @param insns Insnlist to append generated nodes to +// * @param types types to chop +// */ +// public static void chopFrame(InsnList insns, Type[] types) { +// int size = Bytecode.getArgsSize(types); +// while (size > 0) { +// int chop = Math.min(size, 3); +// insns.add(new FrameNode(Opcodes.F_CHOP, chop, null, 0, null)); +// size -= chop; +// } +// } + /** * Get an array of Types from an array of classes. * diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 570125de..116fc122 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -57,6 +57,17 @@ import org.spongepowered.asm.util.throwables.LVTGeneratorError; */ public final class Locals { + /** + * A local variable entry added by mixin itself, eg. by an injector + */ + public static class SyntheticLocalVariableNode extends LocalVariableNode { + + public SyntheticLocalVariableNode(String name, String descriptor, String signature, LabelNode start, LabelNode end, int index) { + super(name, descriptor, signature, start, end, index); + } + + } + /** * Frame type names just for the purposes of debug printing */ @@ -287,9 +298,9 @@ public final class Locals { } } - // Null out any "unknown" locals + // Null out any "unknown" or mixin-provided locals for (int l = 0; l < frame.length; l++) { - if (frame[l] != null && frame[l].desc == null) { + if (frame[l] != null && frame[l].desc == null || frame[l] instanceof SyntheticLocalVariableNode) { frame[l] = null; } } From b947316d4612e3b9f702f1809d940ead3854c000 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 5 Jun 2021 16:08:19 +0100 Subject: [PATCH 37/42] Correctly match NULL in BeforeConstant --- .../asm/mixin/injection/points/BeforeConstant.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index e93769b2..1036cdc5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -280,7 +280,7 @@ public class BeforeConstant extends InjectionPoint { } Object value = Bytecode.getConstant(insn); - if (value == null) { + if (value == Type.VOID_TYPE) { this.log(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue); return this.nullValue || Constants.OBJECT_DESC.equals(this.matchByType); } else if (value instanceof Integer) { From dd1f1ceff68a44098881ac0ae39836e2e88ef831 Mon Sep 17 00:00:00 2001 From: SizableShrimp Date: Wed, 16 Jun 2021 18:45:08 -0500 Subject: [PATCH 38/42] Fix TSRGv2 parsing --- .../tools/obfuscation/mapping/fg3/MappingProviderTSrg.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java index 3d35f99e..2ebd14a2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java @@ -65,7 +65,7 @@ public class MappingProviderTSrg extends MappingProvider { this.inputMappings.addAll(Files.readLines(input, Charset.defaultCharset())); for (String line : this.inputMappings) { - if (Strings.isNullOrEmpty(line) || line.startsWith("#")) { + if (Strings.isNullOrEmpty(line) || line.startsWith("#") || line.startsWith("tsrg2") || line.startsWith("\t\t")) { continue; } From 4517718cc67d77a9f8b5270c61dceec5f0942681 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 22 Jun 2021 23:50:49 +0100 Subject: [PATCH 39/42] Smarter handling of required compatibility level via heuristic, fix #496 --- .../spongepowered/tools/agent/MixinAgent.java | 3 +- .../tools/agent/MixinAgentClassLoader.java | 2 +- .../mojang/MixinServiceLaunchWrapper.java | 17 +- .../asm/mixin/MixinEnvironment.java | 105 ++++++----- .../asm/mixin/injection/InjectionPoint.java | 1 + .../asm/mixin/transformer/ClassInfo.java | 4 +- .../transformer/MixinApplicatorStandard.java | 27 +++ .../asm/mixin/transformer/MixinInfo.java | 31 +-- .../mixin/transformer/MixinPostProcessor.java | 4 +- .../MixinPreProcessorInterface.java | 21 ++- .../mixin/transformer/MixinTargetContext.java | 58 +++++- .../mixin/transformer/MixinTransformer.java | 4 +- .../asm/transformers/MixinClassReader.java | 51 +++++ .../asm/transformers/TreeTransformer.java | 8 +- .../org/spongepowered/asm/util/Bytecode.java | 20 +- .../asm/util/LanguageFeatures.java | 176 ++++++++++++++++++ .../org/spongepowered/asm/util/asm/ASM.java | 83 +++++++-- .../asm/util/asm/ClassNodeAdapter.java | 139 ++++++++++++++ .../asm/launch/MixinLaunchPlugin.java | 3 +- 19 files changed, 651 insertions(+), 106 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java create mode 100644 src/main/java/org/spongepowered/asm/util/LanguageFeatures.java create mode 100644 src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 367d02e3..e06e39f2 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -41,6 +41,7 @@ import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.transformers.MixinClassReader; import org.spongepowered.asm.util.asm.ASM; /** @@ -65,7 +66,7 @@ public class MixinAgent implements IHotSwap { byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined); if (mixinBytecode != null) { ClassNode classNode = new ClassNode(ASM.API_VERSION); - ClassReader cr = new ClassReader(classfileBuffer); + ClassReader cr = new MixinClassReader(classfileBuffer, className); cr.accept(classNode, ClassReader.EXPAND_FRAMES); List targets = this.reloadMixin(className, classNode); diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java index d93d575a..2fd768cb 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -128,7 +128,7 @@ class MixinAgentClassLoader extends ClassLoader { */ private byte[] materialise(String name) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - cw.visit(MixinEnvironment.getCompatibilityLevel().classVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, + cw.visit(MixinEnvironment.getCompatibilityLevel().getClassVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), null); // create init method diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java index 2ef4c898..40035886 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -38,14 +38,14 @@ import java.util.List; import java.util.Locale; import java.util.Set; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.launch.GlobalProperties; import org.spongepowered.asm.launch.GlobalProperties.Keys; import org.spongepowered.asm.launch.platform.MainAttributes; -import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.launch.platform.container.ContainerHandleURI; import org.spongepowered.asm.launch.platform.container.ContainerHandleVirtual; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; @@ -58,15 +58,16 @@ import org.spongepowered.asm.service.IMixinAuditTrail; import org.spongepowered.asm.service.ITransformer; import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinServiceAbstract; +import org.spongepowered.asm.transformers.MixinClassReader; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; -import com.google.common.collect.ImmutableList.Builder; import net.minecraft.launchwrapper.IClassNameTransformer; import net.minecraft.launchwrapper.IClassTransformer; @@ -576,7 +577,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I */ @Override public ClassNode getClassNode(String className) throws ClassNotFoundException, IOException { - return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); + return this.getClassNode(className, this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); } /* (non-Javadoc) @@ -585,7 +586,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I */ @Override public ClassNode getClassNode(String className, boolean runTransformers) throws ClassNotFoundException, IOException { - return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); + return this.getClassNode(className, this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); } /** @@ -595,9 +596,9 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I * @param flags ClassReader flags * @return ASM Tree view of the specified class */ - private ClassNode getClassNode(byte[] classBytes, int flags) { + private ClassNode getClassNode(String className, byte[] classBytes, int flags) { ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(classBytes); + ClassReader classReader = new MixinClassReader(classBytes, className); classReader.accept(classNode, flags); return classNode; } diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 9a409533..74744307 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -55,6 +55,7 @@ import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.IConsumer; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.asm.util.JavaVersion; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.asm.ASM; import org.spongepowered.asm.util.perf.Profiler; @@ -590,12 +591,12 @@ public final class MixinEnvironment implements ITokenProvider { public static enum CompatibilityLevel { /** - * Java 6 and above + * Java 6 (1.6) or above is required */ JAVA_6(6, Opcodes.V1_6, 0), /** - * Java 7 and above + * Java 7 (1.7) or above is required */ JAVA_7(7, Opcodes.V1_7, 0) { @@ -607,9 +608,9 @@ public final class MixinEnvironment implements ITokenProvider { }, /** - * Java 8 and above + * Java 8 (1.8) or above is required */ - JAVA_8(8, Opcodes.V1_8, LanguageFeature.METHODS_IN_INTERFACES) { + JAVA_8(8, Opcodes.V1_8, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES) { @Override boolean isSupported() { @@ -619,9 +620,10 @@ public final class MixinEnvironment implements ITokenProvider { }, /** - * Java 9 and above + * Java 9 or above is required */ - JAVA_9(9, Opcodes.V9, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) { + JAVA_9(9, Opcodes.V9, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES + | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) { @Override boolean isSupported() { @@ -631,9 +633,10 @@ public final class MixinEnvironment implements ITokenProvider { }, /** - * Java 10 and above + * Java 10 or above is required */ - JAVA_10(10, Opcodes.V10, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) { + JAVA_10(10, Opcodes.V10, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES + | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) { @Override boolean isSupported() { @@ -643,10 +646,10 @@ public final class MixinEnvironment implements ITokenProvider { }, /** - * Java 10 and above + * Java 11 or above is required */ - JAVA_11(11, Opcodes.V11, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES - | LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) { + JAVA_11(11, Opcodes.V11, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES + | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) { @Override boolean isSupported() { @@ -655,33 +658,6 @@ public final class MixinEnvironment implements ITokenProvider { }; - /** - * Bitmask values for language features supported - */ - public static class LanguageFeature { - - /** - * Language version supports methods in interfaces - */ - public static final int METHODS_IN_INTERFACES = 1; - - /** - * Language version supports private methods in interfaces - */ - public static final int PRIVATE_METHODS_IN_INTERFACES = 2; - - /** - * Native nesting - */ - public static final int NESTING = 4; - - /** - * Dynamic constants - */ - public static final int DYNAMIC_CONSTANTS = 8; - - } - /** * Default compatibility level to use if not specified by the service */ @@ -695,9 +671,9 @@ public final class MixinEnvironment implements ITokenProvider { private CompatibilityLevel maxCompatibleLevel; - private CompatibilityLevel(int ver, int classVersion, int languageFeatures) { + private CompatibilityLevel(int ver, int classMajorVersion, int languageFeatures) { this.ver = ver; - this.classVersion = classVersion; + this.classVersion = classMajorVersion & 0xFF; this.languageFeatures = languageFeatures; } @@ -711,11 +687,28 @@ public final class MixinEnvironment implements ITokenProvider { /** * Class version expected at this compatibility level + * + * @deprecated Use getClassVersion */ + @Deprecated public int classVersion() { return this.classVersion; } + /** + * Class version expected at this compatibility level + */ + public int getClassVersion() { + return this.classVersion; + } + + /** + * Get all supported language features + */ + public int getLanguageFeatures() { + return this.languageFeatures; + } + /** * Get whether this environment supports non-abstract methods in * interfaces, true in Java 1.8 and above @@ -724,18 +717,18 @@ public final class MixinEnvironment implements ITokenProvider { */ @Deprecated public boolean supportsMethodsInInterfaces() { - return (this.languageFeatures & LanguageFeature.METHODS_IN_INTERFACES) != 0; + return (this.languageFeatures & LanguageFeatures.METHODS_IN_INTERFACES) != 0; } /** - * Get whether the specified {@link LanguageFeature} is supported by + * Get whether the specified {@link LanguageFeatures} is supported by * this runtime. * - * @param languageFeature language feature (or features) to check + * @param languageFeatures language feature (or features) to check * @return true if all specified language features are supported */ - public boolean supports(int languageFeature) { - return (this.languageFeatures & languageFeature) != 0; + public boolean supports(int languageFeatures) { + return (this.languageFeatures & languageFeatures) == languageFeatures; } /** @@ -785,6 +778,25 @@ public final class MixinEnvironment implements ITokenProvider { return level.canElevateTo(this); } + + /** + * Return the minimum language level required to support the specified + * language feature(s). Returns null if no compatibility level + * available can support the requested language features. + * + * @param languageFeatures Language feature(s) to check for + * @return Lowest compatibility level which supports the requested + * language feature, or null if no levels support the requested + * feature + */ + public static CompatibilityLevel requiredFor(int languageFeatures) { + for (CompatibilityLevel level : CompatibilityLevel.values()) { + if (level.supports(languageFeatures)) { + return level; + } + } + return null; + } static String getSupportedVersions() { StringBuilder sb = new StringBuilder(); @@ -981,7 +993,8 @@ public final class MixinEnvironment implements ITokenProvider { printer.kv("Internal Version", version); printer.kv("Java Versions Supported", CompatibilityLevel.getSupportedVersions()); printer.kv("Current Compatibility Level", MixinEnvironment.getCompatibilityLevel()); - printer.kv("Detected ASM API Version", ASM.getApiVersionString()).hr(); + printer.kv("Detected ASM API Version", ASM.getApiVersionString()); + printer.kv("Detected ASM Supports Java", ASM.getClassVersionString()).hr(); printer.kv("Service Name", serviceName); printer.kv("Mixin Service Class", this.service.getClass().getName()); printer.kv("Global Property Service Class", MixinService.getGlobalPropertyService().getClass().getName()).hr(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index e5fff052..0d77875d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -868,6 +868,7 @@ public abstract class InjectionPoint { */ @Deprecated public static void register(Class type) { + InjectionPoint.register(type, null); } /** 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 e72486ca..350526ac 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -49,7 +49,6 @@ import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; @@ -58,6 +57,7 @@ import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.ClassSignature; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; @@ -1690,7 +1690,7 @@ public final class ClassInfo { } } - if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES))) { + if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES))) { for (String implemented : this.interfaces) { ClassInfo iface = ClassInfo.forName(implemented); if (iface == null) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index c94ca2ce..4bb7b5ed 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -64,6 +64,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.ConstraintParser; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.ConstraintParser.Constraint; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; @@ -381,6 +382,8 @@ class MixinApplicatorStandard { this.applyMethods(mixin); activity.next("Apply Initialisers"); this.applyInitialisers(mixin); + activity.next("Apply Nesting"); + this.applyNesting(mixin); break; case PREINJECT: @@ -1023,6 +1026,30 @@ class MixinApplicatorStandard { private static String fieldKey(FieldInsnNode fieldNode) { return String.format("%s:%s", fieldNode.desc, fieldNode.name); } + + /** + * Apply nesting attributes from the mixin to the target. + * + *

NOT YET SUPPORTED!

+ */ + protected void applyNesting(MixinTargetContext mixin) { + + String nestHostClass = mixin.getNestHostClass(); + List nestMembers = mixin.getNestMembers(); + if ((nestHostClass == null && nestMembers == null) || (nestMembers != null && nestMembers.size() == 0)) { + return; + } + + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) { + // Shouldn't get here because we should error out during the initial scan, but you never know + throw new InvalidMixinException(mixin, + String.format("%s contains nesting information but the current compatibility level does not support class nesting attributes", + mixin)); + } + + // TODO Nesting not done yet, just log an error for now that we're not applying these attributes + this.logger.error("NESTING not supported in this version of Mixin. {} nesting attributes will not be applied to the target", mixin); + } /** * Scan for injector methods and injection points 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 7dec6d02..f5e7dcaa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -51,7 +51,6 @@ import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.Overwrite; @@ -70,6 +69,7 @@ import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.asm.ASM; import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.perf.Profiler; @@ -317,6 +317,7 @@ class MixinInfo implements Comparable, IMixinInfo { */ void validate(SubType type, List targetClasses) { MixinClassNode classNode = this.getValidationClassNode(); + MixinPreProcessorStandard preProcessor = type.createPreProcessor(classNode).prepare(); for (ClassInfo target : targetClasses) { preProcessor.conform(target); @@ -329,7 +330,7 @@ class MixinInfo implements Comparable, IMixinInfo { // Pre-flight checks this.validateInner(); - this.validateClassVersion(); + this.validateClassFeatures(); this.validateRemappables(targetClasses); // Read information from the mixin @@ -350,17 +351,19 @@ class MixinInfo implements Comparable, IMixinInfo { } } - private void validateClassVersion() { - if (this.validationClassNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) { - String helpText = "."; - for (CompatibilityLevel level : CompatibilityLevel.values()) { - if (level.classVersion() >= this.validationClassNode.version) { - helpText = String.format(". Mixin requires compatibility level %s or above.", level.name()); - } - } - - throw new InvalidMixinException(MixinInfo.this, "Unsupported mixin class version " + this.validationClassNode.version + helpText); + private void validateClassFeatures() { + CompatibilityLevel compatibilityLevel = MixinEnvironment.getCompatibilityLevel(); + int requiredLanguageFeatures = LanguageFeatures.scan(this.validationClassNode); + if (requiredLanguageFeatures == 0 || compatibilityLevel.supports(requiredLanguageFeatures)) { + return; } + + int missingFeatures = requiredLanguageFeatures & ~compatibilityLevel.getLanguageFeatures(); + CompatibilityLevel minRequiredLevel = CompatibilityLevel.requiredFor(requiredLanguageFeatures); + + throw new InvalidMixinException(MixinInfo.this, String.format( + "Unsupported mixin, %s requires the following unsupported language features: %s, these features require compatibility level %s", + MixinInfo.this, LanguageFeatures.format(missingFeatures), minRequiredLevel != null ? minRequiredLevel.toString() : "UNKNOWN")); } private void validateRemappables(List targetClasses) { @@ -610,7 +613,7 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validate(State state, List targetClasses) { - if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Interface mixin not supported in current enviromnment"); } @@ -654,7 +657,7 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validateTarget(String targetName, ClassInfo targetInfo) { boolean targetIsInterface = targetInfo.isInterface(); - if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Accessor mixin targetting an interface is not supported in current enviromnment"); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index e3b30fd0..311e4c27 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -38,7 +38,6 @@ import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; @@ -49,6 +48,7 @@ import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.Visibility; +import org.spongepowered.asm.util.LanguageFeatures; /** * Performs post-processing tasks required for certain classes which pass @@ -163,7 +163,7 @@ class MixinPostProcessor implements MixinConfig.IListener { } private boolean processAccessor(ClassNode classNode, MixinInfo mixin) { - if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { return false; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java index 2f54a5d8..1638355c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java @@ -27,11 +27,14 @@ package org.spongepowered.asm.mixin.transformer; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.FieldNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.LanguageFeatures; /** * Bytecode preprocessor for interface mixins, simply performs some additional @@ -57,9 +60,17 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { @Override protected void prepareMethod(MixinMethodNode mixinMethod, Method method) { // Userland interfaces should not have non-public methods except for lambda bodies - if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC) && !Bytecode.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)) { - throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains a non-public method! Found " + method + " in " - + this.mixin); + if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC)) { + if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)) { + throw new InvalidInterfaceMixinException(this.mixin, String.format("Interface mixin contains a non-public method! Found %s in %s", + method, this.mixin)); + } + CompatibilityLevel requiredLevel = CompatibilityLevel.requiredFor(LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES); + if (MixinEnvironment.getCompatibilityLevel().isLessThan(requiredLevel)) { + throw new InvalidInterfaceMixinException(this.mixin, String.format( + "Interface mixin contains a synthetic private method but compatibility level %s is required! Found %s in %s", + requiredLevel, method, this.mixin)); + } } super.prepareMethod(mixinMethod, method); @@ -75,8 +86,8 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { @Override protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { if (!Bytecode.isStatic(field)) { - throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains an instance field! Found " + field.name + " in " - + this.mixin); + throw new InvalidInterfaceMixinException(this.mixin, String.format("Interface mixin contains an instance field! Found %s in %s", + field.name, this.mixin)); } return super.validateField(context, field, shadow); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index eb16f91f..ac9c05b2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -39,6 +39,7 @@ import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.objectweb.asm.ConstantDynamic; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -76,6 +77,9 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.Visibility; import org.spongepowered.asm.util.ClassSignature; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.LanguageFeatures; +import org.spongepowered.asm.util.asm.ASM; +import org.spongepowered.asm.util.asm.ClassNodeAdapter; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -179,7 +183,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * Minimum class version required to apply this mixin, target class will be * upgraded if the version is below this value */ - private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion(); + private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.getClassVersion(); /** * ctor @@ -730,6 +734,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return constant; } else if (constant instanceof Handle) { return this.transformHandle(method, iter, (Handle)constant); + } else if (ASM.isAtLeastVersion(6) && constant instanceof ConstantDynamic) { + return this.transformDynamicConstant(method, iter, (ConstantDynamic)constant); } return constant; } @@ -752,6 +758,36 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return memberRef.getMethodHandle(); } + /** + * Transforms a dynamic constant, this is currently a blind implementation + * since I haven't seen this bytecode in the wild. + * TODO Find out if this even works + * + * @param method Method being processed + * @param iter Insn iterator + * @param constant Dynamic constant to transform + * @return Transformed dynamic constant + */ + private ConstantDynamic transformDynamicConstant(MethodNode method, Iterator iter, ConstantDynamic constant) { + this.requireVersion(Opcodes.V11); + + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.DYNAMIC_CONSTANTS)) { + // Shouldn't get here because we should error out during the initial scan, but you never know + throw new InvalidMixinException(this, String.format( + "%s%s in %s contains a dynamic constant, which is not supported by the current compatibility level", + method.name, method.desc, this)); + } + + String desc = this.transformSingleDescriptor(constant.getDescriptor(), false); + Handle bsm = this.transformHandle(method, iter, constant.getBootstrapMethod()); + Object[] bsmArgs = new Object[constant.getBootstrapMethodArgumentCount()]; + for (int i = 0; i < bsmArgs.length; i++) { + bsmArgs[i] = this.transformConstant(method, iter, constant.getBootstrapMethodArgument(i)); + } + + return new ConstantDynamic(constant.getName(), desc, bsm, bsmArgs); + } + /** * Handle "imaginary super" invocations, these are invocations in * non-derived mixins for accessing methods known to exist in a supermixin @@ -1038,9 +1074,9 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version); // This validation is done on the mixin beforehand, however it's still - // possible that an upstream transformer can inject java 7 instructions - // without updating the class version. - if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) { + // possible that an upstream transformer can inject unsupported + // instructions without updating the class version. + if ((version & 0xFFFF) > ASM.getMaxSupportedClassVersionMajor()) { throw new InvalidMixinException(this, "Unsupported mixin class version " + version); } } @@ -1157,6 +1193,20 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { String getSourceFile() { return this.classNode.sourceFile; } + + /** + * Get the nest host class from the mixin + */ + String getNestHostClass() { + return ClassNodeAdapter.getNestHostClass(this.classNode); + } + + /** + * Get the nest members from the mixin + */ + List getNestMembers() { + return ClassNodeAdapter.getNestMembers(this.classNode); + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext 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 183248c5..f65908ea 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -223,7 +223,7 @@ final class MixinTransformer extends TreeTransformer implements IMixinTransforme */ @Override public byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes) { - ClassNode classNode = this.readClass(classBytes); + ClassNode classNode = this.readClass(name, classBytes); if (this.processor.applyMixins(environment, name, classNode)) { return this.writeClass(classNode); } @@ -276,7 +276,7 @@ final class MixinTransformer extends TreeTransformer implements IMixinTransforme private static ClassNode createEmptyClass(String name) { ClassNode classNode = new ClassNode(ASM.API_VERSION); classNode.name = name.replace('.', '/'); - classNode.version = MixinEnvironment.getCompatibilityLevel().classVersion(); + classNode.version = MixinEnvironment.getCompatibilityLevel().getClassVersion(); classNode.superName = Constants.OBJECT; return classNode; } diff --git a/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java b/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java new file mode 100644 index 00000000..bee1d5ee --- /dev/null +++ b/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.transformers; + +import org.objectweb.asm.ClassReader; +import org.spongepowered.asm.util.asm.ASM; + +/** + * A ClassReader which returns a more verbose exception message when the + * incoming class major version is higher than the version supported by the + * active ASM. + */ +public class MixinClassReader extends ClassReader { + + public MixinClassReader(final byte[] classFile, final String name) { + super(MixinClassReader.checkClassVersion(classFile, name)); + } + + private static byte[] checkClassVersion(final byte[] classFile, final String name) { + short majorClassVersion = (short)(((classFile[6] & 0xFF) << 8) | (classFile[7] & 0xFF)); + if (majorClassVersion > ASM.getMaxSupportedClassVersionMajor()) { + throw new IllegalArgumentException(String.format( + "Class file major version %d is not supported by active ASM (version %d.%d supports class version %d), reading %s", + majorClassVersion, ASM.getApiVersionMajor(), ASM.getApiVersionMinor(), ASM.getMaxSupportedClassVersionMajor(), name)); + } + return classFile; + } + +} diff --git a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java index 8e07d2e9..c2078b8b 100644 --- a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java +++ b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java @@ -41,8 +41,8 @@ public abstract class TreeTransformer implements ILegacyClassTransformer { * @param basicClass Original bytecode * @return tree */ - protected final ClassNode readClass(byte[] basicClass) { - return this.readClass(basicClass, true); + protected final ClassNode readClass(String className, byte[] basicClass) { + return this.readClass(className, basicClass, true); } /** @@ -51,8 +51,8 @@ public abstract class TreeTransformer implements ILegacyClassTransformer { * writing the generated ClassNode later * @return tree */ - protected final ClassNode readClass(byte[] basicClass, boolean cacheReader) { - ClassReader classReader = new ClassReader(basicClass); + protected final ClassNode readClass(String className, byte[] basicClass, boolean cacheReader) { + ClassReader classReader = new MixinClassReader(basicClass, className); if (cacheReader) { this.classReader = classReader; } diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 2bf45cfb..e199fd33 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -103,6 +103,17 @@ public final class Bytecode { return other == null || other.ordinal() <= this.ordinal(); } + /** + * Get whether this visibility level represents a level which less than + * the supplied level + * + * @param other level to compare to + * @return true if greater or equal + */ + public boolean isLessThan(Visibility other) { + return other != null && this.ordinal() < other.ordinal(); + } + } /** @@ -1301,9 +1312,12 @@ public final class Bytecode { } // TODO Java 10 -// dest.nestHostClassExperimental = source.nestHostClassExperimental; -// Bytecode.clear(dest.nestMembersExperimental); -// dest.nestMembersExperimental = Bytecode.merge(source.nestMembersExperimental, dest.nestMembersExperimental); +// if (MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) { +// ClassNodeAdapter.setNestHostClass(dest, ClassNodeAdapter.getNestHostClass(source)); +// Bytecode.clear(ClassNodeAdapter.getNestMembers(dest)); +// ClassNodeAdapter.setNestMembers(dest, Bytecode.merge(ClassNodeAdapter.getNestMembers(source), +// ClassNodeAdapter.getNestMembers(dest))); +// } Bytecode.merge(source, dest); diff --git a/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java b/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java new file mode 100644 index 00000000..ca39785c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java @@ -0,0 +1,176 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.lang.reflect.Field; +import java.util.List; +import java.util.ListIterator; + +import org.objectweb.asm.ConstantDynamic; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.util.Bytecode.Visibility; +import org.spongepowered.asm.util.asm.ASM; +import org.spongepowered.asm.util.asm.ClassNodeAdapter; + +/** + * Bitmask values for language features supported. Contains utility methods for + * detecting language features in use in supplied class nodes. + */ +public final class LanguageFeatures { + + /** + * Language version supports methods in interfaces + */ + public static final int METHODS_IN_INTERFACES = 1; + + /** + * Language version supports synthetic private methods in interfaces + */ + public static final int PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES = 2; + + /** + * Language version supports user-defined private methods in interfaces + */ + public static final int PRIVATE_METHODS_IN_INTERFACES = 4; + + /** + * Native nesting + */ + public static final int NESTING = 8; + + /** + * Dynamic constants + */ + public static final int DYNAMIC_CONSTANTS = 16; + + /** + * Utility class + */ + private LanguageFeatures() { + } + + /** + * Scan the supplied class node to determine required language features via + * heuristic. + * + * @param classNode ClassNode to scan (must include method bodies for + * reliable detection) + * @return detected language features + */ + public static int scan(ClassNode classNode) { + int features = LanguageFeatures.scanClassFeatures(classNode); + + boolean isInterface = Bytecode.hasFlag(classNode, Opcodes.ACC_INTERFACE); + for (MethodNode methodNode : classNode.methods) { + if (isInterface) { + features |= LanguageFeatures.scanInterfaceFeatures(methodNode); + } else { + features |= LanguageFeatures.scanMethodFeatures(methodNode); + } + } + + return features; + } + + /** + * Sacn for features at the class level + */ + private static int scanClassFeatures(ClassNode classNode) { + int features = 0; + + String nestHostClass = ClassNodeAdapter.getNestHostClass(classNode); + List nestMembers = ClassNodeAdapter.getNestMembers(classNode); + if (nestHostClass != null || (nestMembers != null && nestMembers.size() > 0)) { + features |= LanguageFeatures.NESTING; + } + + return features; + } + + /** + * Scan the method for interface-specific features + */ + private static int scanInterfaceFeatures(MethodNode methodNode) { + int features = 0; + + if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_ABSTRACT)) { + features |= LanguageFeatures.METHODS_IN_INTERFACES; + } + + if (Bytecode.getVisibility(methodNode).isLessThan(Visibility.PUBLIC)) { + features |= Bytecode.hasFlag(methodNode, Opcodes.ACC_SYNTHETIC) + ? LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES + : LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES; + } + + return features; + } + + /** + * Scan the method code for feature requirements + */ + private static int scanMethodFeatures(MethodNode methodNode) { + // ConstantDynamic only exists in ASM 6 and later + if (ASM.isAtLeastVersion(6)) { + for (ListIterator iter = methodNode.instructions.iterator(); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof LdcInsnNode && ((LdcInsnNode)insn).cst instanceof ConstantDynamic) { + return LanguageFeatures.DYNAMIC_CONSTANTS; + } + } + } + return 0; + } + + /** + * Format the supplied feature mask as a plain-text list for use in error + * messages etc. + * + * @param features Language features to format + * @return Formatted list of features + */ + public static final String format(int features) { + StringBuilder sb = new StringBuilder("["); + try { + int count = 0; + for (Field field : LanguageFeatures.class.getDeclaredFields()) { + if ((features & field.getInt(null)) != 0) { + if (count++ > 0) { + sb.append(','); + } + sb.append(field.getName()); + } + } + } catch (ReflectiveOperationException ex) { + sb.append("ERROR"); + } + return sb.append(']').toString(); + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/ASM.java b/src/main/java/org/spongepowered/asm/util/asm/ASM.java index 5174aaa5..87d38f6d 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/ASM.java +++ b/src/main/java/org/spongepowered/asm/util/asm/ASM.java @@ -38,6 +38,11 @@ public final class ASM { private static int minorVersion = 0; private static String maxVersion = "FALLBACK"; + private static int maxClassVersion = Opcodes.V1_6; + private static int maxClassMajorVersion = Opcodes.V1_6 & 0xFFFF; + private static int maxClassMinorVersion = (Opcodes.V1_6 >> 16) & 0xFFFF; + private static String maxJavaVersion = "V1.6"; + /** * The detected ASM API Version */ @@ -46,6 +51,15 @@ public final class ASM { private ASM() { } + /** + * Get whether the current ASM API is at least the specified version + * + * @param majorVersion version to check for (eg. 6) + */ + public static boolean isAtLeastVersion(int majorVersion) { + return ASM.majorVersion >= majorVersion; + } + /** * Get the major API version */ @@ -69,29 +83,72 @@ public final class ASM { return String.format("ASM %d.%d (%s)", ASM.majorVersion, ASM.minorVersion, ASM.maxVersion); } + /** + * Get the maximum supported class version (raw) + */ + public static int getMaxSupportedClassVersion() { + return ASM.maxClassVersion; + } + + /** + * Get the maximum supported major class versior + */ + public static int getMaxSupportedClassVersionMajor() { + return ASM.maxClassMajorVersion; + } + + /** + * Get the maximum supported minor class versior + */ + public static int getMaxSupportedClassVersionMinor() { + return ASM.maxClassMinorVersion; + } + + /** + * Get the supported java version as a string (mostly for the banner) + * + * @return Java class supported version as string + */ + public static String getClassVersionString() { + return String.format("Up to Java %s (class file version %d.%d)", ASM.maxJavaVersion, ASM.maxClassMajorVersion, ASM.maxClassMinorVersion); + } + private static int detectVersion() { int apiVersion = Opcodes.ASM4; for (Field field : Opcodes.class.getDeclaredFields()) { - if (field.getType() != Integer.TYPE || !field.getName().startsWith("ASM")) { + if (field.getType() != Integer.TYPE) { continue; } try { + String name = field.getName(); int version = field.getInt(null); - - // int patch = version & 0xFF; - int minor = (version >> 8) & 0xFF; - int major = (version >> 16) & 0xFF; - boolean experimental = ((version >> 24) & 0xFF) != 0; - - if (major >= ASM.majorVersion) { - ASM.maxVersion = field.getName(); - if (!experimental) { - apiVersion = version; - ASM.majorVersion = major; - ASM.minorVersion = minor; + if (name.startsWith("ASM")) { + // int patch = version & 0xFF; + int minor = (version >> 8) & 0xFF; + int major = (version >> 16) & 0xFF; + boolean experimental = ((version >> 24) & 0xFF) != 0; + + if (major >= ASM.majorVersion) { + ASM.maxVersion = name; + if (!experimental) { + apiVersion = version; + ASM.majorVersion = major; + ASM.minorVersion = minor; + } } + } else if (name.matches("V([0-9_]+)")) { + int minor = (version >> 16) & 0xFFFF; + int major = (version) & 0xFFFF; + if (major > ASM.maxClassMajorVersion || (major == ASM.maxClassMajorVersion && minor > ASM.maxClassMinorVersion)) { + ASM.maxClassMajorVersion = major; + ASM.maxClassMinorVersion = minor; + ASM.maxClassVersion = version; + ASM.maxJavaVersion = name.replace('_', '.').substring(1); + } + } else if ("ACC_PUBLIC".equals(name)) { + break; } } catch (ReflectiveOperationException ex) { throw new Error(ex); diff --git a/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java b/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java new file mode 100644 index 00000000..6f99bf48 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java @@ -0,0 +1,139 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.asm; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import org.objectweb.asm.tree.ClassNode; + +/** + * Adapter for ClassNode to access members added after ASM 5 + */ +public final class ClassNodeAdapter { + + private static final String NEST_HOST_FIELD = "nestHostClass"; + private static final String NEST_MEMBERS_FIELD = "nestMembers"; + private static final String EXPERIMENTAL_SUFFIX = "Experimental"; + + private static final Field fdNestHost = ClassNodeAdapter.getField(ClassNodeAdapter.NEST_HOST_FIELD); + private static final Field fdNestMembers = ClassNodeAdapter.getField(ClassNodeAdapter.NEST_MEMBERS_FIELD); + + private static boolean notSupported = false; + + private ClassNodeAdapter() { + } + + public static String getNestHostClass(ClassNode classNode) { + if (ASM.isAtLeastVersion(7)) { + return classNode.nestHostClass; + } + + if (ClassNodeAdapter.fdNestHost == null || ClassNodeAdapter.notSupported) { + return null; + } + + try { + return (String)ClassNodeAdapter.fdNestHost.get(classNode); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + return null; + } + } + + public static void setNestHostClass(ClassNode classNode, String nestHostClass) { + if (ASM.isAtLeastVersion(7)) { + classNode.nestHostClass = nestHostClass; + } + + if (ClassNodeAdapter.fdNestHost == null || ClassNodeAdapter.notSupported) { + return; + } + + try { + ClassNodeAdapter.fdNestHost.set(classNode, nestHostClass); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + } + } + + @SuppressWarnings("unchecked") + public static List getNestMembers(ClassNode classNode) { + if (ASM.isAtLeastVersion(7)) { + return classNode.nestMembers; + } + + if (ClassNodeAdapter.fdNestMembers == null || ClassNodeAdapter.notSupported) { + return null; + } + + try { + return (List)ClassNodeAdapter.fdNestMembers.get(classNode); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + return null; + } + } + + public static List getNestMembersAsList(ClassNode classNode) { + List nestMembers = ClassNodeAdapter.getNestMembers(classNode); + if (nestMembers == null) { + nestMembers = new ArrayList(); + ClassNodeAdapter.setNestMembers(classNode, nestMembers); + } + return nestMembers; + } + + public static void setNestMembers(ClassNode classNode, List nestMembers) { + if (ASM.isAtLeastVersion(7)) { + classNode.nestMembers = nestMembers; + } + + if (ClassNodeAdapter.fdNestMembers == null || ClassNodeAdapter.notSupported) { + return; + } + + try { + ClassNodeAdapter.fdNestMembers.set(classNode, nestMembers); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + } + } + + private static Field getField(String fieldBaseName) { + try { + return ClassNode.class.getDeclaredField(fieldBaseName); + } catch (NoSuchFieldException ex) { + try { + return ClassNode.class.getDeclaredField(fieldBaseName + ClassNodeAdapter.EXPERIMENTAL_SUFFIX); + } catch (NoSuchFieldException ex1) { + ClassNodeAdapter.notSupported = true; + } + } + return null; + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java index 1feedbab..857468cc 100644 --- a/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java +++ b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.service.modlauncher.MixinServiceModLauncher; import org.spongepowered.asm.service.modlauncher.ModLauncherAuditTrail; +import org.spongepowered.asm.transformers.MixinClassReader; import com.google.common.io.Resources; @@ -229,7 +230,7 @@ public class MixinLaunchPlugin implements ILaunchPluginService, IClassBytecodePr } ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(classBytes); + ClassReader classReader = new MixinClassReader(classBytes, name); classReader.accept(classNode, ClassReader.EXPAND_FRAMES); return classNode; } From 65b4f9d55a1eb9f5c5491e8a1cfcee3ba9b8fb0e Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 24 Jun 2021 20:22:28 +0100 Subject: [PATCH 40/42] Pass the correct (mutable) targets set to plugins, fixes #485 --- .../spongepowered/asm/mixin/transformer/MixinConfig.java | 8 ++++++++ .../asm/mixin/transformer/MixinProcessor.java | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) 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 b15e1ef1..204b46e6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -1012,6 +1012,14 @@ final class MixinConfig implements Comparable, IMixinConfig { public IMixinConfigPlugin getPlugin() { return this.plugin.get(); } + + /** + * Returns a mutable view of the targets set, used to pass the targets to + * config plugins + */ + public Set getTargetsSet() { + return this.mixinMapping.keySet(); + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getTargets() diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 977782fe..8dc8fea7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -538,7 +538,7 @@ class MixinProcessor { } } - plugin.acceptTargets(config.getTargets(), Collections.unmodifiableSet(otherTargets)); + plugin.acceptTargets(config.getTargetsSet(), Collections.unmodifiableSet(otherTargets)); } for (MixinConfig config : this.pendingConfigs) { From 33c1d2ee0d4239eb483629db1c03ae7f76315ba5 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Fri, 25 Jun 2021 13:10:01 +0100 Subject: [PATCH 41/42] Fix valid signatures being reported as invalid when using ASM 5 --- .../asm/mixin/injection/struct/MemberInfo.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index 60909ce0..dcbdecf0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -44,6 +44,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; +import org.spongepowered.asm.util.asm.ASM; import com.google.common.base.Objects; import com.google.common.base.Strings; @@ -667,10 +668,16 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } } else { try { - for (Type argType : Type.getArgumentTypes(this.desc)) { - // getInternalName is a useful litmus test for improperly-formatted types which parse out of - // the descriptor correctly but are actually invalid, for example unterminated class names - argType.getInternalName(); + // getArgumentTypes can choke on some invalid descriptors + Type[] argTypes = Type.getArgumentTypes(this.desc); + // getInternalName is a useful litmus test for improperly-formatted types which parse out of + // the descriptor correctly but are actually invalid, for example unterminated class names. + // However it doesn't support primitive types properly in ASM versions before 6 so don't run + // the test unless running ASM 6 or later + if (ASM.isAtLeastVersion(6)) { + for (Type argType : argTypes) { + argType.getInternalName(); + } } } catch (Exception ex) { throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); From 0dc21a78ee69d175b6c3422bcbfa41b539decacd Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Fri, 25 Jun 2021 18:01:27 +0100 Subject: [PATCH 42/42] Fix some version checks to properly respect *major* class version --- .../asm/mixin/MixinEnvironment.java | 11 ++++++++-- .../transformer/MixinApplicatorStandard.java | 6 +++++- .../mixin/transformer/MixinTargetContext.java | 21 ++++++++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 74744307..34bff3bb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -671,9 +671,9 @@ public final class MixinEnvironment implements ITokenProvider { private CompatibilityLevel maxCompatibleLevel; - private CompatibilityLevel(int ver, int classMajorVersion, int languageFeatures) { + private CompatibilityLevel(int ver, int classVersion, int languageFeatures) { this.ver = ver; - this.classVersion = classMajorVersion & 0xFF; + this.classVersion = classVersion; this.languageFeatures = languageFeatures; } @@ -702,6 +702,13 @@ public final class MixinEnvironment implements ITokenProvider { return this.classVersion; } + /** + * Get the major class version expected at this compatibility level + */ + public int getClassMajorVersion() { + return this.classVersion & 0xFFFF; + } + /** * Get all supported language features */ diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 4bb7b5ed..dd2ef0e1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -434,7 +434,11 @@ class MixinApplicatorStandard { if (mixin.shouldSetSourceFile()) { this.targetClass.sourceFile = mixin.getSourceFile(); } - this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion()); + + int requiredVersion = mixin.getMinRequiredClassVersion(); + if ((requiredVersion & 0xFFFF) > (this.targetClass.version & 0xFFFF)) { + this.targetClass.version = requiredVersion; + } } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index ac9c05b2..51f2077d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -1071,13 +1071,28 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param version version to require */ protected void requireVersion(int version) { - this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version); + int majorVersion = version & 0xFFFF; + int minorVersion = (version >> 16) & 0xFFFF; + + if (majorVersion <= (this.minRequiredClassVersion & 0xFFFF)) { + return; + } + + this.minRequiredClassVersion = version; // This validation is done on the mixin beforehand, however it's still // possible that an upstream transformer can inject unsupported // instructions without updating the class version. - if ((version & 0xFFFF) > ASM.getMaxSupportedClassVersionMajor()) { - throw new InvalidMixinException(this, "Unsupported mixin class version " + version); + if (majorVersion > ASM.getMaxSupportedClassVersionMajor()) { + throw new InvalidMixinException(this, String.format("Unsupported mixin class version %d.%d. ASM supports %s", + majorVersion, minorVersion, ASM.getClassVersionString())); + } + + CompatibilityLevel compatibilityLevel = MixinEnvironment.getCompatibilityLevel(); + if (majorVersion > compatibilityLevel.getClassMajorVersion()) { + MixinTargetContext.logger.warn( + "{}: Class version {}.{} required is higher than the class version supported by the current compatibility level {} ", + this, majorVersion, minorVersion, compatibilityLevel); } }
0.8.10.8.3February 2021 +
    +
  • Added dynamic target selector support and @Desc + target selector
  • +
  • Added pattern target selector
  • +
  • Added more expressive quantifier support to explicit target + selectors
  • +
  • Facelift and overall improvements to javadoc
  • +
+
0.8.1 (0.8.2) September 2020
  • Hotfix for supporting ModLauncher 7.0
  • Fix critical issue with resolving obfuscated members in inherited interfaces
  • +
  • Updated to ASM 7.2