From 53df42cae5d8101e73154bd89d0a696d7acff310 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 2 Jan 2017 00:16:00 +0000 Subject: [PATCH] Support explicit descriptors for ctor redirect, closes #157 --- gradle.properties | 2 +- .../AnnotatedMixinElementHandler.java | 54 +------- .../AnnotatedMixinElementHandlerInjector.java | 125 +++++++++++++++--- .../asm/launch/MixinBootstrap.java | 2 +- .../asm/mixin/injection/InjectionNodes.java | 10 +- .../asm/mixin/injection/code/Injector.java | 45 ++++++- .../injection/invoke/RedirectInjector.java | 89 ++++++++++++- .../asm/mixin/injection/points/BeforeNew.java | 68 +++++++++- .../mixin/injection/struct/MemberInfo.java | 85 +++++++++++- 9 files changed, 377 insertions(+), 103 deletions(-) diff --git a/gradle.properties b/gradle.properties index 099b9855..708eb7b8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,5 +4,5 @@ packaging=jar description=Mixin url=https://www.spongepowered.org organization=SpongePowered -buildVersion=0.6.3 +buildVersion=0.6.4 buildType=SNAPSHOT diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index ab81ae90..78a1018f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -33,7 +33,6 @@ import javax.lang.model.element.VariableElement; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; -import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; @@ -42,15 +41,14 @@ import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; import org.spongepowered.asm.util.throwables.ConstraintViolationException; import org.spongepowered.asm.util.throwables.InvalidConstraintException; -import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.FieldHandle; import org.spongepowered.tools.obfuscation.mirror.MethodHandle; -import org.spongepowered.tools.obfuscation.mirror.TypeUtils; import org.spongepowered.tools.obfuscation.mirror.TypeHandle; +import org.spongepowered.tools.obfuscation.mirror.TypeUtils; /** * Base class for module for {@link AnnotatedMixin} which handle different @@ -302,56 +300,6 @@ abstract class AnnotatedMixinElementHandler { } return this.mappings; } - - protected final boolean remapReference(String key, String reference, Element element, AnnotationHandle inject, AnnotationHandle at) { - if (reference == null) { - return false; - } - - String annotation = "@At(" + key + ")"; - MemberInfo targetMember = MemberInfo.parse(reference); - if (!targetMember.isFullyQualified()) { - String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"); - this.ap.printMessage(Kind.ERROR, annotation + " is not fully qualified, " + missing, element, inject.asMirror()); - return false; - } - - try { - targetMember.validate(); - } catch (InvalidMemberDescriptorException ex) { - this.ap.printMessage(Kind.ERROR, ex.getMessage(), element, inject.asMirror()); - } - - try { - if (targetMember.isField()) { - ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); - if (obfFieldData.isEmpty()) { - this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + annotation + " '" + reference + "'", element, - inject.asMirror()); - return false; - } - this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); - } else { - ObfuscationData obfMethodData = this.obf.getDataProvider().getObfMethodRecursive(targetMember); - if (obfMethodData.isEmpty()) { - if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) { - this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + annotation + " '" + reference + "'", element, - inject.asMirror()); - return false; - } - } - this.obf.getReferenceManager().addMethodMapping(this.classRef, reference, targetMember, obfMethodData); - } - } catch (ReferenceConflictException ex) { - // 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 " + annotation + ": " + reference + " -> " - + ex.getNew() + " previously defined as " + ex.getOld(), element, inject.asMirror()); - return false; - } - - return true; - } protected final void addFieldMappings(String mcpName, String mcpSignature, ObfuscationData obfData) { for (ObfuscationType type : obfData) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 5095f874..5296fb99 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -32,6 +32,7 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; 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.Constants; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; @@ -75,6 +76,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler private final AnnotationHandle at; + private Map args; + public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at) { super(element, inject); this.at = at; @@ -84,6 +87,24 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return this.at; } + public String getAtArg(String key) { + if (this.args == null) { + this.args = new HashMap(); + for (String arg : this.at.getList("args")) { + if (arg == null) { + continue; + } + int eqPos = arg.indexOf('='); + if (eqPos > -1) { + this.args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1)); + } else { + this.args.put(arg, ""); + } + } + } + + return this.args.get(key); + } } AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { @@ -181,31 +202,95 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String type = elem.getAt().getValue("value"); String target = elem.getAt().getValue("target"); - int remapped = this.remapReference(type + ".", target, elem.getElement(), elem.getAnnotation(), elem.getAt()) ? 1 : 0; + int remapped = 0; - // Pattern for replacing references in args, not used yet -// if ("SOMETYPE".equals(type)) { -// Map args = InjectorHandler.getAtArgs(e.getAt()); -// this.remapReference(type + ".args[target]", args.get("target")); -// } + if ("NEW".equals(type)) { + remapped += this.remapNewTarget("@At(" + type + ".)", target, elem) ? 1 : 0; + remapped += this.remapNewTarget("@At(" + type + ".args[class])", elem.getAtArg("class"), elem) ? 1 : 0; + } else { + remapped += this.remapReference("@At(" + type + ".)", target, elem) ? 1 : 0; + } return remapped; } - - static Map getAtArgs(AnnotationHandle at) { - Map args = new HashMap(); - for (String arg : at.getList("args")) { - if (arg == null) { - continue; - } - int eqPos = arg.indexOf('='); - if (eqPos > -1) { - args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1)); - } else { - args.put(arg, ""); - } + + protected final boolean remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) { + if (reference == null) { + return false; } - return args; + + MemberInfo member = MemberInfo.parse(reference); + 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()) { + this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), + elem.getAnnotation().asMirror()); + return false; + } + + ObfuscationData mappings = new ObfuscationData(); + for (ObfuscationType type : remapped) { + MappingMethod mapping = remapped.get(type); + mappings.add(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); + } + + this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + } + + return true; + } + + protected final boolean remapReference(String subject, String reference, AnnotatedElementInjectionPoint elem) { + if (reference == null) { + return false; + } + + MemberInfo targetMember = MemberInfo.parse(reference); + if (!targetMember.isFullyQualified()) { + String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"); + this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, " + missing, elem.getElement(), elem.getAnnotation().asMirror()); + return false; + } + + try { + targetMember.validate(); + } catch (InvalidMemberDescriptorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAnnotation().asMirror()); + } + + try { + if (targetMember.isField()) { + ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); + if (obfFieldData.isEmpty()) { + this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), + elem.getAnnotation().asMirror()); + return false; + } + this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); + } else { + ObfuscationData obfMethodData = this.obf.getDataProvider().getObfMethodRecursive(targetMember); + if (obfMethodData.isEmpty()) { + if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) { + this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), + elem.getAnnotation().asMirror()); + return false; + } + } + this.obf.getReferenceManager().addMethodMapping(this.classRef, reference, targetMember, obfMethodData); + } + } catch (ReferenceConflictException ex) { + // 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(), elem.getAnnotation().asMirror()); + return false; + } + + return true; } } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index 2d2a2b5d..14a138b0 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -62,7 +62,7 @@ public abstract class MixinBootstrap { /** * Subsystem version */ - public static final String VERSION = "0.6.3"; + public static final String VERSION = "0.6.4"; // Consts private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java index 006e9cec..5f4486dc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java @@ -68,7 +68,7 @@ public class InjectionNodes extends ArrayList { /** * Injector decorations on this node */ - private Map decorations; + private Map decorations; /** * Create a new node wrapper for the specified target node @@ -144,9 +144,9 @@ public class InjectionNodes extends ArrayList { * @param key meta key * @param value meta value */ - public InjectionNode decorate(K key, V value) { + public InjectionNode decorate(String key, V value) { if (this.decorations == null) { - this.decorations = new HashMap(); + this.decorations = new HashMap(); } this.decorations.put(key, value); return this; @@ -169,7 +169,7 @@ public class InjectionNodes extends ArrayList { * @return decoration value or null if absent */ @SuppressWarnings("unchecked") - public V getDecoration(K key) { + public V getDecoration(String key) { return (V) (this.decorations == null ? null : this.decorations.get(key)); } @@ -186,7 +186,7 @@ public class InjectionNodes extends ArrayList { */ @Override public String toString() { - return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget)); + return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget).replaceAll("\\s+", " ")); } } 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 baf3d774..257e871d 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 @@ -26,8 +26,10 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.apache.logging.log4j.LogManager; @@ -57,6 +59,20 @@ import com.google.common.base.Joiner; */ public abstract class Injector { + /** + * A nominated target node + */ + class TargetNode { + + final AbstractInsnNode node; + + final Set nominators = new HashSet(); + + TargetNode(AbstractInsnNode node) { + this.node = node; + } + } + /** * Log more things */ @@ -133,13 +149,13 @@ public abstract class Injector { this.sanityCheck(target, injectionPoints); List myNodes = new ArrayList(); - for (AbstractInsnNode node : this.findTargetNodes(target.method, injectionPoints)) { - this.addTargetNode(target, myNodes, node); + for (TargetNode node : this.findTargetNodes(target.method, injectionPoints)) { + this.addTargetNode(target, myNodes, node.node, node.nominators); } return myNodes; } - protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node) { + protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node, Set nominators) { myNodes.add(target.injectionNodes.add(node)); } @@ -153,6 +169,10 @@ public abstract class Injector { } this.inject(target, node); } + + for (InjectionNode node : nodes) { + this.postInject(target, node); + } } /** @@ -164,8 +184,8 @@ public abstract class Injector { * annotations on the callback method * @return Target insn nodes in the target method */ - protected Set findTargetNodes(MethodNode into, List injectionPoints) { - Set targetNodes = new HashSet(); + private Collection findTargetNodes(MethodNode into, List injectionPoints) { + Map targetNodes = new HashMap(); // Defensive objects, so that injectionPoint instances can't modify our working copies ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions); @@ -174,12 +194,19 @@ public abstract class Injector { for (InjectionPoint injectionPoint : injectionPoints) { nodes.clear(); if (this.findTargetNodes(into, injectionPoint, insns, nodes)) { - targetNodes.addAll(nodes); + for (AbstractInsnNode node : nodes) { + TargetNode target = targetNodes.get(node); + if (target == null) { + target = new TargetNode(node); + targetNodes.put(node, target); + } + target.nominators.add(injectionPoint); + } } } insns.dispose(); - return targetNodes; + return targetNodes.values(); } protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { @@ -194,6 +221,10 @@ public abstract class Injector { protected abstract void inject(Target target, InjectionNode node); + protected void postInject(Target target, InjectionNode node) { + // stub + } + /** * Invoke the handler method * 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 a195af08..66ef74be 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 @@ -24,16 +24,29 @@ */ package org.spongepowered.asm.mixin.injection.invoke; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Set; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.*; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.lib.tree.JumpInsnNode; +import org.spongepowered.asm.lib.tree.LabelNode; +import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.spongepowered.asm.lib.tree.TypeInsnNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.points.BeforeNew; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -80,6 +93,9 @@ import com.google.common.primitives.Ints; */ public class RedirectInjector extends InvokeInjector { + private static final String KEY_NOMINATORS = "nominators"; + private static final String KEY_WILD = "wildcard"; + /** * Meta decoration object for redirector target nodes */ @@ -108,8 +124,21 @@ public class RedirectInjector extends InvokeInjector { } + /** + * Meta decoration for wildcard ctor redirects + */ + class ConstructorRedirectData { + + public static final String KEY = "ctor"; + + public int injected = 0; + + } + protected Meta meta; + private Map ctorRedirectors = new HashMap(); + /** * @param info Injection info */ @@ -135,8 +164,9 @@ public class RedirectInjector extends InvokeInjector { } @Override - protected void addTargetNode(Target target, List myNodes, AbstractInsnNode insn) { + protected void addTargetNode(Target target, List myNodes, AbstractInsnNode insn, Set nominators) { InjectionNode node = target.injectionNodes.get(insn); + ConstructorRedirectData ctorData = null; if (node != null ) { Meta other = node.getDecoration(Meta.KEY); @@ -153,7 +183,29 @@ public class RedirectInjector extends InvokeInjector { } } - myNodes.add(target.injectionNodes.add(insn).decorate(Meta.KEY, this.meta)); + for (InjectionPoint ip : nominators) { + if (ip instanceof BeforeNew && !((BeforeNew)ip).hasDescriptor()) { + ctorData = this.getCtorRedirect((BeforeNew)ip); + } + } + + InjectionNode targetNode = target.injectionNodes.add(insn); + targetNode.decorate(Meta.KEY, this.meta); + targetNode.decorate(RedirectInjector.KEY_NOMINATORS, nominators); + if (insn instanceof TypeInsnNode && insn.getOpcode() == Opcodes.NEW) { + targetNode.decorate(RedirectInjector.KEY_WILD, Boolean.valueOf(ctorData != null)); + targetNode.decorate(ConstructorRedirectData.KEY, ctorData); + } + myNodes.add(targetNode); + } + + private ConstructorRedirectData getCtorRedirect(BeforeNew ip) { + ConstructorRedirectData ctorRedirect = this.ctorRedirectors.get(ip); + if (ctorRedirect == null) { + ctorRedirect = new ConstructorRedirectData(); + this.ctorRedirectors.put(ip, ctorRedirect); + } + return ctorRedirect; } @Override @@ -200,6 +252,18 @@ public class RedirectInjector extends InvokeInjector { return true; } + @Override + protected void postInject(Target target, InjectionNode node) { + super.postInject(target, node); + if (node.getOriginalTarget() instanceof TypeInsnNode && node.getOriginalTarget().getOpcode() == Opcodes.NEW) { + ConstructorRedirectData meta = node.getDecoration(ConstructorRedirectData.KEY); + boolean wildcard = node.getDecoration(RedirectInjector.KEY_WILD).booleanValue(); + if (wildcard && meta.injected == 0) { + throw new InvalidInjectionException(this.info, this.annotationType + " ctor invocation was not found in " + target); + } + } + } + /** * Redirect a method invocation */ @@ -341,18 +405,32 @@ public class RedirectInjector extends InvokeInjector { } protected void injectAtConstructor(Target target, InjectionNode node) { + ConstructorRedirectData meta = node.getDecoration(ConstructorRedirectData.KEY); + boolean wildcard = node.getDecoration(RedirectInjector.KEY_WILD).booleanValue(); + final TypeInsnNode newNode = (TypeInsnNode)node.getCurrentTarget(); final AbstractInsnNode dupNode = target.get(target.indexOf(newNode) + 1); final MethodInsnNode initNode = this.findInitNode(target, newNode); if (initNode == null) { - throw new InvalidInjectionException(this.info, this.annotationType + " ctor invocation was not found in " + target); + if (!wildcard) { + throw new InvalidInjectionException(this.info, this.annotationType + " ctor invocation was not found in " + target); + } + return; } // True if the result of the object construction is being assigned boolean isAssigned = dupNode.getOpcode() == Opcodes.DUP; String desc = initNode.desc.replace(")V", ")L" + newNode.desc + ";"); - boolean withArgs = this.checkDescriptor(desc, target, "constructor"); + boolean withArgs = false; + try { + withArgs = this.checkDescriptor(desc, target, "constructor"); + } catch (InvalidInjectionException ex) { + if (!wildcard) { + throw ex; + } + return; + } if (isAssigned) { target.removeNode(dupNode); @@ -389,6 +467,7 @@ public class RedirectInjector extends InvokeInjector { } target.replaceNode(initNode, insns); + meta.injected++; } protected MethodInsnNode findInitNode(Target target, TypeInsnNode newNode) { 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 e212cdd6..80fa779f 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 @@ -24,15 +24,20 @@ */ package org.spongepowered.asm.mixin.injection.points; +import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; import java.util.ListIterator; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.TypeInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.util.Constants; import com.google.common.base.Strings; @@ -43,7 +48,7 @@ import com.google.common.base.Strings; * {@link org.spongepowered.asm.mixin.injection.At At}:

