diff --git a/build.gradle b/build.gradle index 13fd7694..1ef29a31 100644 --- a/build.gradle +++ b/build.gradle @@ -161,8 +161,12 @@ dependencies { fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' compile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' - compile 'net.minecraft:launchwrapper:1.11' - agentCompile 'net.minecraft:launchwrapper:1.11' + compile('net.minecraft:launchwrapper:1.11') { + exclude module: 'lwjgl' + } + agentCompile('net.minecraft:launchwrapper:1.11') { + exclude module: 'lwjgl' + } // asm bridge compile 'org.ow2.asm:asm-commons:5.0.3' @@ -262,6 +266,8 @@ shadowJar { include(dependency('commons-io:commons-io')) include(dependency('net.minecraftforge.srg2source:Srg2Source')) include(dependency('net.sf.jopt-simple:jopt-simple')) + include(dependency('org.apache.logging.log4j:log4j-core')) + include(dependency('org.apache.logging.log4j:log4j-api')) } classifier = 'processor' } diff --git a/checkstyle.xml b/checkstyle.xml index 206877ad..74525cb5 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -37,7 +37,7 @@ - + diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index d8314c18..f727506c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -52,7 +52,7 @@ import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider; import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.TypeHandle; -import org.spongepowered.tools.obfuscation.struct.Message; +import org.spongepowered.tools.obfuscation.struct.InjectorRemap; /** * Information about a mixin stored during processing @@ -331,12 +331,32 @@ class AnnotatedMixin { this.shadows.registerShadow(this.shadows.new AnnotatedElementShadowMethod(method, shadow, shouldRemap)); } - public Message registerInjector(ExecutableElement method, AnnotationHandle inject, boolean shouldRemap) { - return this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, shouldRemap)); + public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) { + this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, remap)); + + List ats = inject.getAnnotationList("at"); + for (AnnotationHandle at : ats) { + this.registerInjectionPoint(method, inject, at, remap, "@At(%s)"); + } + + List slices = inject.getAnnotationList("slice"); + for (AnnotationHandle slice : slices) { + String id = slice.getValue("id", ""); + + AnnotationHandle from = slice.getAnnotation("from"); + if (from != null) { + this.registerInjectionPoint(method, inject, from, remap, "@Slice[" + id + "](from=@At(%s))"); + } + + AnnotationHandle to = slice.getAnnotation("to"); + if (to != null) { + this.registerInjectionPoint(method, inject, to, remap, "@Slice[" + id + "](to=@At(%s))"); + } + } } - public int registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at) { - return this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at)); + public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap remap, String format) { + this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at, remap), format); } public void registerAccessor(ExecutableElement element, AnnotationHandle accessor) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index e9a3d164..4c0fe8d5 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -27,9 +27,13 @@ package org.spongepowered.tools.obfuscation; import java.util.HashMap; import java.util.Map; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; +import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; @@ -37,9 +41,10 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.Constants; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor.CompilerEnvironment; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.TypeHandle; -import org.spongepowered.tools.obfuscation.struct.Message; +import org.spongepowered.tools.obfuscation.struct.InjectorRemap; /** * A module for {@link AnnotatedMixin} whic handles injectors @@ -51,15 +56,19 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler */ static class AnnotatedElementInjector extends AnnotatedElement { - private final boolean shouldRemap; + private final InjectorRemap state; - public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { + public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, InjectorRemap shouldRemap) { super(element, annotation); - this.shouldRemap = shouldRemap; + this.state = shouldRemap; } public boolean shouldRemap() { - return this.shouldRemap; + return this.state.shouldRemap(); + } + + public void addMessage(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationHandle annotation) { + this.state.addMessage(kind, msg, element, annotation); } @Override @@ -78,9 +87,12 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler private Map args; - public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at) { + private final InjectorRemap state; + + public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap state) { super(element, inject); this.at = at; + this.state = state; } public AnnotationHandle getAt() { @@ -105,13 +117,17 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return this.args.get(key); } + + public void notifyRemapped() { + this.state.notifyRemapped(); + } } AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } - public Message registerInjector(AnnotatedElementInjector elem) { + public void registerInjector(AnnotatedElementInjector elem) { if (this.mixin.isInterface()) { this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", elem.getElement()); } @@ -119,7 +135,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String reference = elem.getAnnotation().getValue("method"); MemberInfo targetMember = MemberInfo.parse(reference); if (targetMember.name == null) { - return null; + return; } try { @@ -133,19 +149,17 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } if (!elem.shouldRemap()) { - return null; + return; } for (TypeHandle target : this.mixin.getTargets()) { - Message message = this.registerInjector(elem, reference, targetMember, target); - if (message != null) { - return message; + if (!this.registerInjector(elem, reference, targetMember, target)) { + break; } } - return null; } - private Message registerInjector(AnnotatedElementInjector elem, String reference, MemberInfo targetMember, TypeHandle target) { + private boolean registerInjector(AnnotatedElementInjector elem, String reference, MemberInfo targetMember, TypeHandle target) { String desc = target.findDescriptor(targetMember); if (desc == null) { Kind error = this.mixin.isMultiTarget() ? Kind.ERROR : Kind.WARNING; @@ -157,7 +171,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } else if (!Constants.CTOR.equals(targetMember.name)) { elem.printMessage(this.ap, error, "Unable to determine signature for " + elem + " target method"); } - return null; + return true; } String targetName = elem + " target " + targetMember.name; @@ -168,7 +182,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler obfData = this.obf.getDataProvider().getRemappedMethod(targetMethod); } else { Kind error = Constants.CTOR.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR; - return new Message(error, "No obfuscation mapping for " + targetName, elem.getElement(), elem.getAnnotation()); + elem.addMessage(error, "No obfuscation mapping for " + targetName, elem.getElement(), elem.getAnnotation()); + return false; } } @@ -184,39 +199,36 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler + ex.getNew() + " previously defined as " + ex.getOld()); } - return null; + return true; } /** * Register a {@link org.spongepowered.asm.mixin.injection.At} annotation * and process the references */ - public int registerInjectionPoint(AnnotatedElementInjectionPoint elem) { + public void registerInjectionPoint(AnnotatedElementInjectionPoint elem, String format) { if (this.mixin.isInterface()) { this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", elem.getElement()); } if (!elem.getAt().getBoolean("remap", true)) { - return 0; + return; } - String type = elem.getAt().getValue("value"); + String type = InjectionPointData.parseType(elem.getAt().getValue("value")); String target = elem.getAt().getValue("target"); - int remapped = 0; 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; + this.remapNewTarget(String.format(format, type + "."), target, elem); + this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem); } else { - remapped += this.remapReference("@At(" + type + ".)", target, elem) ? 1 : 0; + this.remapReference(String.format(format, type + "."), target, elem); } - - return remapped; } - protected final boolean remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) { + protected final void remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) { if (reference == null) { - return false; + return; } MemberInfo member = MemberInfo.parse(reference); @@ -229,7 +241,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (remapped.isEmpty()) { this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), elem.getAnnotation().asMirror()); - return false; + return; } ObfuscationData mappings = new ObfuscationData(); @@ -245,7 +257,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); } - return true; + elem.notifyRemapped(); } protected final boolean remapReference(String subject, String reference, AnnotatedElementInjectionPoint elem) { @@ -253,17 +265,20 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return false; } + // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work + AnnotationMirror errorsOn = (this.ap.getCompilerEnvironment() == CompilerEnvironment.JDT ? elem.getAt() : elem.getAnnotation()).asMirror(); + 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()); + String missing = targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"; + this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorsOn); return false; } try { targetMember.validate(); } catch (InvalidMemberDescriptorException ex) { - this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAnnotation().asMirror()); + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), errorsOn); } try { @@ -271,7 +286,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler 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()); + errorsOn); return false; } this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); @@ -280,7 +295,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler 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()); + errorsOn); return false; } } @@ -290,7 +305,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler // Since references are fully-qualified, it shouldn't be possible for there to be multiple mappings, however // we catch and log the error in case something weird happens in the mapping provider this.ap.printMessage(Kind.ERROR, "Unexpected reference conflict for " + subject + ": " + reference + " -> " - + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), elem.getAnnotation().asMirror()); + + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorsOn); return false; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index b729bd83..44d16811 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -68,7 +68,7 @@ import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.TypeHandle; import org.spongepowered.tools.obfuscation.mirror.TypeHandleSimulated; import org.spongepowered.tools.obfuscation.mirror.TypeReference; -import org.spongepowered.tools.obfuscation.struct.Message; +import org.spongepowered.tools.obfuscation.struct.InjectorRemap; import org.spongepowered.tools.obfuscation.validation.ParentValidator; import org.spongepowered.tools.obfuscation.validation.TargetValidator; @@ -81,28 +81,15 @@ import com.google.common.collect.ImmutableList; class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITypeHandleProvider, IJavadocProvider { private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid"; - - /** - * Detected compiler argument, specifies the behaviour of some operations - * for compatibility purposes. - */ - static enum CompilerEnvironment { - /** - * Default environment - */ - JAVAC, - - /** - * Eclipse - */ - JDT - } /** * Singleton instances for each ProcessingEnvironment */ private static Map instances = new HashMap(); + /** + * Detected compiler environment + */ private final CompilerEnvironment env; /** @@ -219,6 +206,11 @@ class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITyp public ProcessingEnvironment getProcessingEnvironment() { return this.processingEnv; } + + @Override + public CompilerEnvironment getCompilerEnvironment() { + return this.env; + } @Override public Integer getToken(String token) { @@ -444,42 +436,9 @@ class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITyp return; } - boolean remap = this.shouldRemap(mixinClass, inject); - Message errorMessage = mixinClass.registerInjector(method, inject, remap); - int remappedAts = 0; - if (remap) { - Object ats = inject.getValue("at"); - - if (ats instanceof List) { - List annotationList = (List)ats; - for (Object at : annotationList) { - // Fix for JDT - if (at instanceof AnnotationValue) { - at = ((AnnotationValue)at).getValue(); - } - if (at instanceof AnnotationMirror) { - remappedAts += mixinClass.registerInjectionPoint(method, inject, AnnotationHandle.of((AnnotationMirror)at)); - } else { - this.printMessage(Kind.WARNING, "No annotation mirror on " + at.getClass().getName()); - } - } - } else if (ats instanceof AnnotationMirror) { - remappedAts += mixinClass.registerInjectionPoint(method, inject, AnnotationHandle.of((AnnotationMirror)ats)); - } else if (ats instanceof AnnotationValue) { - // Fix for JDT - Object mirror = ((AnnotationValue)ats).getValue(); - if (mirror instanceof AnnotationMirror) { - remappedAts += mixinClass.registerInjectionPoint(method, inject, AnnotationHandle.of((AnnotationMirror)mirror)); - } - } - } - - // The annotation was *not* marked as remap=false and failed so we - // checked for remappable @At annotations, if that failed as well then - // we raise the original error. - if (remappedAts == 0 && errorMessage != null) { - errorMessage.sendTo(this); - } + InjectorRemap remap = new InjectorRemap(this.shouldRemap(mixinClass, inject)); + mixinClass.registerInjector(method, inject, remap); + remap.dispatchPendingMessages(this); } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java index 1abf502f..8bc37660 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java @@ -34,6 +34,29 @@ import org.spongepowered.asm.util.ITokenProvider; */ public interface IMixinAnnotationProcessor extends Messager, IOptionProvider { + /** + * Detected compiler argument, specifies the behaviour of some operations + * for compatibility purposes. + */ + public static enum CompilerEnvironment { + + /** + * Default environment + */ + JAVAC, + + /** + * Eclipse + */ + JDT + + } + + /** + * Get the detected compiler environment + */ + public abstract CompilerEnvironment getCompilerEnvironment(); + /** * Get the underlying processing environment */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java index 403a94a8..4537f090 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java @@ -48,7 +48,7 @@ public interface IMixinValidator { /** * Validate all the things, return false to halt processing of further * validators. Raise compiler errors/warnings directly. - * @param pass TODO + * @param pass current validation pass * @param mixin Mixin being validated * @param annotation Mixin annotation * @param targets Mixin targets diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index ed633770..d1c46348 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -36,6 +36,8 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import com.google.common.collect.ImmutableList; + /** * A wrapper for {@link AnnotationMirror} which provides a more convenient way * to access annotation values. @@ -141,6 +143,25 @@ public class AnnotationHandle { return this.getValue(key, Boolean.valueOf(defaultValue)).booleanValue(); } + /** + * Get an annotation value as an annotation handle + * + * @param key + * @return + */ + public AnnotationHandle getAnnotation(String key) { + Object value = this.getValue(key); + if (value instanceof AnnotationMirror) { + return AnnotationHandle.of((AnnotationMirror)value); + } else if (value instanceof AnnotationValue) { + Object mirror = ((AnnotationValue)value).getValue(); + if (mirror instanceof AnnotationMirror) { + return AnnotationHandle.of((AnnotationMirror)mirror); + } + } + return null; + } + /** * Retrieve the annotation value as a list with values of the specified * type. Returns an empty list if the value is not present or not set. @@ -171,16 +192,22 @@ public class AnnotationHandle { * @return list of annotations */ public List getAnnotationList(String key) { - List list = this.>getValue(key, null); - if (list == null) { + Object val = this.getValue(key, null); + if (val == null) { return Collections.emptyList(); } + // Fix for JDT, single values are just returned as a bare AnnotationMirror + if (val instanceof AnnotationMirror) { + return ImmutableList.of(AnnotationHandle.of((AnnotationMirror)val)); + } + + @SuppressWarnings("unchecked") List list = (List)val; List annotations = new ArrayList(list.size()); for (AnnotationValue value : list) { annotations.add(new AnnotationHandle((AnnotationMirror)value.getValue())); } - return annotations; + return Collections.unmodifiableList(annotations); } protected AnnotationValue getAnnotationValue(String key) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/struct/InjectorRemap.java b/src/ap/java/org/spongepowered/tools/obfuscation/struct/InjectorRemap.java new file mode 100644 index 00000000..82c0291e --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/struct/InjectorRemap.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.tools.obfuscation.struct; + +import javax.annotation.processing.Messager; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic; + +import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; + +/** + * Remap tracking object for injectors. When remapping an injector we will + * generally want to raise an error if remap=true but we don't find + * a mapping for the injector. However it may be the case that remap is true + * because some of the @At's need remapping. This state struct is used to + * log the original error, but supress it if any @At annotations are + * remapped in the process. When {@link #dispatchPendingMessages} is called at + * the end, if no @At's have been remapped then we dispatch the error as + * planned. + */ +public class InjectorRemap { + + /** + * True if remap=true + */ + private final boolean remap; + + /** + * Pending error message (if any) + */ + private Message message; + + /** + * Number of @At annotations which were remapped + */ + private int remappedCount; + + public InjectorRemap(boolean remap) { + this.remap = remap; + } + + public boolean shouldRemap() { + return this.remap; + } + + public void notifyRemapped() { + this.remappedCount++; + this.clearMessage(); + } + + public void addMessage(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationHandle annotation) { + this.message = new Message(kind, msg, element, annotation); + } + + public void clearMessage() { + this.message = null; + } + + public void dispatchPendingMessages(Messager messager) { + if (this.remappedCount == 0 && this.message != null) { + this.message.sendTo(messager); + } + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 824f95e5..8d9f6db7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -77,6 +77,15 @@ public @interface At { */ public String value(); + /** + * For {@link Inject} queries, this specifies the ID of the slice to use for + * this query. For other injector types it is ignored because only one slice + * is supported. + * + * @return + */ + public String slice() default ""; + /** * Shift type for returned opcodes. For example use {@link At.Shift#AFTER * AFTER} with an INVOKE InjectionPoint to move the returned opcodes to @@ -153,5 +162,3 @@ public @interface At { */ public boolean remap() default true; } - - diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index aa7f25a1..72b0bb1b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -63,6 +63,14 @@ public @interface Inject { */ public String method(); + /** + * Array of {@link Slice} annotations which describe the method bisections + * used in the {@link #at} queries for this injector. + * + * @return slices + */ + public Slice[] slice() default {}; + /** * Array of {@link At} annotations which describe the * {@link InjectionPoint}s in the target method. Allows one or more 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 8bec0619..813951d4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -24,24 +24,30 @@ */ package org.spongepowered.asm.mixin.injection; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; -import org.spongepowered.asm.lib.Type; +import org.apache.logging.log4j.LogManager; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; -import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.points.AfterInvoke; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; +import org.spongepowered.asm.mixin.injection.points.BeforeFinalReturn; import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; import org.spongepowered.asm.mixin.injection.points.BeforeNew; import org.spongepowered.asm.mixin.injection.points.BeforeReturn; @@ -50,11 +56,13 @@ import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint; import org.spongepowered.asm.mixin.injection.points.MethodHead; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; /** *

Base class for injection point discovery classes. Each subclass describes @@ -77,6 +85,100 @@ import com.google.common.collect.ImmutableList; * stateless.

*/ public abstract class InjectionPoint { + + /** + * Injection point code for {@link At} annotations to use + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + public @interface AtCode { + + /** + * The string code used to specify the annotated injection point in At + * annotations + */ + public String value(); + + } + + /** + * 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: + * + *
@At(value = "INVOKE:LAST", ... )
+ */ + public enum Selector { + + /** + * Use the first instruction from the query result. + */ + FIRST, + + /** + * Use the last instruction from the query result. + */ + LAST, + + /** + * The query must return exactly one instruction, if it returns + * more than one instruction this should be considered a fail-fast error + * state and a runtime exception will be thrown. + */ + ONE; + + /** + * Default selector type used if no selector is explicitly specified. + * For internal use only. Currently {@link #FIRST} + */ + public static final Selector DEFAULT = Selector.FIRST; + + } + + /** + * Available injection point types + */ + private static Map> types = new HashMap>(); + + static { + // Standard Injection Points + InjectionPoint.register(BeforeFieldAccess.class); + InjectionPoint.register(BeforeInvoke.class); + InjectionPoint.register(BeforeNew.class); + InjectionPoint.register(BeforeReturn.class); + InjectionPoint.register(BeforeStringInvoke.class); + InjectionPoint.register(JumpInsnPoint.class); + InjectionPoint.register(MethodHead.class); + InjectionPoint.register(AfterInvoke.class); + InjectionPoint.register(BeforeLoadLocal.class); + InjectionPoint.register(AfterStoreLocal.class); + InjectionPoint.register(BeforeFinalReturn.class); + } + + private final String slice; + private final Selector selector; + + protected InjectionPoint() { + this("", Selector.DEFAULT); + } + + protected InjectionPoint(InjectionPointData data) { + this(data.getSlice(), data.getSelector()); + } + + public InjectionPoint(String slice, Selector selector) { + this.slice = slice; + this.selector = selector; + } + + public String getSlice() { + return this.slice; + } + + public Selector getSelector() { + return this.selector; + } /** * Find injection points in the supplied insn list @@ -309,6 +411,59 @@ public abstract class InjectionPoint { public static InjectionPoint shift(InjectionPoint point, int count) { return new InjectionPoint.Shift(point, count); } + + /** + * Parse a collection of InjectionPoints from the supplied {@link At} + * annotations + * + * @param info Data for the mixin containing the annotation, used to obtain + * the refmap, amongst other things + * @param ats {@link At} annotations to parse information from + * @return InjectionPoint parsed from the supplied data or null if parsing + * failed + */ + public static List parse(SpecialMethodInfo info, List ats) { + return InjectionPoint.parse(info.getContext(), info.getMethod(), info.getAnnotation(), ats); + } + + /** + * Parse a collection of InjectionPoints from the supplied {@link At} + * annotations + * + * @param mixin Data for the mixin containing the annotation, used to obtain + * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation + * @param ats {@link At} annotations to parse information from + * @return InjectionPoint parsed from the supplied data or null if parsing + * failed + */ + public static List parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, List ats) { + Builder injectionPoints = ImmutableList.builder(); + for (AnnotationNode at : ats) { + InjectionPoint injectionPoint = InjectionPoint.parse(mixin, method, parent, at); + if (injectionPoint != null) { + injectionPoints.add(injectionPoint); + } + } + return injectionPoints.build(); + } + + /** + * Parse an InjectionPoint from the supplied {@link At} annotation + * + * @param mixin Data for the mixin containing the annotation, used to obtain + * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation + * @param at {@link At} annotation to parse information from + * @return InjectionPoint parsed from the supplied data or null if parsing + * failed + */ + public static InjectionPoint parse(SpecialMethodInfo info, At at) { + return InjectionPoint.parse(info.getContext(), info.getMethod(), info.getAnnotation(), at.value(), at.shift(), at.by(), + Arrays.asList(at.args()), at.target(), at.slice(), at.ordinal(), at.opcode()); + } /** * Parse an InjectionPoint from the supplied {@link At} annotation @@ -322,8 +477,22 @@ public abstract class InjectionPoint { * failed */ public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) { - List args = Arrays.asList(at.args()); - return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode()); + return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.slice(), + at.ordinal(), at.opcode()); + } + + /** + * Parse an InjectionPoint from the supplied {@link At} annotation supplied + * as an AnnotationNode instance + * + * @param info Data for the mixin containing the annotation, used to obtain + * the refmap, amongst other things + * @param node {@link At} annotation to parse information from + * @return InjectionPoint parsed from the supplied data or null if parsing + * failed + */ + public static InjectionPoint parse(SpecialMethodInfo info, AnnotationNode node) { + return InjectionPoint.parse(info.getContext(), info.getMethod(), info.getAnnotation(), node); } /** @@ -342,6 +511,7 @@ public abstract class InjectionPoint { String at = ASMHelper.getAnnotationValue(node, "value"); List args = ASMHelper.>getAnnotationValue(node, "args"); String target = ASMHelper.getAnnotationValue(node, "target", ""); + String slice = ASMHelper.getAnnotationValue(node, "slice", ""); At.Shift shift = ASMHelper.getAnnotationValue(node, "shift", At.Shift.class, At.Shift.NONE); int by = ASMHelper.getAnnotationValue(node, "by", Integer.valueOf(0)); int ordinal = ASMHelper.getAnnotationValue(node, "ordinal", Integer.valueOf(-1)); @@ -351,7 +521,7 @@ public abstract class InjectionPoint { args = ImmutableList.of(); } - return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode); + return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, slice, ordinal, opcode); } /** @@ -367,52 +537,59 @@ public abstract class InjectionPoint { * @param by Amount of shift to apply for the BY shift type * @param args Named parameters * @param target Target for supported injection points + * @param slice Slice id for injectors which support multiple slices * @param ordinal Ordinal offset for supported injection points * @param opcode Bytecode opcode for supported injection points * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by, - List args, String target, int ordinal, int opcode) { - InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, ordinal, opcode); - InjectionPoint point = null; + List args, String target, String slice, int ordinal, int opcode) { + InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, slice, ordinal, opcode); + Class ipClass = findClass(mixin, data); + InjectionPoint point = InjectionPoint.create(mixin, data, ipClass); + return InjectionPoint.shift(point, shift, by); + } - if (BeforeFieldAccess.CODE.equals(at)) { - point = new BeforeFieldAccess(data); - } else if (BeforeInvoke.CODE.equals(at)) { - point = new BeforeInvoke(data); - } else if (BeforeNew.CODE.equals(at)) { - point = new BeforeNew(data); - } else if (BeforeReturn.CODE.equals(at)) { - point = new BeforeReturn(data); - } else if (BeforeStringInvoke.CODE.equals(at)) { - point = new BeforeStringInvoke(data); - } else if (JumpInsnPoint.CODE.equals(at)) { - point = new JumpInsnPoint(data); - } else if (MethodHead.CODE.equals(at)) { - point = new MethodHead(data); - } else if (AfterInvoke.CODE.equals(at)) { - point = new AfterInvoke(data); - } else if (BeforeLoadLocal.CODE.equals(at)) { - LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); - point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data); - } else if (AfterStoreLocal.CODE.equals(at)) { - LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); - point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data); - } else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { - try { - @SuppressWarnings("unchecked") Class cls = (Class) Class.forName(at); - Constructor ctor = cls.getDeclaredConstructor(InjectionPointData.class); - ctor.setAccessible(true); - point = ctor.newInstance(data); - } catch (Exception ex) { - throw new InvalidInjectionException(mixin, "The specified class " + at - + " could not be instanced or is not a valid InjectionPoint", ex); + @SuppressWarnings("unchecked") + private static Class findClass(MixinTargetContext mixin, InjectionPointData data) { + String type = data.getType(); + Class ipClass = InjectionPoint.types.get(type); + if (ipClass == null) { + if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { + try { + ipClass = (Class)Class.forName(type); + InjectionPoint.types.put(type, ipClass); + } catch (Exception ex) { + throw new InvalidInjectionException(mixin, data + " could not be loaded or is not a valid InjectionPoint", ex); + } + } else { + throw new InvalidInjectionException(mixin, data + " is not a valid injection point specifier"); } - } else { - throw new InvalidInjectionException(mixin, at + " is not a valid injection point specifier"); + } + return ipClass; + } + + private static InjectionPoint create(MixinTargetContext mixin, InjectionPointData data, Class ipClass) { + Constructor ipCtor = null; + try { + ipCtor = ipClass.getDeclaredConstructor(InjectionPointData.class); + ipCtor.setAccessible(true); + } catch (NoSuchMethodException ex) { + throw new InvalidInjectionException(mixin, ipClass.getName() + " must contain a constructor which accepts an InjectionPointData", ex); } + InjectionPoint point = null; + try { + point = ipCtor.newInstance(data); + } catch (Exception ex) { + throw new InvalidInjectionException(mixin, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex); + } + + return point; + } + + private static InjectionPoint shift(InjectionPoint point, At.Shift shift, int by) { if (point != null) { if (shift == At.Shift.BEFORE) { return InjectionPoint.before(point); @@ -425,4 +602,19 @@ public abstract class InjectionPoint { return point; } + + public static void register(Class type) { + AtCode code = type.getAnnotation(AtCode.class); + if (code == null) { + throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode"); + } + + Class existing = InjectionPoint.types.get(code.value()); + if (existing != null && !existing.equals(type)) { + LogManager.getLogger("mixin").debug("Overriding InjectionPoint {} with {} (previously {})", code.value(), type.getName(), + existing.getName()); + } + + InjectionPoint.types.put(code.value(), type); + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index d976ed9e..1bd38b74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -51,6 +51,14 @@ public @interface ModifyArg { */ public String method(); + /** + * A {@link Slice} annotation which describes the method bisection used in + * the {@link #at} query for this injector. + * + * @return slice + */ + public Slice slice() default @Slice; + /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 6d3c0cd8..3a81138f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -76,6 +76,14 @@ public @interface ModifyVariable { */ public String method(); + /** + * A {@link Slice} annotation which describes the method bisection used in + * the {@link #at} query for this injector. + * + * @return slice + */ + public Slice slice() default @Slice; + /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 411b1853..e36a6d26 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -148,6 +148,14 @@ public @interface Redirect { */ public String method(); + /** + * A {@link Slice} annotation which describes the method bisection used in + * the {@link #at} query for this injector. + * + * @return slice + */ + public Slice slice() default @Slice; + /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java new file mode 100644 index 00000000..102079fc --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java @@ -0,0 +1,175 @@ +/* + * 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 org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; + +/** + * A Slice identifies a section of a method to search for injection + * points. + * + *

Using slices provides for a much more expressive way of identifying target + * injection points in a method, which has two advantages:

+ * + *
    + *
  1. Encoding assumptions about the structure of a method makes it easier to + * detect (and fail-fast) when a method has changed in an unexpected way.
  2. + *
  3. Injection points using slices are less brittle than points specified + * with large ordinals because they allow injection points to be specified + * with reference to characteristics of the method rather than arbitrary + * ordinal values.
  4. + *
+ * + *

Consider the following example:

+ * + *
+ * private void foo(Bar bar) {
+ *     bar.update();
+ *     List<Thing> list = bar.getThings();
+ *     for (Thing thing : list) {
+ *         thing.processStuff();
+ *     }
+ *     
+ *     Thing specialThing = bar.getSpecialThing();
+ *     if (specialThing.isReady()) {
+ *         specialThing.processStuff();
+ *         bar.update();
+ *     }
+ *     
+ *     bar.notifyFoo();
+ * }
+ * + *

Let's assume we are interested in applying a {@link Redirect} to the + * processStuff() method call within the if block. Using + * ordinal we can achieve this as follows:

+ * + *
+ * @At(value = "INVOKE", target = "processStuff", ordinal = 1)
+ *
+ * + *

This will work fine initially. However consider the case that in a future + * version of the target library the method is altered and an additional call to + * processStuff() is added:

+ * + *
+ * private void foo(Bar bar) {
+ *     bar.update();
+ *     List<Thing> list = bar.getThings();
+ *     for (Thing thing : list) {
+ *         thing.processStuff();
+ *     }
+ *     
+ *     // A new call to processStuff, which now has the ordinal 1
+ *     bar.getActiveThing().processStuff();
+ *     
+ *     Thing specialThing = bar.getSpecialThing();
+ *     if (specialThing.isReady()) {
+ *         specialThing.processStuff();
+ *         bar.update();
+ *     }
+ *     
+ *     bar.notifyFoo();
+ * }
+ * + *

It's still pretty easy for a human to identify the correct point since the + * original if hasn't changed. However the use of ordinals means that + * the injection is now wrong and must be fixed by hand.

+ * + *

We can make the injection point more expressive and reliable by using a + * Slice. We know in this example that the call to processStuff() + * we want is the one immediately after a call to isReady(). We + * can slice the method at the call to isReady() and modify + * the injector accordingly:

+ * + *
+ * @Inject(
+ *     slice = @Slice(
+ *         from = @At(value = "INVOKE", target = "isReady")
+ *     )
+ *     at = @At(value = "INVOKE", target = "processStuff", ordinal = 0)
+ * )
+ * + *

The ordinal is specified as 0 because the scope of the + * injection point is now the region of the method defined by the slice + * .

+ * + *

Slices can be specified using a {@link #from} point, a {@link #to} point, + * or both. {@link Inject Callback Injectors} using multiple injection points + * can distinguish different slices using {@link #id} and then specify the slice + * to use in the {@link At#slice} argument.

+ */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Slice { + + /** + * The identifier for this slice (if omitted, this slice becomes the + * default slice and applies to all undecorated {@link At} queries. + * + * @return The identifier for this slice + */ + public String id() default ""; + + /** + * Injection point which specifies the start of the slice region. + * {@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: + * + *
@At(value = "INVOKE:LAST", ... )
+ * + *

If from is not supplied then {@link #to} must be supplied. It + * is allowed to specify both from and to as long + * as the points select a region with positive size (eg the insn returned by + * to must appear after that selected by from in the + * method body).

+ * + * @return the start point of the slice + */ + public At from() default @At("HEAD"); + + /** + * 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: + * + *
@At(value = "INVOKE:LAST", ... )
+ * + *

If to is not supplied then {@link #from} must be supplied. It + * is allowed to specify both from and to as long + * as the points select a region with positive size (eg the insn returned by + * to must appear after that selected by from in + * the method body).

+ * + * @return the start point of the slice + */ + public At to() default @At("TAIL"); + +} 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 257e871d..949d1c09 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 @@ -140,17 +140,17 @@ public abstract class Injector { /** * ... * - * @param target Target method to inject into + * @param injectorTarget Target method to inject into * @param injectionPoints InjectionPoint instances which will identify * target insns in the target method * @return discovered injection points */ - public final List find(Target target, List injectionPoints) { - this.sanityCheck(target, injectionPoints); + public final List find(InjectorTarget injectorTarget, List injectionPoints) { + this.sanityCheck(injectorTarget.getTarget(), injectionPoints); List myNodes = new ArrayList(); - for (TargetNode node : this.findTargetNodes(target.method, injectionPoints)) { - this.addTargetNode(target, myNodes, node.node, node.nominators); + for (TargetNode node : this.findTargetNodes(injectorTarget, injectionPoints)) { + this.addTargetNode(injectorTarget.getTarget(), myNodes, node.node, node.nominators); } return myNodes; } @@ -179,33 +179,31 @@ public abstract class Injector { * Use the supplied InjectionPoints to find target insns in the target * method * - * @param into Target method + * @param target.method Target method * @param injectionPoints List of injection points parsed from At * annotations on the callback method * @return Target insn nodes in the target method */ - private Collection findTargetNodes(MethodNode into, List injectionPoints) { + private Collection findTargetNodes(InjectorTarget injectorTarget, List injectionPoints) { Map targetNodes = new HashMap(); - // Defensive objects, so that injectionPoint instances can't modify our working copies - ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions); Collection nodes = new ArrayList(32); for (InjectionPoint injectionPoint : injectionPoints) { nodes.clear(); - if (this.findTargetNodes(into, injectionPoint, insns, nodes)) { + + if (this.findTargetNodes(injectorTarget.getMethod(), injectionPoint, injectorTarget.getSlice(injectionPoint), nodes)) { for (AbstractInsnNode node : nodes) { - TargetNode target = targetNodes.get(node); - if (target == null) { - target = new TargetNode(node); - targetNodes.put(node, target); + TargetNode targetNode = targetNodes.get(node); + if (targetNode == null) { + targetNode = new TargetNode(node); + targetNodes.put(node, targetNode); } - target.nominators.add(injectionPoint); + targetNode.nominators.add(injectionPoint); } } } - insns.dispose(); return targetNodes.values(); } 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 new file mode 100644 index 00000000..53ce4469 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java @@ -0,0 +1,122 @@ +/* + * 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.code; + +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; + +/** + * Couples {@link MethodSlice method slices} to a {@link Target} for injection + * purposes. + */ +public class InjectorTarget { + + /** + * Owner injector + */ + private final InjectionInfo info; + + /** + * Cache of slices + */ + private final Map cache = new HashMap(); + + /** + * Target method data + */ + private final Target target; + + /** + * ctor + * + * @param info owner + * @param target target + */ + public InjectorTarget(InjectionInfo info, Target target) { + this.info = info; + this.target = target; + } + + /** + * Get the target reference + */ + public Target getTarget() { + return this.target; + } + + /** + * Get the target method + */ + public MethodNode getMethod() { + return this.target.method; + } + + /** + * Get the slice instructions for the specified slice id + * + * @param id slice id + * @return insn slice + */ + public InsnList getSlice(String id) { + ReadOnlyInsnList slice = this.cache.get(id); + if (slice == null) { + MethodSlice sliceInfo = this.info.getSlice(id); + if (sliceInfo != null) { + slice = sliceInfo.getSlice(this.target.method); + } else { + // No slice exists so just wrap the method insns + slice = new ReadOnlyInsnList(this.target.method.instructions); + } + this.cache.put(id, slice); + } + + return slice; + } + + /** + * Get the slice instructions for the specified + * + * @param injectionPoint + * @return + */ + public InsnList getSlice(InjectionPoint injectionPoint) { + return this.getSlice(injectionPoint.getSlice()); + } + + public void dispose() { + for (ReadOnlyInsnList insns : this.cache.values()) { + insns.dispose(); + } + + this.cache.clear(); + } +} + 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 new file mode 100644 index 00000000..50d00b55 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -0,0 +1,469 @@ +/* + * 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.code; + +import java.util.Deque; +import java.util.LinkedList; +import java.util.ListIterator; +import java.util.NoSuchElementException; + +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; +import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; +import org.spongepowered.asm.util.ASMHelper; + +import com.google.common.base.Strings; + +/** + * Stores information about a defined method slice for a particular injector. + */ +public class MethodSlice { + + /** + * A read-only wrapper for an {@link InsnList} which only allows the segment + * identified by {@link #start} and {@link end} to be accessed. In essence + * this class provides a view of the underlying InsnList. + */ + static final class InsnListSlice extends ReadOnlyInsnList { + + /** + * ListIterator for the slice view, wraps an iterator returned by the + * underlying {@link InsnList} and ensures that consumers can only + * traverse the slice. + * + *

Note that this doesn't handle changes in the underlying InsnList + * which occur after instatiation, care should be taken not to modify + * the list via other means whilst this iterator is in use.

+ */ + static class SliceIterator implements ListIterator { + + /** + * The underlying ListIterator returned by the parent list + */ + private final ListIterator iter; + + /** + * Brackets + */ + private int start, end; + + /** + * Virtual index, used to keep track of bounds + */ + private int index; + + public SliceIterator(ListIterator iter, int start, int end, int index) { + this.iter = iter; + this.start = start; + this.end = end; + this.index = index; + } + + /* (non-Javadoc) + * @see java.util.ListIterator#hasNext() + */ + @Override + public boolean hasNext() { + return this.index <= this.end && this.iter.hasNext(); + } + + /* (non-Javadoc) + * @see java.util.ListIterator#next() + */ + @Override + public AbstractInsnNode next() { + if (this.index > this.end) { + throw new NoSuchElementException(); + } + this.index++; + return this.iter.next(); + } + + /* (non-Javadoc) + * @see java.util.ListIterator#hasPrevious() + */ + @Override + public boolean hasPrevious() { + return this.index > this.start ; + } + + /* (non-Javadoc) + * @see java.util.ListIterator#previous() + */ + @Override + public AbstractInsnNode previous() { + if (this.index <= this.start) { + throw new NoSuchElementException(); + } + this.index--; + return this.iter.previous(); + } + + /* (non-Javadoc) + * @see java.util.ListIterator#nextIndex() + */ + @Override + public int nextIndex() { + return this.index - this.start; + } + + /* (non-Javadoc) + * @see java.util.ListIterator#previousIndex() + */ + @Override + public int previousIndex() { + return this.index - this.start - 1; + } + + /* (non-Javadoc) + * @see java.util.ListIterator#remove() + */ + @Override + public void remove() { + throw new UnsupportedOperationException("Cannot remove insn from slice"); + } + + /* (non-Javadoc) + * @see java.util.ListIterator#set(java.lang.Object) + */ + @Override + public void set(AbstractInsnNode e) { + throw new UnsupportedOperationException("Cannot set insn using slice"); + } + + /* (non-Javadoc) + * @see java.util.ListIterator#add(java.lang.Object) + */ + @Override + public void add(AbstractInsnNode e) { + throw new UnsupportedOperationException("Cannot add insn using slice"); + } + } + + /** + * Brackets + */ + private final int start, end; + + protected InsnListSlice(InsnList inner, int start, int end) { + super(inner); + + // Start and end are validated prior to construction + this.start = start; + this.end = end; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #iterator() + */ + @Override + public ListIterator iterator() { + return this.iterator(0); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #iterator(int) + */ + @Override + public ListIterator iterator(int index) { + // Return the bracketed iterator + return new SliceIterator(super.iterator(this.start + index), this.start, this.end, this.start + index); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #toArray() + */ + @Override + public AbstractInsnNode[] toArray() { + AbstractInsnNode[] all = super.toArray(); + AbstractInsnNode[] subset = new AbstractInsnNode[this.size()]; + System.arraycopy(all, this.start, subset, 0, subset.length); + return subset; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #size() + */ + @Override + public int size() { + return (this.end - this.start) + 1; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #getFirst() + */ + @Override + public AbstractInsnNode getFirst() { + return super.get(this.start); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #getLast() + */ + @Override + public AbstractInsnNode getLast() { + return super.get(this.end); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #get(int) + */ + @Override + public AbstractInsnNode get(int index) { + return super.get(this.start + index); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList + * #contains(org.spongepowered.asm.lib.tree.AbstractInsnNode) + */ + @Override + public boolean contains(AbstractInsnNode insn) { + for (AbstractInsnNode node : this.toArray()) { + if (node == insn) { + return true; + } + } + return false; + } + + /** + * Returns the index of the specified instruction in the slice, use + * {@link #realIndexOf} to determine the index of the instruction in the + * underlying InsnList. + * + * @param insn Instruction to inspect + * @return instruction's index in the list + */ + @Override + public int indexOf(AbstractInsnNode insn) { + int index = super.indexOf(insn); + return index >= this.start && index <= this.end ? index - this.start : -1; + } + + /** + * Returns the index of the instruction in the underlying InsnLis + * + * @param insn Instruction to inspect + * @return instruction's index in the list + */ + public int realIndexOf(AbstractInsnNode insn) { + return super.indexOf(insn); + } + + } + + /** + * Owner of this slice + */ + private final InjectionInfo info; + + /** + * Slice ID as declared, slice ID in the parent {@link MethodSlices} + * collection may be different + */ + private final String id; + + /** + * Injection point which defines the start of this slice (inclusive), may be + * null as long as {@link #to} is not null + */ + private final InjectionPoint from; + + /** + * Injection point which defines the end of this slice (inclusive), may be + * null as long as {@link #from} is not null + */ + private final InjectionPoint to; + + /** + * Descriptive name of the slice, used in exceptions + */ + private final String name; + + /** + * ctor + * + * @param info owner + * @param id declared id + * @param from start point, may be null as long as {@link #to} is not null + * @param to end point, may be null as long as {@link #from} is not null + */ + private MethodSlice(InjectionInfo info, String id, InjectionPoint from, InjectionPoint to) { + if (from == null && to == null) { + throw new InvalidSliceException(info, String.format("%s is redundant. No 'from' or 'to' value specified", this)); + } + + this.info = info; + this.id = Strings.nullToEmpty(id); + this.from = from; + this.to = to; + this.name = MethodSlice.getSliceName(id); + } + + /** + * Get the declared id of this slice + */ + public String getId() { + return this.id; + } + + /** + * Get a sliced insn list based on the parameters specified in this slice + * + * @param method method to slice + * @return read only slice + */ + public ReadOnlyInsnList getSlice(MethodNode method) { + int max = method.instructions.size() - 1; + int start = this.find(method, this.from, 0, this.name + "(from)"); + int end = this.find(method, this.to, max, this.name + "(to)"); + + if (start > end) { + throw new InvalidSliceException(this.info, String.format("%s is negative size. Range(%d -> %d)", this.describe(), start, end)); + } + + if (start < 0 || end < 0 || start > max || end > max) { + throw new InjectionError("Unexpected critical error in " + this + ": out of bounds start=" + start + " end=" + end + " lim=" + max); + } + + if (start == 0 && end == max) { + return new ReadOnlyInsnList(method.instructions); + } + + return new InsnListSlice(method.instructions, start, end); + } + + /** + * Runs the specified injection point as a query on the method and returns + * the index of the instruction matching the query. Returns the default + * value if the query returns zero results. + * + * @param method Method to query + * @param injectionPoint Query to run + * @param defaultValue Value to return if query fails + * @param description Description for error message + * @return matching insn index + */ + private int find(MethodNode method, InjectionPoint injectionPoint, int defaultValue, String description) { + if (injectionPoint == null) { + return defaultValue; + } + + Deque nodes = new LinkedList(); + ReadOnlyInsnList insns = new ReadOnlyInsnList(method.instructions); + boolean result = injectionPoint.find(method.desc, insns, nodes); + Selector select = injectionPoint.getSelector(); + if (nodes.size() != 1 && select == Selector.ONE) { + throw new InvalidSliceException(this.info, String.format("%s requires 1 result but found %d", this.describe(description), nodes.size())); + } + + if (!result) { + return defaultValue; + } + + return method.instructions.indexOf(select == Selector.FIRST ? nodes.getFirst() : nodes.getLast()); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return this.describe(); + } + + private String describe() { + return this.describe(this.name); + } + + private String describe(String description) { + return MethodSlice.describeSlice(description, this.info); + } + + private static String describeSlice(String description, InjectionInfo info) { + String annotation = ASMHelper.getSimpleName(info.getAnnotation()); + MethodNode method = info.getMethod(); + return String.format("%s->%s(%s)::%s%s", info.getContext(), annotation, description, method.name, method.desc); + } + + private static String getSliceName(String id) { + return String.format("@Slice[%s]", Strings.nullToEmpty(id)); + } + + /** + * Parses the supplied annotation into a MethodSlice + * + * @param info Owner injection info + * @param slice Annotation to parse + * @return parsed MethodSlice + */ + public static MethodSlice parse(InjectionInfo info, Slice slice) { + String id = slice.id(); + + At from = slice.from(); + At to = slice.to(); + + InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null; + InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null; + + return new MethodSlice(info, id, fromPoint, toPoint); + } + + /** + * Parses the supplied annotation into a MethodSlice + * + * @param info Owner injection info + * @param node Annotation to parse + * @return parsed MethodSlice + */ + public static MethodSlice parse(InjectionInfo info, AnnotationNode node) { + String id = ASMHelper.getAnnotationValue(node, "id"); + + AnnotationNode from = ASMHelper.getAnnotationValue(node, "from"); + AnnotationNode to = ASMHelper.getAnnotationValue(node, "to"); + + InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null; + InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null; + + return new MethodSlice(info, id, fromPoint, toPoint); + } + +} 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 new file mode 100644 index 00000000..3f7c5666 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java @@ -0,0 +1,124 @@ +/* + * 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.code; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Represents a collection of {@link MethodSlice}s, mapped by ID. Stored ids may + * be different to declared slice ids because they are mapped by the underlying + * injector. Some injectors only support a single slice. + */ +public class MethodSlices { + + /** + * Injector which owns this collection of slices + */ + private final InjectionInfo info; + + /** + * Available slices + */ + private final Map slices = new HashMap(4); + + /** + * ctor + * + * @param info owner + */ + private MethodSlices(InjectionInfo info) { + this.info = info; + } + + /** + * Add a slice to this collection + * + * @param slice + */ + private void add(MethodSlice slice) { + String id = this.info.getSliceId(slice.getId()); + if (this.slices.containsKey(id)) { + throw new InvalidSliceException(this.info, slice + " has a duplicate id, '" + id + "' was already defined"); + } + this.slices.put(id, slice); + } + + /** + * Fetch the slice with the specified id, returns null if no slice with the + * supplied id is available + * + * @param id slice id + * @return matching slice or null + */ + public MethodSlice get(String id) { + return this.slices.get(id); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("MethodSlices%s", this.slices.keySet()); + } + + /** + * Parse a collection of slices from the supplied injector + * + * @param info owning injector + * @return parsed slice collection + */ + @SuppressWarnings("unchecked") + public static MethodSlices parse(InjectionInfo info) { + MethodSlices slices = new MethodSlices(info); + + AnnotationNode annotation = info.getAnnotation(); + if (annotation != null) { + List sliceNodes = new ArrayList(); + Object sliceValue = ASMHelper.getAnnotationValue(annotation, "slice"); + if (sliceValue instanceof List) { + sliceNodes.addAll((List)sliceValue); + } else if (sliceValue instanceof AnnotationNode) { + sliceNodes.add((AnnotationNode)sliceValue); + } + + for (AnnotationNode node : sliceNodes) { + MethodSlice slice = MethodSlice.parse(info, node); + slices.add(slice); + } + } + + return slices; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java index 35d6b865..8f595b9c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java @@ -54,7 +54,7 @@ class ReadOnlyInsnList extends InsnList { * org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void set(AbstractInsnNode location, AbstractInsnNode insn) { + public final void set(AbstractInsnNode location, AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -65,7 +65,7 @@ class ReadOnlyInsnList extends InsnList { * #add(org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void add(AbstractInsnNode insn) { + public final void add(AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -75,7 +75,7 @@ class ReadOnlyInsnList extends InsnList { * @see org.objectweb.asm.tree.InsnList#add(org.objectweb.asm.tree.InsnList) */ @Override - public void add(InsnList insns) { + public final void add(InsnList insns) { throw new UnsupportedOperationException(); } @@ -86,7 +86,7 @@ class ReadOnlyInsnList extends InsnList { * #insert(org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void insert(AbstractInsnNode insn) { + public final void insert(AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -97,7 +97,7 @@ class ReadOnlyInsnList extends InsnList { * #insert(org.objectweb.asm.tree.InsnList) */ @Override - public void insert(InsnList insns) { + public final void insert(InsnList insns) { throw new UnsupportedOperationException(); } @@ -109,7 +109,7 @@ class ReadOnlyInsnList extends InsnList { * org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void insert(AbstractInsnNode location, AbstractInsnNode insn) { + public final void insert(AbstractInsnNode location, AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -121,7 +121,7 @@ class ReadOnlyInsnList extends InsnList { * org.objectweb.asm.tree.InsnList) */ @Override - public void insert(AbstractInsnNode location, InsnList insns) { + public final void insert(AbstractInsnNode location, InsnList insns) { throw new UnsupportedOperationException(); } @@ -133,7 +133,7 @@ class ReadOnlyInsnList extends InsnList { * org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void insertBefore(AbstractInsnNode location, AbstractInsnNode insn) { + public final void insertBefore(AbstractInsnNode location, AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -145,7 +145,7 @@ class ReadOnlyInsnList extends InsnList { * org.objectweb.asm.tree.InsnList) */ @Override - public void insertBefore(AbstractInsnNode location, InsnList insns) { + public final void insertBefore(AbstractInsnNode location, InsnList insns) { throw new UnsupportedOperationException(); } @@ -156,7 +156,7 @@ class ReadOnlyInsnList extends InsnList { * #remove(org.objectweb.asm.tree.AbstractInsnNode) */ @Override - public void remove(AbstractInsnNode insn) { + public final void remove(AbstractInsnNode insn) { throw new UnsupportedOperationException(); } @@ -258,7 +258,7 @@ class ReadOnlyInsnList extends InsnList { * @see org.objectweb.asm.tree.InsnList#resetLabels() */ @Override - public void resetLabels() { + public final void resetLabels() { this.insnList.resetLabels(); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java index 2ed1e3e0..bf9d60dd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java @@ -25,10 +25,9 @@ package org.spongepowered.asm.mixin.injection.modify; import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; -import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** *

This injection point is a companion for the {@link ModifyVariable} @@ -69,13 +68,11 @@ import org.spongepowered.asm.mixin.transformer.MixinTargetContext; *

Important Note: Unlike other standard injection points, this class * matches the insn immediately after the matching point.

*/ +@AtCode("STORE") public class AfterStoreLocal extends BeforeLoadLocal { - @SuppressWarnings("hiding") - public static final String CODE = "STORE"; - - public AfterStoreLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator local, InjectionPointData data) { - super(mixin, returnType, local, data, Opcodes.ISTORE, true); + public AfterStoreLocal(InjectionPointData data) { + super(data, Opcodes.ISTORE, true); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java index b00c0e6f..b8dd7005 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java @@ -31,11 +31,11 @@ import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.Target; -import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** *

This injection point is a companion for the {@link ModifyVariable} @@ -72,6 +72,7 @@ import org.spongepowered.asm.mixin.transformer.MixinTargetContext; * @At("LOAD") * */ +@AtCode("LOAD") public class BeforeLoadLocal extends ContextualInjectionPoint { /** @@ -142,8 +143,6 @@ public class BeforeLoadLocal extends ContextualInjectionPoint { } - public static final String CODE = "LOAD"; - /** * Return type of the handler, also the type of the local variable we're * interested in @@ -170,17 +169,17 @@ public class BeforeLoadLocal extends ContextualInjectionPoint { * opcode, used by {@link AfterStoreLocal}. */ private boolean opcodeAfter; - - public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) { - this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false); + + protected BeforeLoadLocal(InjectionPointData data) { + this(data, Opcodes.ILOAD, false); } - protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data, + protected BeforeLoadLocal(InjectionPointData data, int opcode, boolean opcodeAfter) { - super(mixin); - this.returnType = returnType; - this.discriminator = discriminator; - this.opcode = data.getOpcode(returnType.getOpcode(opcode)); + super(data.getMixin()); + this.returnType = data.getReturnType(); + this.discriminator = data.getLocalVariableDiscriminator(); + this.opcode = data.getOpcode(this.returnType.getOpcode(opcode)); this.ordinal = data.getOrdinal(); this.opcodeAfter = opcodeAfter; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java index fc975c18..d0be8d46 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java @@ -33,6 +33,7 @@ import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -65,11 +66,9 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to * adjust the matched opcode as necessary.

*/ +@AtCode("INVOKE_ASSIGN") public class AfterInvoke extends BeforeInvoke { - @SuppressWarnings("hiding") - public static final String CODE = "INVOKE_ASSIGN"; - public AfterInvoke(InjectionPointData data) { super(data); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java index 8bd74162..46e2a2c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java @@ -27,6 +27,7 @@ package org.spongepowered.asm.mixin.injection.points; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -62,11 +63,9 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} * specifier to adjust the matched opcode as necessary.

*/ +@AtCode("FIELD") public class BeforeFieldAccess extends BeforeInvoke { - @SuppressWarnings("hiding") - public static final String CODE = "FIELD"; - private final int opcode; public BeforeFieldAccess(InjectionPointData data) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java new file mode 100644 index 00000000..1701d8b8 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java @@ -0,0 +1,92 @@ +/* + * 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.points; + +import java.util.Collection; +import java.util.ListIterator; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + *

This injection point searches for the last RETURN opcode in the target + * method and returns it. Note that the last RETURN opcode may not correspond to + * the notional "bottom" of a method in the original Java source, since + * conditional expressions can cause the bytecode emitted to differ + * significantly in order from the original Java.

+ * + *

Example:

+ *
+ *   @At(value = "TAIL")
+ *
+ *

Note that if value is the only parameter specified, it can be + * omitted:

+ *
+ *   @At("TAIL")
+ *
+ */ +@AtCode("TAIL") +public class BeforeFinalReturn extends InjectionPoint { + + private final MixinTargetContext mixin; + + public BeforeFinalReturn(InjectionPointData data) { + super(data); + + this.mixin = data.getMixin(); + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + AbstractInsnNode ret = null; + + // RETURN opcode varies based on return type, thus we calculate what opcode we're actually looking for by inspecting the target method + int returnOpcode = Type.getReturnType(desc).getOpcode(Opcodes.IRETURN); + + ListIterator iter = insns.iterator(); + while (iter.hasNext()) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof InsnNode && insn.getOpcode() == returnOpcode) { + ret = insn; + } + } + + // WAT? + if (ret == null) { + throw new InvalidInjectionException(this.mixin, "TAIL could not locate a valid RETURN in the target method!"); + } + + nodes.add(ret); + return true; + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index 9249322d..96286cb6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -33,6 +33,7 @@ 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.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; @@ -64,10 +65,9 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} * specifier to adjust the matched opcode as necessary.

*/ +@AtCode("INVOKE") public class BeforeInvoke extends InjectionPoint { - public static final String CODE = "INVOKE"; - protected final MemberInfo target; /** @@ -87,6 +87,8 @@ public class BeforeInvoke extends InjectionPoint { protected final String className; public BeforeInvoke(InjectionPointData data) { + super(data); + this.target = data.getTarget(); this.ordinal = data.getOrdinal(); this.logging = data.get("log", false); 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 80fa779f..2d440f18 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 @@ -35,6 +35,7 @@ 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.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.util.Constants; @@ -84,10 +85,9 @@ import com.google.common.base.Strings; * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} * specifier to adjust the matched opcode as necessary.

*/ +@AtCode("NEW") public class BeforeNew extends InjectionPoint { - public static final String CODE = "NEW"; - /** * Class name we're looking for */ @@ -104,6 +104,8 @@ public class BeforeNew extends InjectionPoint { private final int ordinal; public BeforeNew(InjectionPointData data) { + super(data); + this.ordinal = data.getOrdinal(); String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); MemberInfo member = MemberInfo.parseAndValidate(target, data.getMixin()); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java index 45b40ee8..a704ec1c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java @@ -33,6 +33,7 @@ import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -64,16 +65,17 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * @At("RETURN") * */ +@AtCode("RETURN") public class BeforeReturn extends InjectionPoint { - public static final String CODE = "RETURN"; - /** * Ordinal of the target insn */ private final int ordinal; public BeforeReturn(InjectionPointData data) { + super(data); + this.ordinal = data.getOrdinal(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java index 373ee5f0..c47145de 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java @@ -29,6 +29,7 @@ import java.util.Collection; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.LdcInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; @@ -80,11 +81,9 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} * specifier to adjust the matched opcode as necessary.

*/ +@AtCode("INVOKE_STRING") public class BeforeStringInvoke extends BeforeInvoke { - @SuppressWarnings("hiding") - public static final String CODE = "INVOKE_STRING"; - private static final String STRING_VOID_SIG = "(Ljava/lang/String;)V"; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java index 9873d301..233b475e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java @@ -32,6 +32,7 @@ import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.JumpInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -66,10 +67,9 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} * specifier to adjust the matched opcode as necessary.

*/ +@AtCode("JUMP") public class JumpInsnPoint extends InjectionPoint { - public static final String CODE = "JUMP"; - private final int opCode; private final int ordinal; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java index 84aad081..5761cd18 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java @@ -29,6 +29,7 @@ import java.util.Collection; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -42,11 +43,11 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; * @At("HEAD") * */ +@AtCode("HEAD") public class MethodHead extends InjectionPoint { - public static final String CODE = "HEAD"; - public MethodHead(InjectionPointData data) { + super(data); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java index a6689266..62d8188c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java @@ -33,6 +33,8 @@ import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; +import com.google.common.base.Strings; + /** * Information about a callback to inject, usually specified by {@link Inject} */ @@ -51,4 +53,9 @@ public class CallbackInjectionInfo extends InjectionInfo { return new CallbackInjector(this, cancellable, locals, identifier); } + @Override + public String getSliceId(String id) { + return Strings.nullToEmpty(id); + } + } 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 dbc3a3ac..d9ae7680 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 @@ -49,6 +49,9 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; 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.code.MethodSlice; +import org.spongepowered.asm.mixin.injection.code.MethodSlices; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; @@ -73,6 +76,11 @@ public abstract class InjectionInfo extends SpecialMethodInfo { */ protected final Deque targets = new ArrayDeque(); + /** + * Method slice descriptors parsed from the annotation + */ + protected final MethodSlices slices; + /** * Injection points parsed from * {@link org.spongepowered.asm.mixin.injection.At} annotations @@ -124,6 +132,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo { protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { super(mixin, method, annotation); this.isStatic = ASMHelper.methodIsStatic(method); + this.slices = MethodSlices.parse(this); this.readAnnotation(); } @@ -176,12 +185,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo { } protected void parseInjectionPoints(List ats) { - for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at); - if (injectionPoint != null) { - this.injectionPoints.add(injectionPoint); - } - } + this.injectionPoints.addAll(InjectionPoint.parse(this.mixin, this.method, this.annotation, ats)); } protected void parseRequirements() { @@ -220,7 +224,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo { this.targetNodes.clear(); for (MethodNode targetMethod : this.targets) { Target target = this.mixin.getTargetMethod(targetMethod); - this.targetNodes.put(target, this.injector.find(target, this.injectionPoints)); + InjectorTarget injectorTarget = new InjectorTarget(this, target); + this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); + injectorTarget.dispose(); } } @@ -276,6 +282,25 @@ public abstract class InjectionInfo extends SpecialMethodInfo { return this.targets; } + /** + * Get the slice descriptors + */ + public MethodSlice getSlice(String id) { + return this.slices.get(this.getSliceId(id)); + } + + /** + * Return the mapped slice id for the specified ID. Injectors which only + * support use of a single slice will always return the default id (an empty + * string) + * + * @param id + * @return mapped id + */ + public String getSliceId(String id) { + return ""; + } + /** * Get the injected callback count * 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 8566b356..27008a36 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 @@ -27,18 +27,31 @@ package org.spongepowered.asm.mixin.injection.struct; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import com.google.common.base.Joiner; +import com.google.common.base.Strings; + /** * Data read from an {@link org.spongepowered.asm.mixin.injection.At} annotation * and passed into an InjectionPoint ctor */ public class InjectionPointData { + + /** + * Regex for recognising at declarations + */ + private static final Pattern AT_PATTERN = InjectionPointData.createPattern(); /** * K/V arguments parsed from the "args" node in the {@link At} annotation @@ -53,23 +66,38 @@ public class InjectionPointData { /** * Injector callback */ - private MethodNode method; + private final MethodNode method; /** * Parent annotation */ - private AnnotationNode parent; + private final AnnotationNode parent; /** * At arg */ - private String at; + private final String at; + + /** + * Parsed from the at argument, the injector type (shortcode or class name) + */ + private final String type; + + /** + * Selector parsed from the at argument, only used by slices + */ + private final Selector selector; /** * Target */ private final String target; + /** + * Slice id specified in the annotation, only used by slices + */ + private final String slice; + /** * Ordinal */ @@ -79,14 +107,15 @@ public class InjectionPointData { * Opcode */ private final int opcode; - + public InjectionPointData(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, List args, String target, - int ordinal, int opcode) { + String slice, int ordinal, int opcode) { this.mixin = mixin; this.method = method; this.parent = parent; this.at = at; this.target = target; + this.slice = Strings.nullToEmpty(slice); this.ordinal = Math.max(-1, ordinal); this.opcode = opcode; @@ -95,6 +124,10 @@ public class InjectionPointData { this.args.put("target", target); this.args.put("ordinal", String.valueOf(ordinal)); this.args.put("opcode", String.valueOf(opcode)); + + Matcher matcher = InjectionPointData.AT_PATTERN.matcher(at); + this.type = InjectionPointData.parseType(matcher, at); + this.selector = InjectionPointData.parseSelector(matcher); } private void parseArgs(List args) { @@ -112,6 +145,18 @@ public class InjectionPointData { } } } + + public String getAt() { + return this.at; + } + + public String getType() { + return this.type; + } + + public Selector getSelector() { + return this.selector; + } public MixinTargetContext getMixin() { return this.mixin; @@ -124,6 +169,18 @@ public class InjectionPointData { public AnnotationNode getParent() { return this.parent; } + + public String getSlice() { + return this.slice; + } + + public Type getReturnType() { + return Type.getReturnType(this.method.desc); + } + + public LocalVariableDiscriminator getLocalVariableDiscriminator() { + return LocalVariableDiscriminator.parse(this.parent); + } public String get(String key, String defaultValue) { String value = this.args.get(key); @@ -192,4 +249,27 @@ public class InjectionPointData { } return defaultOpcode; } + + @Override + public String toString() { + return this.type; + } + + private static Pattern createPattern() { + return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values()))); + } + + private static String parseType(Matcher matcher, String at) { + return matcher.matches() ? matcher.group(1) : at; + } + + private static Selector parseSelector(Matcher matcher) { + return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT; + } + + public static String parseType(String at) { + Matcher matcher = InjectionPointData.AT_PATTERN.matcher(at); + return InjectionPointData.parseType(matcher, at); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java new file mode 100644 index 00000000..f27885e9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.throwables; + +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; + +/** + * Thrown when an injector slice fails a state check, for example if a slice + * selector fails or a slice is negative in size + */ +public class InvalidSliceException extends InvalidInjectionException { + + private static final long serialVersionUID = 1L; + + public InvalidSliceException(IReferenceMapperContext context, String message) { + super(context, message); + } + + public InvalidSliceException(InjectionInfo info, String message) { + super(info, message); + } + + public InvalidSliceException(IReferenceMapperContext context, Throwable cause) { + super(context, cause); + } + + public InvalidSliceException(InjectionInfo info, Throwable cause) { + super(info, cause); + } + + public InvalidSliceException(IReferenceMapperContext context, String message, Throwable cause) { + super(context, message, cause); + } + + public InvalidSliceException(InjectionInfo info, String message, Throwable cause) { + super(info, message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java index 7f521ec1..bc5a9b4e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java @@ -49,28 +49,27 @@ public class MixinClassWriter extends ClassWriter { */ @Override protected String getCommonSuperClass(final String type1, final String type2) { - ClassInfo c = ClassInfo.forName(type1); - ClassInfo d = ClassInfo.forName(type2); + ClassInfo t1 = ClassInfo.forName(type1); + ClassInfo t2 = ClassInfo.forName(type2); - if (c.hasSuperClass(d)) { + if (t1.hasSuperClass(t2)) { return type2; } - if (d.hasSuperClass(c)) { + if (t2.hasSuperClass(t1)) { return type1; } - if (c.isInterface() || d.isInterface()) { + if (t1.isInterface() || t2.isInterface()) { return MixinClassWriter.JAVA_LANG_OBJECT; } do { - c = c.getSuperClass(); - if (c == null) { + t1 = t1.getSuperClass(); + if (t1 == null) { return MixinClassWriter.JAVA_LANG_OBJECT; } - - } while (!d.hasSuperClass(c)); + } while (!t2.hasSuperClass(t1)); - return c.getName(); + return t1.getName(); } } diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java index 5b0ac8f2..1f852b7c 100644 --- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java +++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java @@ -200,10 +200,12 @@ public class ASMHelper { } public static String getNodeDescriptionForDebug(AbstractInsnNode node) { - String out = String.format("%-14s ", node.getClass().getSimpleName().replace("Node", "")); if (node instanceof LabelNode) { - out += String.format("[%s]", ((LabelNode)node).getLabel()); - } else if (node instanceof JumpInsnNode) { + return String.format("[%s]", ((LabelNode)node).getLabel()); + } + + String out = String.format(" %-14s ", node.getClass().getSimpleName().replace("Node", "")); + if (node instanceof JumpInsnNode) { out += String.format("[%s] [%s]", ASMHelper.getOpcodeName(node), ((JumpInsnNode)node).label.getLabel()); } else if (node instanceof VarInsnNode) { out += String.format("[%s] %d", ASMHelper.getOpcodeName(node), ((VarInsnNode)node).var); @@ -215,11 +217,13 @@ public class ASMHelper { out += String.format("[%s] %s %s %s", ASMHelper.getOpcodeName(node), fld.owner, fld.name, fld.desc); } else if (node instanceof LineNumberNode) { LineNumberNode ln = (LineNumberNode)node; - out += String.format("LINE=%d LABEL=[%s]", ln.line, ln.start.getLabel()); + out += String.format("LINE=[%d] LABEL=[%s]", ln.line, ln.start.getLabel()); } else if (node instanceof LdcInsnNode) { out += (((LdcInsnNode)node).cst); } else if (node instanceof IntInsnNode) { out += (((IntInsnNode)node).operand); + } else if (node instanceof FrameNode) { + out += String.format("[%s] ", ASMHelper.getOpcodeName(((FrameNode)node).type, "H_INVOKEINTERFACE", -1)); } else { out += String.format("[%s] ", ASMHelper.getOpcodeName(node)); } @@ -247,12 +251,16 @@ public class ASMHelper { * the {@link Opcodes} class have the same value as opcodes */ public static String getOpcodeName(int opcode) { - if (opcode > 0) { + return ASMHelper.getOpcodeName(opcode, "UNINITIALIZED_THIS", 1); + } + + private static String getOpcodeName(int opcode, String start, int min) { + if (opcode >= min) { boolean found = false; try { for (java.lang.reflect.Field f : Opcodes.class.getDeclaredFields()) { - if (!found && f.getName() != "UNINITIALIZED_THIS") { + if (!found && !f.getName().equals(start)) { continue; } found = true; @@ -265,7 +273,7 @@ public class ASMHelper { } } - return opcode >= 0 ? String.valueOf(opcode) : ""; + return opcode >= 0 ? String.valueOf(opcode) : "UNKNOWN"; } /** @@ -406,6 +414,7 @@ public class ASMHelper { * @param annotationClasses Types of annotation to search for * @return the annotation, or null if not present */ + @SuppressWarnings("unchecked") public static AnnotationNode getSingleVisibleAnnotation(MethodNode method, Class... annotationClasses) { return ASMHelper.getSingleAnnotation(method.visibleAnnotations, annotationClasses); } @@ -418,6 +427,7 @@ public class ASMHelper { * @param annotationClasses Types of annotation to search for * @return the annotation, or null if not present */ + @SuppressWarnings("unchecked") public static AnnotationNode getSingleInvisibleAnnotation(MethodNode method, Class... annotationClasses) { return ASMHelper.getSingleAnnotation(method.invisibleAnnotations, annotationClasses); } @@ -512,7 +522,7 @@ public class ASMHelper { return null; } - private static AnnotationNode getSingleAnnotation(List annotations, Class... annotationClasses) { + private static AnnotationNode getSingleAnnotation(List annotations, Class[] annotationClasses) { List nodes = new ArrayList(); for (Class annotationClass : annotationClasses) { AnnotationNode annotation = ASMHelper.getAnnotation(annotations, Type.getDescriptor(annotationClass));