From e02f4cae3fe51d6bd83de5e020956587ead8087c Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 21 Jan 2024 18:25:47 +0000 Subject: [PATCH] Refactoring cherry-pick from 0.8.6-dev for target selectors --- .../tools/obfuscation/AnnotatedMixin.java | 5 + .../AnnotatedMixinElementHandler.java | 5 + .../AnnotatedMixinElementHandlerInjector.java | 10 +- .../asm/mixin/gen/AccessorInfo.java | 3 +- .../asm/mixin/gen/InvokerInfo.java | 2 +- .../asm/mixin/injection/Desc.java | 2 +- .../asm/mixin/injection/InjectionPoint.java | 42 +- .../asm/mixin/injection/Next.java | 86 ++++ .../asm/mixin/injection/Slice.java | 14 +- .../injection/callback/CallbackInjector.java | 9 +- .../asm/mixin/injection/code/Injector.java | 40 +- .../mixin/injection/code/InjectorTarget.java | 38 +- .../asm/mixin/injection/code/MethodSlice.java | 50 ++- .../mixin/injection/code/MethodSlices.java | 10 + .../injection/invoke/RedirectInjector.java | 7 +- .../invoke/arg/ArgsClassGenerator.java | 4 +- .../injection/points/BeforeConstant.java | 2 +- .../injection/selectors/ISelectorContext.java | 6 + .../injection/selectors/TargetSelectors.java | 375 ++++++++++++++++++ .../selectors/dynamic/DescriptorResolver.java | 25 +- .../dynamic/DynamicSelectorDesc.java | 26 +- .../dynamic/IResolvedDescriptor.java | 6 + .../mixin/injection/struct/InjectionInfo.java | 321 +++++---------- .../injection/struct/InjectionPointData.java | 18 +- .../struct/ModifyConstantInjectionInfo.java | 16 +- .../struct/SelectorAnnotationContext.java | 9 + .../asm/mixin/injection/struct/Target.java | 2 +- .../asm/mixin/refmap/IMixinContext.java | 7 + .../asm/mixin/struct/AnnotatedMethodInfo.java | 80 ++++ .../asm/mixin/struct/SpecialMethodInfo.java | 16 +- .../mixin/transformer/MixinCoprocessor.java | 4 +- .../mixin/transformer/MixinTargetContext.java | 8 + 32 files changed, 895 insertions(+), 353 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/Next.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelectors.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index f3b918a8..5e85e421 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -467,6 +467,11 @@ class AnnotatedMixin implements IMixinContext, IAnnotatedElement { public String getClassName() { return this.getClassRef().replace('/', '.'); } + + @Override + public String getTargetClassName() { + return this.primaryTarget.toString(); + } @Override public String getTargetClassRef() { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 2e7c7415..375af9e0 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -165,6 +165,11 @@ abstract class AnnotatedMixinElementHandler { return reference; } + @Override + public String getElementDescription() { + return String.format("%s annotation on %s", this.getAnnotation(), this); + } + @Override public String toString() { return TypeUtils.getName(this.element); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index fb6b9623..ebea7621 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -257,13 +257,13 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } } - IReferenceManager refMap = this.obf.getReferenceManager(); + IReferenceManager refMaps = this.obf.getReferenceManager(); try { // If the original owner is unspecified, and the mixin is multi-target, we strip the owner from the obf mappings if ((targetMember.getOwner() == null && this.mixin.isMultiTarget()) || target.isSimulated()) { obfData = AnnotatedMixinElementHandler.stripOwnerData(obfData); } - refMap.addMethodMapping(this.classRef, reference, obfData); + refMaps.addMethodMapping(this.classRef, reference, obfData); } catch (ReferenceConflictException ex) { String conflictType = this.mixin.isMultiTarget() ? "Multi-target" : "Target"; @@ -274,9 +274,9 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String newName = newMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)newMember).getName() : newMember.toString(); if (oldName != null && oldName.equals(newName)) { obfData = AnnotatedMixinElementHandler.stripDescriptors(obfData); - refMap.setAllowConflicts(true); - refMap.addMethodMapping(this.classRef, reference, obfData); - refMap.setAllowConflicts(false); + refMaps.setAllowConflicts(true); + refMaps.addMethodMapping(this.classRef, reference, obfData); + refMaps.setAllowConflicts(false); // This is bad because in notch mappings, using the bare target name might cause everything to explode elem.printMessage(this.ap, MessageType.BARE_REFERENCE, "Coerced " + conflictType + " reference has conflicting descriptors for " 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 14cd8fb2..68bc81be 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -515,7 +515,8 @@ public class AccessorInfo extends SpecialMethodInfo { try { return result.getSingleResult(true); } catch (IllegalStateException ex) { - throw new InvalidAccessorException(this, ex.getMessage() + " matching " + this.target + " in " + this.classNode.name + " for " + this); + throw new InvalidAccessorException(this, String.format("%s matching %s in %s for %s", + ex.getMessage(), this.target, this.classNode.name, this)); } } 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 b65d0c15..ef6ccabe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -109,7 +109,7 @@ class InvokerInfo extends AccessorInfo { try { return result.getSingleResult(true); } catch (IllegalStateException ex) { - String message = ex.getMessage() + " matching " + this.target + " in " + this.classNode.name + " for " + this; + String message = String.format("%s matching %s in %s for %s", ex.getMessage(), this.target, this.classNode.name, this); if (this.type == AccessorType.METHOD_PROXY && this.specifiedName != null && this.target instanceof ITargetSelectorByName) { String name = ((ITargetSelectorByName)this.target).getName(); if (name != null && (name.contains(".") || name.contains("/"))) { 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 97ec046b..b30f45bd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -115,7 +115,7 @@ public @interface Desc { * The next elements of this descriptor path, evaluated in order for each * recurse point. */ - // public Next[] next() default { }; + public Next[] next() default { }; /** * The minimum number of times this selector should match. By default the 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 141740a3..725ba6c7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -162,15 +162,19 @@ public abstract class InjectionPoint { } /** - * Selector type for slice delmiters, ignored for normal injection points. - * Selectors can be supplied in {@link At} annotations by including - * a colon (:) character followed by the selector type - * (case-sensitive), eg: + * Additional specifier for injection points. Specifiers can be + * supplied in {@link At} annotations by including a colon (:) + * character followed by the specifier type (case-sensitive), eg: * *
@At(value = "INVOKE:LAST", ... )
*/ - public enum Selector { - + public enum Specifier { + + /** + * Use all instructions from the query result. + */ + ALL, + /** * Use the first instruction from the query result. */ @@ -186,13 +190,13 @@ public abstract class InjectionPoint { * more than one instruction this should be considered a fail-fast error * state and a runtime exception will be thrown. */ - ONE; + ONE, /** - * Default selector type used if no selector is explicitly specified. - * For internal use only. Currently {@link #FIRST} + * Use the default setting as defined by the consumer. For slices this + * is {@link #FIRST}, for all other consumers this is {@link #ALL} */ - public static final Selector DEFAULT = Selector.FIRST; + DEFAULT; } @@ -276,26 +280,26 @@ public abstract class InjectionPoint { } private final String slice; - private final Selector selector; + private final Specifier specifier; private final String id; private final IMessageSink messageSink; protected InjectionPoint() { - this("", Selector.DEFAULT, null); + this("", Specifier.DEFAULT, null); } protected InjectionPoint(InjectionPointData data) { - this(data.getSlice(), data.getSelector(), data.getId(), data.getMessageSink()); + this(data.getSlice(), data.getSpecifier(), data.getId(), data.getMessageSink()); } - public InjectionPoint(String slice, Selector selector, String id) { - this(slice, selector, id, null); + public InjectionPoint(String slice, Specifier specifier, String id) { + this(slice, specifier, id, null); } - public InjectionPoint(String slice, Selector selector, String id, IMessageSink messageSink) { + public InjectionPoint(String slice, Specifier specifier, String id, IMessageSink messageSink) { this.slice = slice; - this.selector = selector; + this.specifier = specifier; this.id = id; this.messageSink = messageSink; } @@ -304,8 +308,8 @@ public abstract class InjectionPoint { return this.slice; } - public Selector getSelector() { - return this.selector; + public Specifier getSpecifier(Specifier defaultSpecifier) { + return this.specifier == Specifier.DEFAULT ? defaultSpecifier : this.specifier; } public String getId() { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Next.java b/src/main/java/org/spongepowered/asm/mixin/injection/Next.java new file mode 100644 index 00000000..c16b96af --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Next.java @@ -0,0 +1,86 @@ +/* + * 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.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * See {@link Desc#next @Desc.next} + */ +@Target({ }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Next { + + /** + * The name of the member to match. Optional. If present is matched + * case-sensitively against targets. + */ + public String name() default ""; + + /** + * 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 { }; + + /** + * 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/Slice.java b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java index 857432db..68689107 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java @@ -28,7 +28,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; +import org.spongepowered.asm.mixin.injection.InjectionPoint.Specifier; /** * A Slice identifies a section of a method to search for injection @@ -162,10 +162,10 @@ public @interface Slice { /** * Injection point which specifies the start of the slice region. - * {@link At}s supplied here should generally specify a {@link Selector} + * {@link At}s supplied here should generally use a {@link Specifier} * in order to identify which instruction should be used for queries which - * return multiple results. The selector is specified by appending the - * selector type to the injection point type as follows: + * return multiple results. The specifier is supplied by appending the + * specifier type to the injection point type as follows: * *
@At(value = "INVOKE:LAST", ... )
* @@ -182,9 +182,9 @@ public @interface Slice { /** * Injection point which specifies the end of the slice region. * Like {@link #from}, {@link At}s supplied here should generally specify a - * {@link Selector} in order to identify which instruction should be used - * for queries which return multiple results. The selector is specified by - * appending the selector type to the injection point type as follows: + * {@link Specifier} in order to identify which instruction should be used + * for queries which return multiple results. The specifier is supplied by + * appending the specifier type to the injection point type as follows: * *
@At(value = "INVOKE:LAST", ... )
* 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 55e3021f..3c6b5dd4 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 @@ -38,6 +38,7 @@ 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.code.InjectorTarget; 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; @@ -393,13 +394,13 @@ public class CallbackInjector extends Injector { * org.objectweb.asm.tree.AbstractInsnNode, java.util.Set) */ @Override - protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node, Set nominators) { - InjectionNode injectionNode = target.addInjectionNode(node); + protected void addTargetNode(InjectorTarget injectorTarget, List myNodes, AbstractInsnNode node, Set nominators) { + InjectionNode injectionNode = injectorTarget.addInjectionNode(node); for (InjectionPoint ip : nominators) { try { - this.checkTargetForNode(target, injectionNode, ip.getTargetRestriction(this.info)); + this.checkTargetForNode(injectorTarget.getTarget(), injectionNode, ip.getTargetRestriction(this.info)); } catch (InvalidInjectionException ex) { throw new InvalidInjectionException(this.info, String.format("%s selector %s", ip, ex.getMessage())); } @@ -412,7 +413,7 @@ public class CallbackInjector extends Injector { String existingId = this.ids.get(Integer.valueOf(injectionNode.getId())); if (existingId != null && !existingId.equals(id)) { Injector.logger.warn("Conflicting id for {} insn in {}, found id {} on {}, previously defined as {}", Bytecode.getOpcodeName(node), - target.toString(), id, this.info, existingId); + injectorTarget.toString(), id, this.info, existingId); break; } 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 e0f645c9..a53aa7c4 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 @@ -42,6 +42,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; +import org.spongepowered.asm.mixin.injection.InjectionPoint.Specifier; import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; @@ -238,13 +239,13 @@ public abstract class Injector { List myNodes = new ArrayList(); for (TargetNode node : this.findTargetNodes(injectorTarget, injectionPoints)) { - this.addTargetNode(injectorTarget.getTarget(), myNodes, node.insn, node.nominators); + this.addTargetNode(injectorTarget, myNodes, node.insn, node.nominators); } return myNodes; } - protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node, Set nominators) { - myNodes.add(target.addInjectionNode(node)); + protected void addTargetNode(InjectorTarget injectorTarget, List myNodes, AbstractInsnNode node, Set nominators) { + myNodes.add(injectorTarget.addInjectionNode(node)); } /** @@ -294,7 +295,7 @@ public abstract class Injector { IMixinContext mixin = this.info.getMixin(); MethodNode method = injectorTarget.getMethod(); Map targetNodes = new TreeMap(); - Collection nodes = new ArrayList(32); + List nodes = new ArrayList(32); for (InjectionPoint injectionPoint : injectionPoints) { nodes.clear(); @@ -307,15 +308,20 @@ public abstract class Injector { injectorTarget, injectorTarget.getMergedBy(), injectorTarget.getMergedPriority())); } - if (this.findTargetNodes(method, injectionPoint, injectorTarget, nodes)) { + if (!this.findTargetNodes(method, injectionPoint, injectorTarget, nodes)) { + continue; + } + + Specifier specifier = injectionPoint.getSpecifier(Specifier.ALL); + if (specifier == Specifier.ONE && nodes.size() != 1) { + throw new InvalidInjectionException(this.info, String.format("%s on %s has specifier :ONE but matched %d instructions", + injectionPoint, this, nodes.size())); + } else if (specifier != Specifier.ALL && nodes.size() > 1) { + AbstractInsnNode specified = nodes.get(specifier == Specifier.FIRST ? 0 : nodes.size() - 1); + this.addTargetNode(method, targetNodes, injectionPoint, specified); + } else { for (AbstractInsnNode insn : nodes) { - Integer key = method.instructions.indexOf(insn); - TargetNode targetNode = targetNodes.get(key); - if (targetNode == null) { - targetNode = new TargetNode(insn); - targetNodes.put(key, targetNode); - } - targetNode.nominators.add(injectionPoint); + this.addTargetNode(method, targetNodes, injectionPoint, insn); } } } @@ -323,6 +329,16 @@ public abstract class Injector { return targetNodes.values(); } + protected void addTargetNode(MethodNode method, Map targetNodes, InjectionPoint injectionPoint, AbstractInsnNode insn) { + Integer key = method.instructions.indexOf(insn); + TargetNode targetNode = targetNodes.get(key); + if (targetNode == null) { + targetNode = new TargetNode(insn); + targetNodes.put(key, targetNode); + } + targetNode.nominators.add(injectionPoint); + } + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget, Collection nodes) { return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes); 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 9347f3a7..f0e55166 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 @@ -27,13 +27,15 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.HashMap; import java.util.Map; +import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.AnnotationNode; 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.selectors.TargetSelectors.SelectedMethod; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.util.Annotations; @@ -59,9 +61,9 @@ public class InjectorTarget { private final Target target; /** - * Selector which selected this method + * Selected method identified by the target selector */ - private final ITargetSelector selector; + private final SelectedMethod selectedMethod; /** * Name of the mixin which merged the target, if any @@ -79,10 +81,10 @@ public class InjectorTarget { * @param context owner * @param target target */ - public InjectorTarget(ISliceContext context, Target target, ITargetSelector selector) { + public InjectorTarget(ISliceContext context, Target target, SelectedMethod selectedMethod) { this.context = context; this.target = target; - this.selector = selector; + this.selectedMethod = selectedMethod; AnnotationNode merged = Annotations.getVisible(target.method, MixinMerged.class); this.mergedBy = Annotations.getValue(merged, "mixin"); @@ -94,6 +96,28 @@ public class InjectorTarget { return this.target.toString(); } + /** + * Add an injection node to this target if it does not already exist, + * returns the existing node if it exists + * + * @param node Instruction node to add + * @return wrapper for the specified node + */ + public InjectionNode addInjectionNode(AbstractInsnNode node) { + return this.target.addInjectionNode(node); + } + + /** + * Get an injection node from this collection if it already exists, returns + * null if the node is not tracked + * + * @param node instruction node + * @return wrapper node or null if not tracked + */ + public InjectionNode getInjectionNode(AbstractInsnNode node) { + return this.target.getInjectionNode(node); + } + /** * Get the target reference */ @@ -111,8 +135,8 @@ public class InjectorTarget { /** * Get the selector which selected this target */ - public ITargetSelector getSelector() { - return this.selector; + public SelectedMethod getSelectedMethod() { + return this.selectedMethod; } /** 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 79891e95..58201c05 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 @@ -37,7 +37,7 @@ import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; 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.InjectionPoint.Specifier; import org.spongepowered.asm.mixin.injection.Slice; import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; @@ -325,6 +325,11 @@ public final class MethodSlice { * Descriptive name of the slice, used in exceptions */ private final String name; + + /** + * Success counts for from and to injection points + */ + private int successCountFrom, successCountTo; /** * ctor @@ -361,8 +366,8 @@ public final class MethodSlice { */ 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)"); + int start = this.find(method, this.from, 0, 0, "from"); + int end = this.find(method, this.to, max, start, "to"); if (start > end) { throw new InvalidSliceException(this.owner, String.format("%s is negative size. Range(%d -> %d)", this.describe(), start, end)); @@ -389,32 +394,53 @@ public final class MethodSlice { * @param defaultValue Value to return if injection point is null (open * ended) * @param failValue Value to use if query fails - * @param description Description for error message + * @param argument The name of the argument ("from" or "to") for debug msgs * @return matching insn index */ - private int find(MethodNode method, InjectionPoint injectionPoint, int defaultValue, int failValue, String description) { + private int find(MethodNode method, InjectionPoint injectionPoint, int defaultValue, int failValue, String argument) { if (injectionPoint == null) { return defaultValue; } + String description = String.format("%s(%s)", this.name, argument); Deque nodes = new LinkedList(); 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) { + Specifier specifier = injectionPoint.getSpecifier(Specifier.FIRST); + if (specifier == Specifier.ALL) { + throw new InvalidSliceException(this.owner, String.format("ALL is not a valid specifier for slice %s", this.describe(description))); + } + if (nodes.size() != 1 && specifier == Specifier.ONE) { throw new InvalidSliceException(this.owner, String.format("%s requires 1 result but found %d", this.describe(description), nodes.size())); } if (!result) { - if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) { - MethodSlice.logger.warn("{} did not match any instructions", this.describe(description)); - } return failValue; } - return method.instructions.indexOf(select == Selector.FIRST ? nodes.getFirst() : nodes.getLast()); + if ("from".equals(argument)) { + this.successCountFrom++; + } else { + this.successCountTo++; + } + + return method.instructions.indexOf(specifier == Specifier.FIRST ? nodes.getFirst() : nodes.getLast()); } - + + /** + * Perform post-injection debugging and validation tasks + */ + public void postInject() { + if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) { + if (this.from != null && this.successCountFrom == 0) { + MethodSlice.logger.warn("{} did not match any instructions", this.describe(this.name + "(from)")); + } + if (this.to != null && this.successCountTo == 0) { + MethodSlice.logger.warn("{} did not match any instructions", this.describe(this.name + "(to)")); + } + } + } + /* (non-Javadoc) * @see java.lang.Object#toString() */ 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 fb9979aa..0789b762 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 @@ -82,6 +82,16 @@ public final class MethodSlices { return this.slices.get(id); } + /** + * Called to do post-injection validation/debug logging for slices + */ + public void postInject() { + for (MethodSlice slice : this.slices.values()) { + slice.postInject(); + } + } + + /* (non-Javadoc) * @see java.lang.Object#toString() */ 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 3a5b5fc7..bf996cba 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 @@ -37,6 +37,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; import org.spongepowered.asm.mixin.injection.points.BeforeNew; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; @@ -252,8 +253,8 @@ public class RedirectInjector extends InvokeInjector { } @Override - protected void addTargetNode(Target target, List myNodes, AbstractInsnNode insn, Set nominators) { - InjectionNode node = target.getInjectionNode(insn); + protected void addTargetNode(InjectorTarget injectorTarget, List myNodes, AbstractInsnNode insn, Set nominators) { + InjectionNode node = injectorTarget.getInjectionNode(insn); ConstructorRedirectData ctorData = null; int fuzz = BeforeFieldAccess.ARRAY_SEARCH_FUZZ_DEFAULT; int opcode = 0; @@ -289,7 +290,7 @@ public class RedirectInjector extends InvokeInjector { } } - InjectionNode targetNode = target.addInjectionNode(insn); + InjectionNode targetNode = injectorTarget.addInjectionNode(insn); targetNode.decorate(Meta.KEY, this.meta); targetNode.decorate(RedirectInjector.KEY_NOMINATORS, nominators); if (insn instanceof TypeInsnNode && insn.getOpcode() == Opcodes.NEW) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java index 05d47943..8772344c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java @@ -61,8 +61,10 @@ public final class ArgsClassGenerator implements IClassGenerator { public static final String ARGS_REF = ArgsClassGenerator.ARGS_NAME.replace('.', '/'); public static final String GETTER_PREFIX = "$"; + + public static final String SYNTHETIC_PACKAGE = Constants.SYNTHETIC_PACKAGE + ".args"; - private static final String CLASS_NAME_BASE = Constants.SYNTHETIC_PACKAGE + ".args.Args$"; + private static final String CLASS_NAME_BASE = ArgsClassGenerator.SYNTHETIC_PACKAGE + ".Args$"; private static final String OBJECT = "java/lang/Object"; private static final String OBJECT_ARRAY = "[L" + ArgsClassGenerator.OBJECT + ";"; 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 e8030562..bbad13ed 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 @@ -147,7 +147,7 @@ public class BeforeConstant extends InjectionPoint { private final boolean log; public BeforeConstant(IMixinContext context, AnnotationNode node, String returnType) { - super(Annotations.getValue(node, "slice", ""), Selector.DEFAULT, null); + super(Annotations.getValue(node, "slice", ""), Specifier.DEFAULT, null); Boolean empty = Annotations.getValue(node, "nullValue", (Boolean)null); this.ordinal = Annotations.getValue(node, "ordinal", Integer.valueOf(-1)); 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 763bfee4..78583e40 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 @@ -83,5 +83,11 @@ public interface ISelectorContext { * not return null! */ public abstract String remap(String reference); + + /** + * Get a human-readable description of the annotation on the method for use + * in error messages + */ + public abstract String getElementDescription(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelectors.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelectors.java new file mode 100644 index 00000000..b46ee143 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelectors.java @@ -0,0 +1,375 @@ +/* + * 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.Collection; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; +import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.struct.TargetNotSupportedException; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo; +import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; + +public class TargetSelectors implements Iterable { + + /** + * Selected target method, paired with the selector which identified it + */ + public static class SelectedMethod { + + /** + * The parent target of this target. If this target is a lambda then + * this will be the selector for the enclosing method. Parent is null + * for the outermost method. + */ + private final SelectedMethod parent; + + /** + * The target selector which selected this target + */ + private final ITargetSelector selector; + + /** + * The selected target method + */ + private final MethodNode method; + + SelectedMethod(SelectedMethod parent, ITargetSelector selector, MethodNode method) { + this.parent = parent; + this.selector = selector; + this.method = method; + } + + SelectedMethod(ITargetSelector selector, MethodNode method) { + this(null, selector, method); + } + + @Override + public String toString() { + return this.method.name + this.method.desc; + } + + public SelectedMethod getParent() { + return this.parent; + } + + public ITargetSelector next() { + return this.selector.next(); + } + + public MethodNode getMethod() { + return this.method; + } + + } + + /** + * The selector context for these selectors, for example the injector which + * is running the selectors + */ + private final ISelectorContext context; + + /** + * The target class node within which targets can be resolved + */ + private final ClassNode targetClassNode; + + /** + * The mixin + */ + private final IMixinContext mixin; + + /** + * Annotated method, as MethodNode at runtime, or IAnnotatedElement during + * compile + */ + private final Object method; + + /** + * Whether the annotated method is static + */ + private final boolean isStatic; + + /** + * Root selectors + */ + private final Set selectors = new LinkedHashSet(); + + /** + * Selected targets + */ + private final List targets = new ArrayList(); + + private boolean doPermissivePass; + + public TargetSelectors(ISelectorContext context, ClassNode classNode) { + this.context = context; + this.targetClassNode = classNode; + this.mixin = context.getMixin(); + this.method = context.getMethod(); + this.isStatic = this.method instanceof MethodNode && Bytecode.isStatic((MethodNode)this.method); + } + + public void parse(Set selectors) { + // Validate and attach the parsed selectors + for (ITargetSelector selector : selectors) { + try { + this.addSelector(selector.validate().attach(this.context)); + } catch (InvalidMemberDescriptorException ex) { + throw new InvalidInjectionException(this.context, String.format("%s, has invalid target descriptor: %s. %s", + this.context.getElementDescription(), ex.getMessage(), this.mixin.getReferenceMapper().getStatus())); + } catch (TargetNotSupportedException ex) { + throw new InvalidInjectionException(this.context, String.format("%s specifies a target class '%s', which is not supported", + this.context.getElementDescription(), ex.getMessage())); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionException(this.context, String.format("%s is decorated with an invalid selector: %s", + this.context.getElementDescription(), ex.getMessage())); + } + } + } + + public TargetSelectors addSelector(ITargetSelector selector) { + this.selectors.add(selector); + return this; + } + + public int size() { + return this.targets.size(); + } + + public void clear() { + this.targets.clear(); + } + + @Override + public Iterator iterator() { + return this.targets.iterator(); + } + + public void remove(SelectedMethod target) { + this.targets.remove(target); + } + + public boolean isPermissivePassEnabled() { + return this.doPermissivePass; + } + + public TargetSelectors setPermissivePass(boolean enabled) { + this.doPermissivePass = enabled; + return this; + } + + /** + * Find methods in the target class which match the parsed selectors + */ + public void find() { + this.findRootTargets(); + // this.findNestedTargets(); + } + + /** + * Evaluate the root selectors parsed from this injector, find the root + * targets and store them in the {@link #targets} collection. + */ + private void findRootTargets() { + int passes = this.doPermissivePass ? 2 : 1; + + for (ITargetSelector selector : this.selectors) { + selector = selector.configure(Configure.SELECT_MEMBER); + + int matchCount = 0; + int maxCount = selector.getMaxMatchCount(); + + // Second pass ignores descriptor + ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); + int selectorPasses = (permissiveSelector == selector) ? 1 : passes; + + scan: for (int pass = 0; pass < selectorPasses && matchCount < 1; pass++) { + ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector; + for (MethodNode target : this.targetClassNode.methods) { + if (passSelector.match(ElementNode.of(this.targetClassNode, target)).isExactMatch()) { + matchCount++; + + 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(new SelectedMethod(passSelector, target)); + } + + if (matchCount >= maxCount) { + break scan; + } + } + } + } + + if (matchCount < selector.getMinMatchCount()) { + throw new InvalidInjectionException(this.context, new SelectorConstraintException(selector, String.format( + "Injection validation failed: %s for %s did not match the required number of targets (required=%d, matched=%d). %s%s", + selector, this.context.getElementDescription(), selector.getMinMatchCount(), matchCount, + this.mixin.getReferenceMapper().getStatus(), AnnotatedMethodInfo.getDynamicInfo(this.method)))); + } + } + } + + /** + * For each root target, resolve the nested targets from the target + * descriptor + */ + protected void findNestedTargets() { + boolean recursed = false; + do { + recursed = false; + for (ListIterator iter = this.targets.listIterator(); iter.hasNext();) { + SelectedMethod target = iter.next(); + ITargetSelector next = target.next(); + if (next == null) { + continue; + } + + recursed = true; + Result result = TargetSelector.run(next, ElementNode.dynamicInsnList(target.getMethod().instructions)); + iter.remove(); + for (ElementNode candidate : result.candidates) { + if (candidate.getInsn().getOpcode() != Opcodes.INVOKEDYNAMIC) { + continue; + } + + if (!candidate.getOwner().equals(this.mixin.getTargetClassRef())) { + throw new InvalidInjectionException(this.context, String.format( + "%s, failed to select into child. Cannot select foreign method: %s. %s", + this.context.getElementDescription(), candidate, this.mixin.getReferenceMapper().getStatus())); + } + + MethodNode method = this.findMethod(candidate); + if (method == null) { + throw new InvalidInjectionException(this.context, String.format( + "%s, failed to select into child. %s%s was not found in the target class.", + this.context.getElementDescription(), candidate.getName(), candidate.getDesc())); + } + + iter.add(new SelectedMethod(target, next, method)); + } + } + } + while (recursed); + } + + private void checkTarget(MethodNode target) { + AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class); + if (merged == null) { + return; + } + + if (Annotations.getVisible(target, Final.class) != null) { + throw new InvalidInjectionException(this.context, String.format("%s cannot inject into @Final method %s::%s%s merged by %s", this, + this.mixin.getTargetClassName(), target.name, target.desc, Annotations.getValue(merged, "mixin"))); + } + } + + /** + * Finds a method in the target class + * + * @return Target method matching searchFor, or null if not found + */ + private MethodNode findMethod(ElementNode searchFor) { + for (MethodNode target : this.targetClassNode.methods) { + if (target.name.equals(searchFor.getSyntheticName()) && target.desc.equals(searchFor.getDesc())) { + return target; + } + } + return null; + } + + /** + * Post-search validation that some targets were found, we can fail-fast if + * no targets were actually identified or if the specified limits are + * exceeded. + * + * @param expectedCallbackCount Number of callbacks specified by expect + * @param requiredCallbackCount Number of callbacks specified by require + */ + public void validate(int expectedCallbackCount, int requiredCallbackCount) { + int targetCount = this.targets.size(); + if (targetCount > 0) { + return; + } + + if ((this.mixin.getOption(Option.DEBUG_INJECTORS) && expectedCallbackCount > 0)) { + throw new InvalidInjectionException(this.context, + String.format("Injection validation failed: %s could not find any targets matching %s in %s. %s%s", + this.context.getElementDescription(), TargetSelectors.namesOf(this.selectors), this.mixin.getTargetClassRef(), + this.mixin.getReferenceMapper().getStatus(), AnnotatedMethodInfo.getDynamicInfo(this.method))); + } else if (requiredCallbackCount > 0) { + throw new InvalidInjectionException(this.context, + String.format("Critical injection failure: %s could not find any targets matching %s in %s. %s%s", + this.context.getElementDescription(), TargetSelectors.namesOf(this.selectors), this.mixin.getTargetClassRef(), + this.mixin.getReferenceMapper().getStatus(), AnnotatedMethodInfo.getDynamicInfo(this.method))); + } + } + + /** + * Print the names of the specified members as a human-readable list + * + * @param selectors members to print + * @return human-readable list of member names + */ + private static String namesOf(Collection selectors) { + int index = 0, count = selectors.size(); + StringBuilder sb = new StringBuilder(); + for (ITargetSelector selector : selectors) { + if (index > 0) { + if (index == (count - 1)) { + sb.append(" or "); + } else { + sb.append(", "); + } + } + sb.append('\'').append(selector.toString()).append('\''); + index++; + } + return sb.toString(); + } + +} 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 1a6f6f60..49e4ea4e 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 @@ -73,11 +73,21 @@ public final class DescriptorResolver { * Selector context */ private final ISelectorContext context; - + + /** + * True if this is a debug descriptor + */ + private final boolean debug; + Descriptor(Set searched, IAnnotationHandle desc, ISelectorContext context) { + this(searched, desc, context, false); + } + + Descriptor(Set searched, IAnnotationHandle desc, ISelectorContext context, boolean debug) { this.searched = searched; this.desc = desc; this.context = context; + this.debug = debug; } /** @@ -88,6 +98,15 @@ public final class DescriptorResolver { return this.desc != null; } + /** + * True if this is a debugging descriptor and shouldn't be treated as + * fully resolved + */ + @Override + public boolean isDebug() { + return this.debug; + } + /** * Get information about the resolution of this descriptor, for * inclusion in error messages when isResolved is false @@ -276,11 +295,13 @@ public final class DescriptorResolver { * @return Resolution result */ public static IResolvedDescriptor resolve(String id, ISelectorContext context) { + boolean debug = false; IResolverObserver observer = new ResolverObserverBasic(); if (!Strings.isNullOrEmpty(id)) { if (DescriptorResolver.PRINT_ID.equals(id)) { observer = new ResolverObserverDebug(context); id = ""; + debug = true; } else { observer.visit(id, "", ""); } @@ -288,7 +309,7 @@ public final class DescriptorResolver { IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true)); observer.postResolve(); - return new Descriptor(observer.getSearched(), desc, context); + return new Descriptor(observer.getSearched(), desc, context, debug); } /** 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 a1315850..f3df6190 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 @@ -177,7 +177,7 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec private final int index; Next(int index, IResolvedDescriptor next) { - super(null, null, next.getOwner(), next.getName(), next.getArgs(), next.getReturnType(), next.getMatches(), null); + super(null, null, next.getOwner(), next.getName(), next.getArgs(), next.getReturnType(), next.getMatches(), null, next.isDebug()); this.index = index; } @@ -239,25 +239,30 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec */ private final List next; + /** + * True if matching is disabled for this selector + */ + private final boolean disabled; + private DynamicSelectorDesc(IResolvedDescriptor desc) { this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches(), - desc.getNext()); + desc.getNext(), desc.isDebug()); } private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) { - this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier, desc.next); + this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier, desc.next, desc.disabled); } private DynamicSelectorDesc(DynamicSelectorDesc desc, Type owner) { - this(desc.parseException, desc.id, owner, desc.name, desc.args, desc.returnType, desc.matches, desc.next); + this(desc.parseException, desc.id, owner, desc.name, desc.args, desc.returnType, desc.matches, desc.next, desc.disabled); } private DynamicSelectorDesc(InvalidSelectorException ex) { - this(ex, null, null, null, null, null, Quantifier.NONE, null); + this(ex, null, null, null, null, null, Quantifier.NONE, null, true); } protected DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches, - List then) { + List next, boolean disabled) { this.parseException = ex; this.id = id; @@ -267,7 +272,8 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec this.returnType = returnType; this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; this.matches = matches; - this.next = then; + this.next = next; + this.disabled = disabled; } /** @@ -281,7 +287,7 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec */ public static DynamicSelectorDesc parse(String input, ISelectorContext context) { IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context); - if (!descriptor.isResolved()) { + if (!descriptor.isResolved() && !descriptor.isDebug()) { String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : ""; return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra)); } @@ -297,7 +303,7 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec */ public static DynamicSelectorDesc parse(IAnnotationHandle desc, ISelectorContext context) { IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context); - if (!descriptor.isResolved()) { + if (!descriptor.isResolved() && !descriptor.isDebug()) { return new DynamicSelectorDesc(new InvalidSelectorException("Invalid descriptor")); } return DynamicSelectorDesc.of(descriptor); @@ -494,7 +500,7 @@ public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelec */ @Override public MatchResult match(ElementNode node) { - if (node == null) { + if (node == null || this.disabled) { return MatchResult.NONE; } else if (node.isField()) { return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.returnType.getInternalName()); 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 39a0860f..d4dbc0bd 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 @@ -40,6 +40,12 @@ public interface IResolvedDescriptor { * Get whether the descriptor was successfully resolved */ public abstract boolean isResolved(); + + /** + * Get whether the descriptor is for debugging and shouldn't be used as a + * live descriptor + */ + public abstract boolean isDebug(); /** * Get the resolved descriptor, or null if the descriptor was not resolved 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 bb686fb5..a4ee28be 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 @@ -31,7 +31,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -45,10 +44,9 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.Dynamic; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.extensibility.IActivityContext.IActivity; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.code.ISliceContext; @@ -56,22 +54,21 @@ 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; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelectors; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelectors.SelectedMethod; 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; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.transformer.ActivityStack; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; -import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; @@ -80,7 +77,6 @@ import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.logging.MessageRouter; import com.google.common.base.Joiner; -import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; /** @@ -160,33 +156,6 @@ 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 */ @@ -213,6 +182,11 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC InjectionInfo.register(ModifyVariableInjectionInfo.class); // @ModifyVariable InjectionInfo.register(ModifyConstantInjectionInfo.class); // @ModifyConstant } + + /** + * Activity tracker + */ + protected final ActivityStack activities = new ActivityStack(null); /** * Annotated method is static @@ -220,14 +194,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected final boolean isStatic; /** - * Target selector(s) + * Targets */ - protected final Set selectors = new LinkedHashSet(); - - /** - * Target method(s) - */ - protected final List targets = new ArrayList(); + protected final TargetSelectors targets; /** * Method slice descriptors parsed from the annotation @@ -238,6 +207,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * The key into the annotation which contains the injection points */ protected final String atKey; + + protected final List injectionPointAnnotations = new ArrayList(); /** * Injection points parsed from @@ -311,6 +282,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation, String atKey) { super(mixin, method, annotation); this.isStatic = Bytecode.isStatic(method); + this.targets = new TargetSelectors(this, mixin.getTargetClassNode()); this.slices = MethodSlices.parse(this); this.atKey = atKey; this.readAnnotation(); @@ -323,56 +295,44 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if (this.annotation == null) { return; } - - List injectionPoints = this.readInjectionPoints(); - this.parseRequirements(); - this.parseSelectors(); - this.findTargets(); - this.parseInjectionPoints(injectionPoints); - this.injector = this.parseInjector(this.annotation); - } - 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); - - // 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)); - } - - // Validate and attach the parsed selectors - for (ITargetSelector selector : selectors) { - try { - 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())); - } catch (TargetNotSupportedException ex) { - throw new InvalidInjectionException(this, - String.format("%s annotation on %s specifies a target class '%s', which is not supported", - this.annotationType, this.methodName, ex.getMessage())); - } 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())); - } + this.activities.clear(); + try { + // 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 "permissive" pass without the descriptor if this happens. + this.targets.setPermissivePass(this.mixin.getOption(Option.REFMAP_REMAP)); + + IActivity activity = this.activities.begin("Read Injection Points"); + this.readInjectionPoints(); + activity.next("Parse Requirements"); + this.parseRequirements(); + activity.next("Parse Selectors"); + this.parseSelectors(); + activity.next("Find Targets"); + this.targets.find(); + activity.next("Validate Targets"); + this.targets.validate(this.expectedCallbackCount, this.requiredCallbackCount); + activity.next("Parse Injection Points"); + this.parseInjectionPoints(); + activity.next("Parse Injector"); + this.injector = this.parseInjector(this.annotation); + activity.end(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this.mixin, "Unexpected " + ex.getClass().getSimpleName() + " parsing " + + this.getElementDescription(), ex, this.activities); } } - protected List readInjectionPoints() { + protected void readInjectionPoints() { List ats = Annotations.getValue(this.annotation, this.atKey, false); if (ats == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", - this.annotationType, this.methodName, this.atKey)); + throw new InvalidInjectionException(this, String.format("%s is missing '%s' value(s)", this.getElementDescription(), this.atKey)); } - return ats; - } - - protected void parseInjectionPoints(List ats) { - this.injectionPoints.addAll(InjectionPoint.parse(this, ats)); + this.injectionPointAnnotations.addAll(ats); } protected void parseRequirements() { @@ -396,6 +356,24 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } } + 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); + + // Raise an error if we have no selectors + if (selectors.size() == 0) { + throw new InvalidInjectionException(this, String.format("%s is missing 'method' or 'target' to specify targets", + this.getElementDescription())); + } + + this.targets.parse(selectors); + } + + protected void parseInjectionPoints() { + this.injectionPoints.addAll(InjectionPoint.parse(this, this.injectionPointAnnotations)); + } + // stub protected abstract Injector parseInjector(AnnotationNode injectAnnotation); @@ -413,18 +391,31 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * Discover injection points */ public void prepare() { - this.targetNodes.clear(); - 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) { - 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(); + this.activities.clear(); + try { + this.targetNodes.clear(); + IActivity activity = this.activities.begin("?"); + for (SelectedMethod targetMethod : this.targets) { + activity.next("{ target: %s }", targetMethod); + Target target = this.mixin.getTargetMethod(targetMethod.getMethod()); + InjectorTarget injectorTarget = new InjectorTarget(this, target, targetMethod); + try { + this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); + } catch (SelectorException ex) { + throw new InvalidInjectionException(this, String.format("Injection validation failed: %s: %s. %s%s", + this.getElementDescription(), ex.getMessage(), this.mixin.getReferenceMapper().getStatus(), + AnnotatedMethodInfo.getDynamicInfo(this.method))); + } finally { + injectorTarget.dispose(); + } } + activity.end(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this.mixin, "Unexpecteded " + ex.getClass().getSimpleName() + " preparing " + + this.getElementDescription(), ex, this.activities); } } @@ -457,7 +448,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC String description = this.getDescription(); String refMapStatus = this.mixin.getReferenceMapper().getStatus(); - String extraInfo = this.getDynamicInfo() + this.getMessages(); + String extraInfo = AnnotatedMethodInfo.getDynamicInfo(this.method) + this.getMessages(); if ((this.mixin.getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) { throw new InvalidInjectionException(this, String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. Scanned %d target(s). %s%s", @@ -473,6 +464,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC String.format("Critical injection failure: %s %s%s in %s failed injection check, %d succeeded of %d allowed.%s", description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, extraInfo)); } + + this.slices.postInject(); } /** @@ -577,115 +570,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected String getMessages() { return this.messages != null ? " Messages: { " + Joiner.on(" ").join(this.messages) + "}" : ""; } - - /** - * Find methods in the target class which match the parsed 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 : this.selectors) { - selector = selector.configure(Configure.SELECT_MEMBER); - - int matchCount = 0; - int maxCount = selector.getMaxMatchCount(); - - // Second pass ignores descriptor - ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); - int selectorPasses = (permissiveSelector == selector) ? 1 : passes; - - 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()) { - matchCount++; - - 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(new SelectedTarget(passSelector, target)); - } - - if (matchCount >= maxCount) { - break scan; - } - } - } - } - - 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()))); - } - } - } - - /** - * 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; - } - - 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(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(this.selectors), this.mixin.getTarget(), - this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); - } - } - - protected void checkTarget(MethodNode target) { - AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class); - if (merged == null) { - return; - } - - if (Annotations.getVisible(target, Final.class) != null) { - throw new InvalidInjectionException(this, String.format("%s cannot inject into @Final method %s::%s%s merged by %s", this, - this.classNode.name, target.name, target.desc, Annotations.getValue(merged, "mixin"))); - } - } - - /** - * Get info from a decorating {@link Dynamic} annotation. If the annotation - * is present, a descriptive string suitable for inclusion in an error - * message is returned. If the annotation is not present then an empty - * string is returned. - */ - protected String getDynamicInfo() { - AnnotationNode annotation = Annotations.getInvisible(this.method, Dynamic.class); - String description = Strings.nullToEmpty(Annotations.getValue(annotation)); - Type upstream = Annotations.getValue(annotation, "mixin"); - if (upstream != null) { - description = String.format("{%s} %s", upstream.getClassName(), description).trim(); - } - return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : ""; - } /** * Parse an injector from the specified method (if an injector annotation is @@ -756,29 +640,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC return String.format("%s->@%s::%s%s", mixin.toString(), Annotations.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); } - /** - * Print the names of the specified members as a human-readable list - * - * @param selectors members to print - * @return human-readable list of member names - */ - private static String namesOf(Collection selectors) { - int index = 0, count = selectors.size(); - StringBuilder sb = new StringBuilder(); - for (ITargetSelector selector : selectors) { - if (index > 0) { - if (index == (count - 1)) { - sb.append(" or "); - } else { - sb.append(", "); - } - } - sb.append('\'').append(selector.toString()).append('\''); - index++; - } - 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/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index cb4290a9..b41cdd7c 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 @@ -36,7 +36,7 @@ import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; +import org.spongepowered.asm.mixin.injection.InjectionPoint.Specifier; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; @@ -86,7 +86,7 @@ public class InjectionPointData { /** * Selector parsed from the at argument, only used by slices */ - private final Selector selector; + private final Specifier specifier; /** * Target @@ -131,7 +131,7 @@ public class InjectionPointData { Matcher matcher = InjectionPointData.AT_PATTERN.matcher(at); this.type = InjectionPointData.parseType(matcher, at); - this.selector = InjectionPointData.parseSelector(matcher); + this.specifier = InjectionPointData.parseSpecifier(matcher); } private void parseArgs(List args) { @@ -172,10 +172,10 @@ public class InjectionPointData { } /** - * Get the selector value parsed from the injector + * Get the specifier value parsed from the injector */ - public Selector getSelector() { - return this.selector; + public Specifier getSpecifier() { + return this.specifier; } /** @@ -362,7 +362,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(Specifier.values()))); } /** @@ -380,8 +380,8 @@ public class InjectionPointData { return matcher.matches() ? matcher.group(1) : at; } - private static Selector parseSelector(Matcher matcher) { - return matcher.matches() && matcher.group(3) != null ? Selector.valueOf(matcher.group(3)) : Selector.DEFAULT; + private static Specifier parseSpecifier(Matcher matcher) { + return matcher.matches() && matcher.group(3) != null ? Specifier.valueOf(matcher.group(3)) : Specifier.DEFAULT; } private static int parseInt(String string, int defaultValue) { 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 ad184f18..08f88124 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 @@ -24,8 +24,6 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import java.util.List; - import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; @@ -39,7 +37,6 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; /** * Information about a constant modifier injector @@ -55,21 +52,20 @@ public class ModifyConstantInjectionInfo extends InjectionInfo { } @Override - protected List readInjectionPoints() { - List ats = super.readInjectionPoints(); - if (ats.isEmpty()) { + protected void readInjectionPoints() { + super.readInjectionPoints(); + if (this.injectionPointAnnotations.isEmpty()) { AnnotationNode c = new AnnotationNode(ModifyConstantInjectionInfo.CONSTANT_ANNOTATION_CLASS); c.visit("log", Boolean.TRUE); - ats = ImmutableList.of(c); + this.injectionPointAnnotations.add(c); } - return ats; } @Override - protected void parseInjectionPoints(List ats) { + protected void parseInjectionPoints() { Type returnType = Type.getReturnType(this.method.desc); - for (AnnotationNode at : ats) { + for (AnnotationNode at : this.injectionPointAnnotations) { 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 index 605d0b08..76756c8d 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 @@ -127,5 +127,14 @@ public class SelectorAnnotationContext implements ISelectorContext { public String remap(String reference) { return this.parent.remap(reference); } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getElementDescription() + */ + @Override + public String getElementDescription() { + return String.format("%s in %s", this.selectorAnnotation, this.parent.getElementDescription()); + } } 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 971a8d59..0e042a92 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 @@ -647,7 +647,7 @@ public class Target implements Comparable, Iterable { */ public DelegateInitialiser findDelegateInitNode() { if (!this.isCtor) { - return null; + return DelegateInitialiser.NONE; } if (this.delegateInitialiser == null) { 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 22ed77d1..0ab2e95e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java @@ -56,6 +56,13 @@ public interface IMixinContext { * @return internal class name */ public abstract String getClassRef(); + + /** + * Get the name of the target class for this context + * + * @return target class name + */ + public abstract String getTargetClassName(); /** * Get the internal name of the target class for this context 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 4fb3c7fd..5ac54bb8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -28,17 +28,23 @@ import java.util.Locale; import javax.tools.Diagnostic.Kind; +import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.Dynamic; 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.Annotations; +import org.spongepowered.asm.util.asm.IAnnotatedElement; import org.spongepowered.asm.util.asm.IAnnotationHandle; +import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.logging.MessageRouter; +import com.google.common.base.Strings; + /** * Data bundle for an annotated method in a mixin */ @@ -59,12 +65,33 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { */ protected final AnnotationNode annotation; + /** + * Human-readable annotation type + */ + protected final String annotationType; + + /** + * Original name of the method, if available + */ + protected final String methodName; + public AnnotatedMethodInfo(IMixinContext mixin, MethodNode method, AnnotationNode annotation) { this.context = mixin; this.method = method; this.annotation = annotation; + this.annotationType = this.annotation != null ? "@" + Annotations.getSimpleName(this.annotation) : "Undecorated method"; + this.methodName = MethodNodeEx.getName(method); } + /** + * Get a human-readable description of the annotation on the method for use + * in error messages + */ + @Override + public final String getElementDescription() { + return String.format("%s annotation on %s", this.annotationType, this.methodName); + } + @Override public String remap(String reference) { if (this.context != null) { @@ -160,4 +187,57 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { } } + /** + * Get info from a decorating {@link Dynamic} annotation. If the annotation + * is present, a descriptive string suitable for inclusion in an error + * message is returned. If the annotation is not present then an empty + * string is returned. + * + * @param method method to inspect + */ + public static final String getDynamicInfo(Object method) { + if (method instanceof MethodNode) { + return AnnotatedMethodInfo.getDynamicInfo((MethodNode)method); + } else if (method instanceof IAnnotatedElement) { + return AnnotatedMethodInfo.getDynamicInfo((IAnnotatedElement)method); + } + return ""; + } + + /** + * Get info from a decorating {@link Dynamic} annotation. If the annotation + * is present, a descriptive string suitable for inclusion in an error + * message is returned. If the annotation is not present then an empty + * string is returned. + * + * @param method method to inspect + */ + public static final String getDynamicInfo(MethodNode method) { + return AnnotatedMethodInfo.getDynamicInfo(Annotations.handleOf(Annotations.getInvisible(method, Dynamic.class))); + } + + /** + * Get info from a decorating {@link Dynamic} annotation. If the annotation + * is present, a descriptive string suitable for inclusion in an error + * message is returned. If the annotation is not present then an empty + * string is returned. + * + * @param method method to inspect + */ + public static final String getDynamicInfo(IAnnotatedElement method) { + return AnnotatedMethodInfo.getDynamicInfo(method.getAnnotation(Dynamic.class)); + } + + private static String getDynamicInfo(IAnnotationHandle annotation) { + if (annotation == null) { + return ""; + } + String description = Strings.nullToEmpty(annotation.getValue()); + Type upstream = annotation.getTypeValue("mixin"); + if (upstream != null) { + description = String.format("{%s} %s", upstream.getClassName(), description).trim(); + } + return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : ""; + } + } 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 d509a898..6dcac649 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -29,8 +29,6 @@ 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.Annotations; -import org.spongepowered.asm.util.asm.MethodNodeEx; /** * Information about a special mixin method such as an injector or accessor @@ -38,19 +36,9 @@ import org.spongepowered.asm.util.asm.MethodNodeEx; public class SpecialMethodInfo extends AnnotatedMethodInfo { /** - * Human-readable annotation type - */ - protected final String annotationType; - - /** - * Class + * Target class node */ protected final ClassNode classNode; - - /** - * Original name of the method, if available - */ - protected final String methodName; /** * Mixin data @@ -60,9 +48,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 ? "@" + 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/MixinCoprocessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinCoprocessor.java index 98926464..6f311619 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinCoprocessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinCoprocessor.java @@ -156,8 +156,8 @@ abstract class MixinCoprocessor implements IListener { /** * Perform postprocessing actions on the supplied class. This is called for * all classes. For passthrough classes and classes which are not mixin - * targets this is called immediately after {@link process} is completed for - * all coprocessors. For mixin targets this is called after mixins are + * targets this is called immediately after {@link #process} is completed + * for all coprocessors. For mixin targets this is called after mixins are * applied. * * @param className Name of the target class 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 1f4a91ad..c08ec0d1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -319,6 +319,14 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { public TargetClassContext getTarget() { return this.targetClass; } + + /** + * Get the target class name + */ + @Override + public String getTargetClassName() { + return this.getTarget().getClassName(); + } /** * Get the target class reference