* *
- *
named argument class
+ *
named argument class (or specify using target
*
The value of the NEW node to look for, the fully-qualified class name *
*
ordinal
@@ -51,15 +56,28 @@ import com.google.common.base.Strings; * opcode appears 3 times in the method 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 + *
target
+ *
Target class can also be specified in target which also + * supports specifying the exact signature of the constructor to target. In + * this case the target type is specified as the return type of the + * constructor (in place of the usual V (void)) and no owner or name + * should be specified (they are ignored).
*
* *

Examples:

*
+ *   // Find all NEW opcodes for String
  *   @At(value = "NEW", args = "class=java/lang/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
+ *   @At(value = "NEW", target = "([C)Ljava/lang/String;"
+ *
* *

Note that like all standard injection points, this class matches the insn * itself, putting the injection point immediately before the access in @@ -73,7 +91,12 @@ public class BeforeNew extends InjectionPoint { /** * Class name we're looking for */ - private final String className; + private final String target; + + /** + * Ctor descriptor we're looking for + */ + private final String desc; /** * Ordinal value @@ -82,32 +105,65 @@ public class BeforeNew extends InjectionPoint { public BeforeNew(InjectionPointData data) { this.ordinal = data.getOrdinal(); - this.className = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); + String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); + MemberInfo member = MemberInfo.parseAndValidate(target, data.getMixin()); + this.target = member.toCtorType(); + this.desc = member.toCtorDesc(); + } + + public boolean hasDescriptor() { + return this.desc != null; } + @SuppressWarnings("unchecked") @Override public boolean find(String desc, InsnList insns, Collection nodes) { boolean found = false; int ordinal = 0; + Collection newNodes = new ArrayList(); + Collection candidates = (Collection) (this.desc != null ? newNodes : nodes); ListIterator iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (insn instanceof TypeInsnNode && insn.getOpcode() == Opcodes.NEW && this.matchesOwner((TypeInsnNode) insn)) { if (this.ordinal == -1 || this.ordinal == ordinal) { - nodes.add(insn); - found = true; + candidates.add(insn); + found = this.desc == null; } ordinal++; } } + + if (this.desc != null) { + for (TypeInsnNode newNode : newNodes) { + if (this.findCtor(insns, newNode)) { + nodes.add(newNode); + found = true; + } + } + } return found; } + protected boolean findCtor(InsnList insns, TypeInsnNode newNode) { + int indexOf = insns.indexOf(newNode); + for (Iterator iter = insns.iterator(indexOf); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof MethodInsnNode && insn.getOpcode() == Opcodes.INVOKESPECIAL) { + MethodInsnNode methodNode = (MethodInsnNode)insn; + if (Constants.CTOR.equals(methodNode.name) && methodNode.owner.equals(newNode.desc) && methodNode.desc.equals(this.desc)) { + return true; + } + } + } + return false; + } + private boolean matchesOwner(TypeInsnNode insn) { - return this.className == null || this.className.equals(insn.desc); + return this.target == null || this.target.equals(insn.desc); } } 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 3afeff53..dcc5a465 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 @@ -36,6 +36,8 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.SignaturePrinter; +import com.google.common.base.Strings; + /** *

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 @@ -102,6 +104,11 @@ public class MemberInfo { * Force this member to report as a field */ private final boolean forceField; + + /** + * The actual String value passed into the {@link #parse} method + */ + private final String unparsed; /** * ctor @@ -149,6 +156,19 @@ public class MemberInfo { * @param matchAll True to match all matching members, not just the first */ public MemberInfo(String name, String owner, String desc, boolean matchAll) { + this(name, owner, desc, matchAll, 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 matchAll True to match all matching members, not just the first + */ + public MemberInfo(String name, String owner, String desc, boolean matchAll, String unparsed) { if (owner != null && owner.contains(".")) { throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format"); } @@ -158,6 +178,7 @@ public class MemberInfo { this.desc = desc; this.matchAll = matchAll; this.forceField = false; + this.unparsed = unparsed; } /** @@ -169,6 +190,7 @@ public class MemberInfo { public MemberInfo(AbstractInsnNode insn) { this.matchAll = false; this.forceField = false; + this.unparsed = null; if (insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; @@ -196,6 +218,7 @@ public class MemberInfo { this.desc = mapping.getDesc(); this.matchAll = false; this.forceField = mapping.getType() == IMapping.Type.FIELD; + this.unparsed = null; } /** @@ -209,6 +232,7 @@ public class MemberInfo { this.desc = method.getDesc(); this.matchAll = remapped.matchAll; this.forceField = false; + this.unparsed = null; } /** @@ -223,6 +247,7 @@ public class MemberInfo { this.desc = original.desc; this.matchAll = original.matchAll; this.forceField = original.forceField; + this.unparsed = null; } /* (non-Javadoc) @@ -265,6 +290,47 @@ public class MemberInfo { return new SignaturePrinter(this).setFullyQualified(true).toDescriptor(); } + public String toCtorType() { + if (this.unparsed == null) { + return null; + } + + String returnType = this.getReturnType(); + if (returnType != null) { + return returnType; + } + + if (this.owner != null) { + return this.owner; + } + + if (this.name != null && this.desc == null) { + return this.name; + } + + return this.desc != null ? this.desc : this.unparsed; + } + + public String toCtorDesc() { + if (this.desc != null && this.desc.startsWith("(") && this.desc.indexOf(')') > -1) { + return this.desc.substring(0, this.desc.indexOf(')') + 1) + "V"; + } + + return null; + } + + public String getReturnType() { + if (this.desc == null || this.desc.indexOf(')') == -1 || this.desc.indexOf('(') != 0 ) { + return null; + } + + String returnType = this.desc.substring(this.desc.indexOf(')') + 1); + if (returnType.startsWith("L") && returnType.endsWith(";")) { + return returnType.substring(1, returnType.length() - 1); + } + return returnType; + } + public IMapping asMapping() { return this.isField() ? this.asFieldMapping() : this.asMethodMapping(); } @@ -503,16 +569,15 @@ public class MemberInfo { /** * Parse a MemberInfo from a string * - * @param name String to parse MemberInfo from + * @param input String to parse MemberInfo from * @param refMapper Reference mapper to use * @param mixinClass Mixin class to use for remapping * @return parsed MemberInfo */ - private static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) { + private static MemberInfo parse(String input, ReferenceMapper refMapper, String mixinClass) { String desc = null; String owner = null; - - name = name.replaceAll("\\s", ""); + String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); if (refMapper != null) { name = refMapper.remap(mixinClass, name); @@ -538,6 +603,11 @@ public class MemberInfo { name = name.substring(0, colonPos); } + if ((name.indexOf('/') > -1 || name.indexOf('.') > -1) && owner == null) { + owner = name; + name = ""; + } + boolean matchAll = name.endsWith("*"); if (matchAll) { name = name.substring(0, name.length() - 1); @@ -547,10 +617,15 @@ public class MemberInfo { name = null; } - return new MemberInfo(name, owner, desc, matchAll); + return new MemberInfo(name, owner, desc, matchAll, input); } public static MemberInfo fromMapping(IMapping mapping) { return new MemberInfo(mapping); } + + public static void main(String[] args) { + MemberInfo m = MemberInfo.parseAndValidate(null); //"(Lfoo;III)Lfoo/bar/qcv;"); + System.err.printf(">> [%s] [%s]\n", m.toCtorType(), m.toCtorDesc()); + } }