Merge branch 'feature/slice'

This commit is contained in:
Mumfrey committed 2017-01-13 16:05:49 +00:00
commit 87b2e958bb
40 files changed
+1770 -240

No files matched your search

+8 -2
View File
@@ -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'
}
+1 -1
View File
@@ -37,7 +37,7 @@
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
<property name="tokens" value="CLASS_DEF,METHOD_DEF,CTOR_DEF,LITERAL_FOR,LITERAL_WHILE,STATIC_INIT,INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
+1 -1
View File
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
buildVersion=0.6.4
buildVersion=0.6.5
buildType=SNAPSHOT
@@ -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<AnnotationHandle> ats = inject.getAnnotationList("at");
for (AnnotationHandle at : ats) {
this.registerInjectionPoint(method, inject, at, remap, "@At(%s)");
}
List<AnnotationHandle> slices = inject.getAnnotationList("slice");
for (AnnotationHandle slice : slices) {
String id = slice.<String>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) {
@@ -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<ExecutableElement> {
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<String, String> 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().<String>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().<String>getValue("value");
String type = InjectionPointData.parseType(elem.getAt().<String>getValue("value"));
String target = elem.getAt().<String>getValue("target");
int remapped = 0;
if ("NEW".equals(type)) {
remapped += this.remapNewTarget("@At(" + type + ".<target>)", target, elem) ? 1 : 0;
remapped += this.remapNewTarget("@At(" + type + ".args[class])", elem.getAtArg("class"), elem) ? 1 : 0;
this.remapNewTarget(String.format(format, type + ".<target>"), target, elem);
this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem);
} else {
remapped += this.remapReference("@At(" + type + ".<target>)", target, elem) ? 1 : 0;
this.remapReference(String.format(format, type + ".<target>"), 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<String> mappings = new ObfuscationData<String>();
@@ -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<MappingField> 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;
}
@@ -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<ProcessingEnvironment, AnnotatedMixins> instances = new HashMap<ProcessingEnvironment, AnnotatedMixins>();
/**
* 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);
}
/**
@@ -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
*/
@@ -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
@@ -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.<Boolean>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<AnnotationHandle> getAnnotationList(String key) {
List<AnnotationValue> list = this.<List<AnnotationValue>>getValue(key, null);
if (list == null) {
Object val = this.getValue(key, null);
if (val == null) {
return Collections.<AnnotationHandle>emptyList();
}
// Fix for JDT, single values are just returned as a bare AnnotationMirror
if (val instanceof AnnotationMirror) {
return ImmutableList.<AnnotationHandle>of(AnnotationHandle.of((AnnotationMirror)val));
}
@SuppressWarnings("unchecked") List<AnnotationValue> list = (List<AnnotationValue>)val;
List<AnnotationHandle> annotations = new ArrayList<AnnotationHandle>(list.size());
for (AnnotationValue value : list) {
annotations.add(new AnnotationHandle((AnnotationMirror)value.getValue()));
}
return annotations;
return Collections.<AnnotationHandle>unmodifiableList(annotations);
}
protected AnnotationValue getAnnotationValue(String key) {
@@ -0,0 +1,86 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.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 <tt>remap=true</tt> but we don't find
* a mapping for the injector. However it may be the case that remap is true
* because some of the &#064;At's need remapping. This state struct is used to
* log the original error, but supress it if any &#064;At annotations are
* remapped in the process. When {@link #dispatchPendingMessages} is called at
* the end, if no &#064;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 &#064;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);
}
}
}
@@ -62,7 +62,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.6.4";
public static final String VERSION = "0.6.5";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
@@ -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;
}
@@ -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
@@ -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;
/**
* <p>Base class for injection point discovery classes. Each subclass describes
@@ -77,6 +85,100 @@ import com.google.common.collect.ImmutableList;
* <b>stateless</b>.</p>
*/
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.
* <tt>Selectors</tt> can be supplied in {@link At} annotations by including
* a colon (<tt>:</tt>) character followed by the selector type
* (case-sensitive), eg:
*
* <blockquote><pre>&#064;At(value = "INVOKE:LAST", ... )</pre></blockquote>
*/
public enum Selector {
/**
* Use the <em>first</em> instruction from the query result.
*/
FIRST,
/**
* Use the <em>last</em> instruction from the query result.
*/
LAST,
/**
* The query <b>must return exactly one</b> 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.
* <em>For internal use only. Currently {@link #FIRST}</em>
*/
public static final Selector DEFAULT = Selector.FIRST;
}
/**
* Available injection point types
*/
private static Map<String, Class<? extends InjectionPoint>> types = new HashMap<String, Class<? extends InjectionPoint>>();
static {
// Standard Injection Points
InjectionPoint.register(BeforeFieldAccess.class);
InjectionPoint.register(BeforeInvoke.class);
InjectionPoint.register(BeforeNew.class);
InjectionPoint.register(BeforeReturn.class);
InjectionPoint.register(BeforeStringInvoke.class);
InjectionPoint.register(JumpInsnPoint.class);
InjectionPoint.register(MethodHead.class);
InjectionPoint.register(AfterInvoke.class);
InjectionPoint.register(BeforeLoadLocal.class);
InjectionPoint.register(AfterStoreLocal.class);
InjectionPoint.register(BeforeFinalReturn.class);
}
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<InjectionPoint> parse(SpecialMethodInfo info, List<AnnotationNode> 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<InjectionPoint> parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, List<AnnotationNode> ats) {
Builder<InjectionPoint> injectionPoints = ImmutableList.<InjectionPoint>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<String> 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.<String>getAnnotationValue(node, "value");
List<String> args = ASMHelper.<List<String>>getAnnotationValue(node, "args");
String target = ASMHelper.<String>getAnnotationValue(node, "target", "");
String slice = ASMHelper.<String>getAnnotationValue(node, "slice", "");
At.Shift shift = ASMHelper.<At.Shift>getAnnotationValue(node, "shift", At.Shift.class, At.Shift.NONE);
int by = ASMHelper.<Integer>getAnnotationValue(node, "by", Integer.valueOf(0));
int ordinal = ASMHelper.<Integer>getAnnotationValue(node, "ordinal", Integer.valueOf(-1));
@@ -351,7 +521,7 @@ public abstract class InjectionPoint {
args = ImmutableList.<String>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<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, ordinal, opcode);
InjectionPoint point = null;
List<String> args, String target, String slice, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, slice, ordinal, opcode);
Class<? extends InjectionPoint> 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<? extends InjectionPoint> cls = (Class<? extends InjectionPoint>) Class.forName(at);
Constructor<? extends InjectionPoint> 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<? extends InjectionPoint> findClass(MixinTargetContext mixin, InjectionPointData data) {
String type = data.getType();
Class<? extends InjectionPoint> 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<? extends InjectionPoint>)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<? extends InjectionPoint> ipClass) {
Constructor<? extends InjectionPoint> 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<? extends InjectionPoint> type) {
AtCode code = type.<AtCode>getAnnotation(AtCode.class);
if (code == null) {
throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode");
}
Class<? extends InjectionPoint> 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);
}
}
@@ -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} <i>must only</i>
@@ -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} <i>must only</i>
@@ -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} <i>must only</i>
@@ -0,0 +1,175 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
/**
* A <tt>Slice</tt> identifies a section of a method to search for injection
* points.
*
* <p>Using slices provides for a much more expressive way of identifying target
* injection points in a method, which has two advantages:</p>
*
* <ol>
* <li>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.</li>
* <li>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.</li>
* </ol>
*
* <p>Consider the following example:</p>
*
* <blockquote><pre>
* private void foo(Bar bar) {
* bar.update();
* List&lt;Thing&gt; list = bar.getThings();
* for (Thing thing : list) {
* thing.<b>processStuff</b>();
* }
*
* Thing specialThing = bar.getSpecialThing();
* if (specialThing.isReady()) {
* specialThing.<b>processStuff</b>();
* bar.update();
* }
*
* bar.notifyFoo();
* }</pre></blockquote>
*
* <p>Let's assume we are interested in applying a {@link Redirect} to the
* <tt>processStuff()</tt> method call within the <tt>if</tt> block. Using
* <tt>ordinal</tt> we can achieve this as follows:</p>
*
* <blockquote><pre>
* &#064;At(value = "INVOKE", target = "processStuff", ordinal = 1)</pre>
* </blockquote>
*
* <p>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
* <tt>processStuff()</tt> is added:</p>
*
* <blockquote><pre>
* private void foo(Bar bar) {
* bar.update();
* List&lt;Thing&gt; list = bar.getThings();
* for (Thing thing : list) {
* thing.<b>processStuff</b>();
* }
*
* // A new call to processStuff, which now has the ordinal 1
* bar.getActiveThing().<b>processStuff</b>();
*
* Thing specialThing = bar.getSpecialThing();
* if (specialThing.isReady()) {
* specialThing.<b>processStuff</b>();
* bar.update();
* }
*
* bar.notifyFoo();
* }</pre></blockquote>
*
* <p>It's still pretty easy for a human to identify the correct point since the
* original <tt>if</tt> hasn't changed. However the use of ordinals means that
* the injection is now wrong and must be fixed by hand.</p>
*
* <p>We can make the injection point more expressive and reliable by using a
* <tt>Slice</tt>. We know in this example that the call to <tt>processStuff()
* </tt> we want is the one immediately after a call to <tt>isReady()</tt>. We
* can <em>slice</em> the method at the call to <tt>isReady()</tt> and modify
* the injector accordingly:</p>
*
* <blockquote><pre>
* &#064;Inject(
* slice = &#064;Slice(
* from = &#064;At(value = "INVOKE", target = "isReady")
* )
* at = &#064;At(value = "INVOKE", target = "processStuff", ordinal = 0)
* )</pre></blockquote>
*
* <p>The <tt>ordinal</tt> is specified as <tt>0</tt> because the scope of the
* injection point is now the region of the method defined by the <em>slice</em>
* .</p>
*
* <p>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.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Slice {
/**
* The identifier for this slice (if omitted, this slice becomes the <em>
* default slice</em> and applies to all undecorated {@link At} queries.
*
* @return The identifier for this slice
*/
public String id() default "";
/**
* Injection point which specifies the <em>start</em> 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:
*
* <blockquote><pre>&#064;At(value = "INVOKE:LAST", ... )</pre></blockquote>
*
* <p>If <tt>from</tt> is not supplied then {@link #to} must be supplied. It
* is allowed to specify <b>both</b> <tt>from</tt> and <tt>to</tt> as long
* as the points select a region with positive size (eg the insn returned by
* <tt>to</tt> must appear after that selected by <tt>from</tt> in the
* method body).</p>
*
* @return the start point of the slice
*/
public At from() default @At("HEAD");
/**
* Injection point which specifies the <em>end</em> 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:
*
* <blockquote><pre>&#064;At(value = "INVOKE:LAST", ... )</pre></blockquote>
*
* <p>If <tt>to</tt> is not supplied then {@link #from} must be supplied. It
* is allowed to specify <b>both</b> <tt>from</tt> and <tt>to</tt> as long
* as the points select a region with positive size (eg the insn returned by
* <tt>to</tt> must appear <em>after</em> that selected by <tt>from</tt> in
* the method body).</p>
*
* @return the start point of the slice
*/
public At to() default @At("TAIL");
}
@@ -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<InjectionNode> find(Target target, List<InjectionPoint> injectionPoints) {
this.sanityCheck(target, injectionPoints);
public final List<InjectionNode> find(InjectorTarget injectorTarget, List<InjectionPoint> injectionPoints) {
this.sanityCheck(injectorTarget.getTarget(), injectionPoints);
List<InjectionNode> myNodes = new ArrayList<InjectionNode>();
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<TargetNode> findTargetNodes(MethodNode into, List<InjectionPoint> injectionPoints) {
private Collection<TargetNode> findTargetNodes(InjectorTarget injectorTarget, List<InjectionPoint> injectionPoints) {
Map<AbstractInsnNode, TargetNode> targetNodes = new HashMap<AbstractInsnNode, TargetNode>();
// Defensive objects, so that injectionPoint instances can't modify our working copies
ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions);
Collection<AbstractInsnNode> nodes = new ArrayList<AbstractInsnNode>(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();
}
@@ -0,0 +1,122 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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<String, ReadOnlyInsnList> cache = new HashMap<String, ReadOnlyInsnList>();
/**
* 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();
}
}
@@ -0,0 +1,469 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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 <em>view</em> 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.
*
* <p>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.</p>
*/
static class SliceIterator implements ListIterator<AbstractInsnNode> {
/**
* The underlying ListIterator returned by the parent list
*/
private final ListIterator<AbstractInsnNode> iter;
/**
* Brackets
*/
private int start, end;
/**
* Virtual index, used to keep track of bounds
*/
private int index;
public SliceIterator(ListIterator<AbstractInsnNode> 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<AbstractInsnNode> iterator() {
return this.iterator(0);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList
* #iterator(int)
*/
@Override
public ListIterator<AbstractInsnNode> 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 <em>declared</em> 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<AbstractInsnNode> nodes = new LinkedList<AbstractInsnNode>();
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.<String>getAnnotationValue(node, "id");
AnnotationNode from = ASMHelper.<AnnotationNode>getAnnotationValue(node, "from");
AnnotationNode to = ASMHelper.<AnnotationNode>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);
}
}
@@ -0,0 +1,124 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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<String, MethodSlice> slices = new HashMap<String, MethodSlice>(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<AnnotationNode> sliceNodes = new ArrayList<AnnotationNode>();
Object sliceValue = ASMHelper.getAnnotationValue(annotation, "slice");
if (sliceValue instanceof List) {
sliceNodes.addAll((List<AnnotationNode>)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;
}
}
@@ -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();
}
}
@@ -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;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
@@ -69,13 +68,11 @@ import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
* <p><b>Important Note:</b> Unlike other standard injection points, this class
* matches the insn immediately <b>after</b> the matching point.</p>
*/
@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);
}
}
@@ -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;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
@@ -72,6 +72,7 @@ import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
* &#064;At("LOAD")</pre>
* </blockquote>
*/
@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;
}
@@ -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.</p>
*/
@AtCode("INVOKE_ASSIGN")
public class AfterInvoke extends BeforeInvoke {
@SuppressWarnings("hiding")
public static final String CODE = "INVOKE_ASSIGN";
public AfterInvoke(InjectionPointData data) {
super(data);
}
@@ -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.</p>
*/
@AtCode("FIELD")
public class BeforeFieldAccess extends BeforeInvoke {
@SuppressWarnings("hiding")
public static final String CODE = "FIELD";
private final int opcode;
public BeforeFieldAccess(InjectionPointData data) {
@@ -0,0 +1,92 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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;
/**
* <p>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.</p>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;At(value = "TAIL")</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("TAIL")</pre>
* </blockquote>
*/
@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<AbstractInsnNode> 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<AbstractInsnNode> 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;
}
}
@@ -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.</p>
*/
@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);
@@ -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.</p>
*/
@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());
@@ -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;
* &#064;At("RETURN")</pre>
* </blockquote>
*/
@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();
}
@@ -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.</p>
*/
@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";
/**
@@ -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.</p>
*/
@AtCode("JUMP")
public class JumpInsnPoint extends InjectionPoint {
public static final String CODE = "JUMP";
private final int opCode;
private final int ordinal;
@@ -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;
* &#064;At("HEAD")</pre>
* </blockquote>
*/
@AtCode("HEAD")
public class MethodHead extends InjectionPoint {
public static final String CODE = "HEAD";
public MethodHead(InjectionPointData data) {
super(data);
}
@Override
@@ -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);
}
}
@@ -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<MethodNode> targets = new ArrayDeque<MethodNode>();
/**
* 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<AnnotationNode> 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
*
@@ -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<String> 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<String> 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);
}
}
@@ -0,0 +1,62 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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);
}
}
@@ -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();
}
}
@@ -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<? extends Annotation>... 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<? extends Annotation>... annotationClasses) {
return ASMHelper.getSingleAnnotation(method.invisibleAnnotations, annotationClasses);
}
@@ -512,7 +522,7 @@ public class ASMHelper {
return null;
}
private static AnnotationNode getSingleAnnotation(List<AnnotationNode> annotations, Class<? extends Annotation>... annotationClasses) {
private static AnnotationNode getSingleAnnotation(List<AnnotationNode> annotations, Class<? extends Annotation>[] annotationClasses) {
List<AnnotationNode> nodes = new ArrayList<AnnotationNode>();
for (Class<? extends Annotation> annotationClass : annotationClasses) {
AnnotationNode annotation = ASMHelper.getAnnotation(annotations, Type.getDescriptor(annotationClass));