diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index bfc2e522..88418387 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -42,15 +42,17 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.tools.MirrorUtils; -import org.spongepowered.tools.obfuscation.AnnotatedMixinInjectorHandler.AnnotatedElementInjectionPoint; -import org.spongepowered.tools.obfuscation.AnnotatedMixinInjectorHandler.AnnotatedElementInjector; -import org.spongepowered.tools.obfuscation.AnnotatedMixinOverwriteHandler.AnnotatedElementOverwrite; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementAccessor; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementInvoker; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass; -import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider; +import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; import org.spongepowered.tools.obfuscation.struct.Message; /** @@ -116,17 +118,22 @@ class AnnotatedMixin { /** * Overwrite handler */ - private final AnnotatedMixinOverwriteHandler overwrites; + private final AnnotatedMixinElementHandlerOverwrite overwrites; /** * Shadow handler */ - private final AnnotatedMixinShadowHandler shadows; + private final AnnotatedMixinElementHandlerShadow shadows; /** * Injector handler */ - private final AnnotatedMixinInjectorHandler injectors; + private final AnnotatedMixinElementHandlerInjector injectors; + + /** + * Accessor handler + */ + private final AnnotatedMixinElementHandlerAccessor accessors; public AnnotatedMixin(IMixinAnnotationProcessor ap, TypeElement type) { this.annotation = MirrorUtils.getAnnotation(type, Mixin.class); @@ -140,9 +147,10 @@ class AnnotatedMixin { this.primaryTarget = this.initTargets(); this.remap = AnnotatedMixins.getRemapValue(this.annotation) && this.targets.size() > 0; - this.overwrites = new AnnotatedMixinOverwriteHandler(ap, this); - this.shadows = new AnnotatedMixinShadowHandler(ap, this); - this.injectors = new AnnotatedMixinInjectorHandler(ap, this); + this.overwrites = new AnnotatedMixinElementHandlerOverwrite(ap, this); + this.shadows = new AnnotatedMixinElementHandlerShadow(ap, this); + this.injectors = new AnnotatedMixinElementHandlerInjector(ap, this); + this.accessors = new AnnotatedMixinElementHandlerAccessor(ap, this); } AnnotatedMixin runValidators(ValidationPass pass, Collection validators) { @@ -317,5 +325,13 @@ class AnnotatedMixin { public int registerInjectionPoint(ExecutableElement element, AnnotationMirror inject, AnnotationMirror at) { return this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at)); } + + public void registerAccessor(ExecutableElement element, AnnotationMirror accessor) { + this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor)); + } + + public void registerInvoker(ExecutableElement element, AnnotationMirror invoker) { + this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker)); + } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 9f8f1d55..0a6b501b 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -65,9 +65,12 @@ abstract class AnnotatedMixinElementHandler { private final AnnotationMirror annotation; + private final String desc; + public AnnotatedElement(E element, AnnotationMirror annotation) { this.element = element; this.annotation = annotation; + this.desc = MirrorUtils.getDescriptor(element); } public E getElement() { @@ -78,6 +81,14 @@ abstract class AnnotatedMixinElementHandler { return this.annotation; } + public String getSimpleName() { + return this.getElement().getSimpleName().toString(); + } + + public String getDesc() { + return this.desc; + } + } /** @@ -95,12 +106,23 @@ abstract class AnnotatedMixinElementHandler { */ private final List aliases; + private boolean caseSensitive; + public AliasedElementName(Element element, AnnotationMirror annotation) { this.originalName = element.getSimpleName().toString(); List aliases = MirrorUtils.>getAnnotationValue(annotation, "aliases"); this.aliases = MirrorUtils.unfold(aliases); } + public AliasedElementName setCaseSensitive(boolean caseSensitive) { + this.caseSensitive = caseSensitive; + return this; + } + + public boolean isCaseSensitive() { + return this.caseSensitive; + } + /** * Get whether this member has any aliases defined */ @@ -486,4 +508,13 @@ abstract class AnnotatedMixinElementHandler { } } + protected static > ObfuscationData stripOwnerData(ObfuscationData data) { + ObfuscationData stripped = new ObfuscationData(); + for (ObfuscationType type : data) { + T mapping = data.get(type); + stripped.add(type, mapping.move(null)); + } + return stripped; + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java new file mode 100644 index 00000000..6de620c3 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -0,0 +1,242 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.gen.AccessorInfo; +import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorType; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.obfuscation.mapping.common.MappingField; +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.tools.MirrorUtils; +import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; + +import com.google.common.base.Strings; + +/** + * A module for {@link AnnotatedMixin} which handles accessors + */ +public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler implements IReferenceMapperContext { + + /** + * Accessor element + */ + static class AnnotatedElementAccessor extends AnnotatedElement { + + private final TypeMirror returnType; + + private String targetName; + + public AnnotatedElementAccessor(ExecutableElement element, AnnotationMirror annotation) { + super(element, annotation); + this.returnType = this.getElement().getReturnType(); + } + + public String getAnnotationValue() { + return MirrorUtils.getAnnotationValue(this.getAnnotation()); + } + + public TypeMirror getTargetType() { + switch (this.getAccessorType()) { + case FIELD_GETTER: + return this.returnType; + case FIELD_SETTER: + return this.getElement().getParameters().get(0).asType(); + default: + return null; + } + } + + public String getTargetTypeName() { + return MirrorUtils.getTypeName(this.getTargetType()); + } + + public String getAccessorDesc() { + return MirrorUtils.getInternalName(this.getTargetType()); + } + + public MemberInfo getContext() { + return new MemberInfo(this.getTargetName(), null, this.getAccessorDesc()); + } + + public AccessorType getAccessorType() { + return this.returnType.getKind() == TypeKind.VOID ? AccessorType.FIELD_SETTER : AccessorType.FIELD_GETTER; + } + + public void setTargetName(String targetName) { + this.targetName = targetName; + } + + public String getTargetName() { + return this.targetName; + } + + @Override + public String toString() { + return this.targetName != null ? this.targetName : ""; + } + } + + /** + * Invoker element + */ + static class AnnotatedElementInvoker extends AnnotatedElementAccessor { + + public AnnotatedElementInvoker(ExecutableElement element, AnnotationMirror annotation) { + super(element, annotation); + } + + @Override + public String getAccessorDesc() { + return MirrorUtils.generateSignature(this.getElement()); + } + + @Override + public AccessorType getAccessorType() { + return AccessorType.METHOD_PROXY; + } + + @Override + public String getTargetTypeName() { + return MirrorUtils.getJavaSignature(this.getElement()); + } + + } + + public AnnotatedMixinElementHandlerAccessor(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + super(ap, mixin); + } + + @Override + public ReferenceMapper getReferenceMapper() { + return null; + } + + @Override + public String getClassRef() { + return this.mixin.getClassRef(); + } + + @Override + public IMixinInfo getMixin() { + throw new UnsupportedOperationException("MixinInfo not available at compile time"); + } + + public void registerAccessor(AnnotatedElementAccessor elem) { + if (elem.getAccessorType() == null) { + this.ap.printMessage(Kind.WARNING, "Unsupported accessor type", elem.getElement(), elem.getAnnotation()); + return; + } + + String targetName = this.getAccessorTargetName(elem); + if (targetName == null) { + this.ap.printMessage(Kind.WARNING, "Cannot inflect accessor target name", elem.getElement(), elem.getAnnotation()); + return; + } + elem.setTargetName(targetName); + + for (TypeHandle target : this.mixin.getTargets()) { + if (elem.getAccessorType() == AccessorType.METHOD_PROXY) { + this.registerInvokerForTarget((AnnotatedElementInvoker)elem, target); + } else { + this.registerAccessorForTarget(elem, target); + } + } + } + + private void registerAccessorForTarget(AnnotatedElementAccessor elem, TypeHandle target) { + FieldHandle targetField = target.findField(elem.getTargetName(), elem.getTargetTypeName(), false); + if (targetField == null) { + this.ap.printMessage(Kind.ERROR, "Could not locate @Accessor target " + elem + " in target " + target, elem.getElement(), + elem.getAnnotation()); + return; + } + + ObfuscationData obfData = this.obf.getDataProvider().getObfField(targetField.asMapping().move(target.getName())); + if (obfData.isEmpty()) { + String info = this.mixin.isMultiTarget() ? " in target " + target : ""; + this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping" + info + " for @Accessor target " + elem, + elem.getElement(), elem.getAnnotation()); + return; + } + + obfData = AnnotatedMixinElementHandler.stripOwnerData(obfData); + + try { + this.obf.getReferenceManager().addFieldMapping(this.mixin.getClassRef(), elem.getTargetName(), elem.getContext(), obfData); + } catch (ReferenceConflictException ex) { + this.ap.printMessage(Kind.ERROR, "Mapping conflict for @Accessor target " + elem + ": " + ex.getNew() + " for target " + + target + " conflicts with existing mapping " + ex.getOld(), elem.getElement(), elem.getAnnotation()); + } + } + + private void registerInvokerForTarget(AnnotatedElementInvoker elem, TypeHandle target) { + MethodHandle targetMethod = target.findMethod(elem.getTargetName(), elem.getTargetTypeName(), false); + if (targetMethod == null) { + this.ap.printMessage(Kind.ERROR, "Could not locate @Invoker target " + elem + " in target " + target, elem.getElement(), + elem.getAnnotation()); + return; + } + + ObfuscationData obfData = this.obf.getDataProvider().getObfMethod(targetMethod.asMapping().move(target.getName())); + if (obfData.isEmpty()) { + String info = this.mixin.isMultiTarget() ? " in target " + target : ""; + this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping" + info + " for @Accessor target " + elem, + elem.getElement(), elem.getAnnotation()); + return; + } + + obfData = AnnotatedMixinElementHandler.stripOwnerData(obfData); + + try { + this.obf.getReferenceManager().addMethodMapping(this.mixin.getClassRef(), elem.getTargetName(), elem.getContext(), obfData); + } catch (ReferenceConflictException ex) { + this.ap.printMessage(Kind.ERROR, "Mapping conflict for @Invoker target " + elem + ": " + ex.getNew() + " for target " + + target + " conflicts with existing mapping " + ex.getOld(), elem.getElement(), elem.getAnnotation()); + } + } + + private String getAccessorTargetName(AnnotatedElementAccessor elem) { + String value = elem.getAnnotationValue(); + if (Strings.isNullOrEmpty(value)) { + return this.inflectAccessorTarget(elem); + } + return value; + } + + private String inflectAccessorTarget(AnnotatedElementAccessor elem) { + return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", this, false); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java similarity index 93% rename from src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java rename to src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index c6e85baa..9811a354 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -45,7 +45,7 @@ import org.spongepowered.tools.obfuscation.struct.Message; /** * A module for {@link AnnotatedMixin} whic handles injectors */ -class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler { +class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler { /** * Injector element @@ -88,7 +88,7 @@ class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler { } - AnnotatedMixinInjectorHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } @@ -151,7 +151,7 @@ class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler { try { // If the original owner is unspecified, and the mixin is multi-target, we strip the owner from the obf mappings if (targetMember.owner == null && this.mixin.isMultiTarget()) { - obfData = AnnotatedMixinInjectorHandler.stripOwnerData(obfData); + obfData = AnnotatedMixinElementHandler.stripOwnerData(obfData); } this.obf.getReferenceManager().addMethodMapping(this.classRef, reference, obfData); } catch (ReferenceConflictException ex) { @@ -163,15 +163,6 @@ class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler { return null; } - private static ObfuscationData stripOwnerData(ObfuscationData data) { - ObfuscationData stripped = new ObfuscationData(); - for (ObfuscationType type : data) { - MappingMethod mappingMethod = data.get(type); - stripped.add(type, mappingMethod.move(null)); - } - return stripped; - } - /** * Register a {@link org.spongepowered.asm.mixin.injection.At} annotation * and process the references diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java similarity index 90% rename from src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java rename to src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java index cfaec902..6c037bf7 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java @@ -31,38 +31,26 @@ import javax.lang.model.element.ExecutableElement; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; -import org.spongepowered.tools.MirrorUtils; import org.spongepowered.tools.obfuscation.Mappings.MappingConflictException; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; /** * A module for {@link AnnotatedMixin} which handles method overwrites */ -class AnnotatedMixinOverwriteHandler extends AnnotatedMixinElementHandler { +class AnnotatedMixinElementHandlerOverwrite extends AnnotatedMixinElementHandler { /** * Overwrite element */ static class AnnotatedElementOverwrite extends AnnotatedElement { - private final String desc; - public AnnotatedElementOverwrite(ExecutableElement element, AnnotationMirror annotation) { super(element, annotation); - this.desc = MirrorUtils.getDescriptor(element); - } - - public String getSimpleName() { - return this.getElement().getSimpleName().toString(); - } - - public String getDesc() { - return this.desc; } } - AnnotatedMixinOverwriteHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + AnnotatedMixinElementHandlerOverwrite(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java similarity index 91% rename from src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java rename to src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java index 7805b293..89f4c67c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java @@ -34,7 +34,6 @@ import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.IMapping.Type; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; -import org.spongepowered.tools.MirrorUtils; import org.spongepowered.tools.obfuscation.Mappings.MappingConflictException; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IObfuscationDataProvider; @@ -42,7 +41,7 @@ import org.spongepowered.tools.obfuscation.interfaces.IObfuscationDataProvider; /** * A module for {@link AnnotatedMixin} which handles shadowed fields and methods */ -class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { +class AnnotatedMixinElementHandlerShadow extends AnnotatedMixinElementHandler { /** * A shadow element to be processed @@ -56,15 +55,12 @@ class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { private final ShadowElementName name; - private final String desc; - private final Type type; protected AnnotatedElementShadow(E element, AnnotationMirror annotation, boolean shouldRemap, Type type) { super(element, annotation); this.shouldRemap = shouldRemap; this.name = new ShadowElementName(element, annotation); - this.desc = MirrorUtils.getDescriptor(element); this.type = type; } @@ -76,10 +72,6 @@ class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { return this.name; } - public String getDesc() { - return this.desc; - } - public Type getElementType() { return this.type; } @@ -123,7 +115,7 @@ class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { @Override public void addMapping(ObfuscationType type, IMapping remapped) { - AnnotatedMixinShadowHandler.this.addFieldMapping(type, this.setObfuscatedName(remapped), this.getDesc(), remapped.getDesc()); + AnnotatedMixinElementHandlerShadow.this.addFieldMapping(type, this.setObfuscatedName(remapped), this.getDesc(), remapped.getDesc()); } } @@ -144,12 +136,12 @@ class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { @Override public void addMapping(ObfuscationType type, IMapping remapped) { - AnnotatedMixinShadowHandler.this.addMethodMapping(type, this.setObfuscatedName(remapped), this.getDesc(), remapped.getDesc()); + AnnotatedMixinElementHandlerShadow.this.addMethodMapping(type, this.setObfuscatedName(remapped), this.getDesc(), remapped.getDesc()); } } - AnnotatedMixinShadowHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + AnnotatedMixinElementHandlerShadow(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index 598ef4d3..e247d7da 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -55,6 +55,8 @@ import javax.tools.StandardLocation; import org.spongepowered.asm.launch.MixinBootstrap; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.tools.MirrorUtils; import org.spongepowered.tools.obfuscation.interfaces.IJavadocProvider; @@ -340,6 +342,38 @@ class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITyp return minions; } + + /** + * Register an {@link org.spongepowered.asm.mixin.gen.Accessor} method + * + * @param mixinType Mixin class + * @param method Accessor method + */ + public void registerAccessor(TypeElement mixinType, ExecutableElement method) { + AnnotatedMixin mixinClass = this.getMixin(mixinType); + if (mixinClass == null) { + this.printMessage(Kind.ERROR, "Found @Accessor annotation on a non-mixin method", method); + return; + } + + mixinClass.registerAccessor(method, MirrorUtils.getAnnotation(method, Accessor.class)); + } + + /** + * Register an {@link org.spongepowered.asm.mixin.gen.Accessor} method + * + * @param mixinType Mixin class + * @param method Accessor method + */ + public void registerInvoker(TypeElement mixinType, ExecutableElement method) { + AnnotatedMixin mixinClass = this.getMixin(mixinType); + if (mixinClass == null) { + this.printMessage(Kind.ERROR, "Found @Accessor annotation on a non-mixin method", method); + return; + } + + mixinClass.registerInvoker(method, MirrorUtils.getAnnotation(method, Invoker.class)); + } /** * Register an {@link org.spongepowered.asm.mixin.Overwrite} method diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java index bb08b9dd..53762ef1 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java @@ -26,6 +26,9 @@ package org.spongepowered.tools.obfuscation; import javax.lang.model.element.VariableElement; +import org.spongepowered.asm.obfuscation.mapping.common.MappingField; +import org.spongepowered.tools.MirrorUtils; + /** * Retrieved from a {@link TypeHandle} when searching for fields */ @@ -72,4 +75,9 @@ class FieldHandle { public boolean isRawType() { return this.rawType; } + + public MappingField asMapping() { + return new MappingField(null, this.element.getSimpleName().toString(), MirrorUtils.getInternalName(this.element)); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java index 8b6c6312..2b952f8f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java @@ -26,6 +26,9 @@ package org.spongepowered.tools.obfuscation; import javax.lang.model.element.ExecutableElement; +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.tools.MirrorUtils; + /** * Retrieved from a {@link TypeHandle} when searching for methods */ @@ -54,4 +57,8 @@ class MethodHandle { return this.element; } + public MappingMethod asMapping() { + return new MappingMethod(null, this.element.getSimpleName().toString(), MirrorUtils.getDescriptor(this.element)); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java similarity index 97% rename from src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java rename to src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java index fba47d11..bebf0e22 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java @@ -40,7 +40,7 @@ import org.spongepowered.asm.mixin.Mixin; /** * Base class for mixin annotation processor modules */ -public abstract class MixinProcessor extends AbstractProcessor { +public abstract class MixinObfuscationProcessor extends AbstractProcessor { /** * Mixin info manager diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java similarity index 98% rename from src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java rename to src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java index 38a1167a..ccc05416 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java @@ -54,7 +54,7 @@ import org.spongepowered.tools.MirrorUtils; "org.spongepowered.asm.mixin.injection.Redirect", "org.spongepowered.asm.mixin.injection.At" }) -public class InjectionObfuscationProcessor extends MixinProcessor { +public class MixinObfuscationProcessorInjection extends MixinObfuscationProcessor { /* (non-Javadoc) * @see javax.annotation.processing.AbstractProcessor diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorTargets.java similarity index 68% rename from src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java rename to src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorTargets.java index 525d478b..8eb7f9a3 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorTargets.java @@ -38,14 +38,21 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.tools.MirrorUtils; /** * Annotation processor which finds {@link Shadow} and {@link Overwrite} * annotations in mixin classes and generates new obfuscation mappings */ -@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" }) -public class TargetObfuscationProcessor extends MixinProcessor { +@SupportedAnnotationTypes({ + "org.spongepowered.asm.mixin.Mixin", + "org.spongepowered.asm.mixin.Shadow", + "org.spongepowered.asm.mixin.Overwrite", + "org.spongepowered.asm.mixin.gen.Accessor" +}) +public class MixinObfuscationProcessorTargets extends MixinObfuscationProcessor { /* (non-Javadoc) * @see javax.annotation.processing.AbstractProcessor @@ -61,6 +68,8 @@ public class TargetObfuscationProcessor extends MixinProcessor { this.processMixins(roundEnv); this.processShadows(roundEnv); this.processOverwrites(roundEnv); + this.processAccessors(roundEnv); + this.processInvokers(roundEnv); this.postProcess(roundEnv); return true; @@ -71,6 +80,7 @@ public class TargetObfuscationProcessor extends MixinProcessor { super.postProcess(roundEnv); try { + this.mixins.writeReferences(); this.mixins.writeMappings(); } catch (Exception ex) { ex.printStackTrace(); @@ -120,4 +130,44 @@ public class TargetObfuscationProcessor extends MixinProcessor { } } } + + /** + * Searches for {@link Accessor} annotations and registers them with their + * parent mixins + */ + private void processAccessors(RoundEnvironment roundEnv) { + for (Element elem : roundEnv.getElementsAnnotatedWith(Accessor.class)) { + Element parent = elem.getEnclosingElement(); + if (!(parent instanceof TypeElement)) { + this.mixins.printMessage(Kind.ERROR, "Unexpected parent with type " + MirrorUtils.getElementType(parent), elem); + continue; + } + + if (elem.getKind() == ElementKind.METHOD) { + this.mixins.registerAccessor((TypeElement)parent, (ExecutableElement)elem); + } else { + this.mixins.printMessage(Kind.ERROR, "Element is not a method", elem); + } + } + } + + /** + * Searches for {@link Invoker} annotations and registers them with their + * parent mixins + */ + private void processInvokers(RoundEnvironment roundEnv) { + for (Element elem : roundEnv.getElementsAnnotatedWith(Invoker.class)) { + Element parent = elem.getEnclosingElement(); + if (!(parent instanceof TypeElement)) { + this.mixins.printMessage(Kind.ERROR, "Unexpected parent with type " + MirrorUtils.getElementType(parent), elem); + continue; + } + + if (elem.getKind() == ElementKind.METHOD) { + this.mixins.registerInvoker((TypeElement)parent, (ExecutableElement)elem); + } else { + this.mixins.printMessage(Kind.ERROR, "Element is not a method", elem); + } + } + } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java index 98fe3ed3..00cf471b 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java @@ -209,7 +209,18 @@ public class TypeHandle { * @return handle to the discovered field if matched or null if no match */ public FieldHandle findField(VariableElement element) { - return this.findField(element.getSimpleName().toString(), MirrorUtils.getTypeName(element.asType())); + return this.findField(element, true); + } + + /** + * Find a member field in this type which matches the name and declared type + * of the supplied element + * + * @param element Element to match + * @return handle to the discovered field if matched or null if no match + */ + public FieldHandle findField(VariableElement element, boolean caseSensitive) { + return this.findField(element.getSimpleName().toString(), MirrorUtils.getTypeName(element.asType()), caseSensitive); } /** @@ -221,6 +232,18 @@ public class TypeHandle { * @return handle to the discovered field if matched or null if no match */ public FieldHandle findField(String name, String type) { + return this.findField(name, type, true); + } + + /** + * Find a member field in this type which matches the name and declared type + * specified + * + * @param name Field name to search for + * @param type Field descriptor (java-style) + * @return handle to the discovered field if matched or null if no match + */ + public FieldHandle findField(String name, String type, boolean caseSensitive) { String rawType = MirrorUtils.stripGenerics(type); for (Element element : this.getEnclosedElements()) { @@ -229,15 +252,26 @@ public class TypeHandle { } VariableElement field = (VariableElement)element; - if (this.compareElement(field, name, type)) { + if (this.compareElement(field, name, type, caseSensitive)) { return new FieldHandle(field); - } else if (this.compareElement(field, name, rawType)) { + } else if (this.compareElement(field, name, rawType, caseSensitive)) { return new FieldHandle(field, true); } } return null; } + + /** + * Find a member method in this type which matches the name and declared + * type of the supplied element + * + * @param element Element to match + * @return handle to the discovered method if matched or null if no match + */ + public MethodHandle findMethod(ExecutableElement element) { + return this.findMethod(element, true); + } /** * Find a member method in this type which matches the name and declared @@ -246,8 +280,8 @@ public class TypeHandle { * @param element Element to match * @return handle to the discovered method if matched or null if no match */ - public MethodHandle findMethod(ExecutableElement element) { - return this.findMethod(element.getSimpleName().toString(), MirrorUtils.getJavaSignature(element)); + public MethodHandle findMethod(ExecutableElement element, boolean caseSensitive) { + return this.findMethod(element.getSimpleName().toString(), MirrorUtils.getJavaSignature(element), caseSensitive); } /** @@ -259,6 +293,18 @@ public class TypeHandle { * @return handle to the discovered method if matched or null if no match */ public MethodHandle findMethod(String name, String signature) { + return this.findMethod(name, signature, true); + } + + /** + * Find a member method in this type which matches the name and signature + * specified + * + * @param name Method name to search for + * @param signature Method signature + * @return handle to the discovered method if matched or null if no match + */ + public MethodHandle findMethod(String name, String signature, boolean caseSensitive) { String rawSignature = MirrorUtils.stripGenerics(signature); for (Element element : this.getEnclosedElements()) { @@ -266,7 +312,8 @@ public class TypeHandle { case CONSTRUCTOR: case METHOD: ExecutableElement method = (ExecutableElement)element; - if (this.compareElement(method, name, signature) || this.compareElement(method, name, rawSignature)) { + if (this.compareElement(method, name, signature, caseSensitive) + || this.compareElement(method, name, rawSignature, caseSensitive)) { return new MethodHandle(method); } @@ -282,12 +329,13 @@ public class TypeHandle { return null; } - private boolean compareElement(Element elem, String name, String type) { + private boolean compareElement(Element elem, String name, String type, boolean caseSensitive) { try { String elementName = elem.getSimpleName().toString(); String elementType = MirrorUtils.getJavaSignature(elem); String rawElementType = MirrorUtils.stripGenerics(elementType); - return name.equals(elementName) && (type.length() == 0 || type.equals(elementType) || type.equals(rawElementType)); + boolean compared = caseSensitive ? name.equals(elementName) : name.equalsIgnoreCase(elementName); + return compared && (type.length() == 0 || type.equals(elementType) || type.equals(rawElementType)); } catch (NullPointerException ex) { return false; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java index bb4c23e9..b853e90d 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java @@ -27,12 +27,15 @@ package org.spongepowered.tools.obfuscation.validation; import java.util.Collection; import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.tools.MirrorUtils; import org.spongepowered.tools.obfuscation.MixinValidator; import org.spongepowered.tools.obfuscation.SupportedOptions; @@ -74,6 +77,19 @@ public class TargetValidator extends MixinValidator { } private void validateInterfaceMixin(TypeElement mixin, Collection targets) { + boolean containsNonAccessorMethod = false; + for (Element element : mixin.getEnclosedElements()) { + if (element.getKind() == ElementKind.METHOD) { + boolean isAccessor = MirrorUtils.getAnnotation(element, Accessor.class) != null; + boolean isInvoker = MirrorUtils.getAnnotation(element, Invoker.class) != null; + containsNonAccessorMethod |= (!isAccessor && !isInvoker); + } + } + + if (!containsNonAccessorMethod) { + return; + } + for (TypeHandle target : targets) { TypeElement targetType = target.getElement(); if (targetType != null && !(targetType.getKind() == ElementKind.INTERFACE)) { diff --git a/src/ap/resources/META-INF/services/javax.annotation.processing.Processor b/src/ap/resources/META-INF/services/javax.annotation.processing.Processor index 5c54ba68..d526e229 100644 --- a/src/ap/resources/META-INF/services/javax.annotation.processing.Processor +++ b/src/ap/resources/META-INF/services/javax.annotation.processing.Processor @@ -1,2 +1,2 @@ -org.spongepowered.tools.obfuscation.TargetObfuscationProcessor -org.spongepowered.tools.obfuscation.InjectionObfuscationProcessor \ No newline at end of file +org.spongepowered.tools.obfuscation.MixinObfuscationProcessorInjection +org.spongepowered.tools.obfuscation.MixinObfuscationProcessorTargets diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java b/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java new file mode 100644 index 00000000..aa9b928d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java @@ -0,0 +1,76 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.Shadow; + +/** + * Defines an accessor method in a mixin, the method can be a getter (must + * return the field type and take no arguments) or a setter (must take an + * argument of the field type and return void). The annotated method must be + * abstract. + * + *

Accessors provide a simple way of gaining access to internal class members + * in a target class without needing to resort to access transformers, and + * without the usual need to {@link Shadow} a target field. This can both + * greatly simplify mixins which only contain accessors, and provide for + * faster development than with access transformers since no re-decompile is + * needed to put the changes into effect.

+ * + *

Accessors can be used in regular mixins as a convenient way to generate + * getters and setters. They can also be used to create "Accessor Mixins" + * which are special mixins defined as interfaces which must + * only contain {@link Accessor} and {@link Invoker} methods. Unlike + * normal mixins however, Accessor Mixins are accessible via user code + * and thus no surrogate "Duck" interface is required to expose the + * generated methods, the mixin itself acts as its own Duck.

+ * + *
  • See also {@link Invoker}
+ */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Accessor { + + /** + * Normally the target field name is inflected by examining the annotated + * method name. If the annotated method starts with "get", "set" or "is" + * followed by a capital letter, then the prefix is stripped and the + * remainder of the method name is used as the target field name. + * + *

However sometimes it maye be desirable to name an accessor method + * differently to the target field name. In this case you may specify the + * field using its name.

+ * + * @return name for the target field, or empty string to inflect using the + * annotated method name + */ + public String value() default ""; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java new file mode 100644 index 00000000..9ac77f39 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -0,0 +1,71 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import java.util.ArrayList; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.MethodNode; + +/** + * Base class for accessor generators + */ +public abstract class AccessorGenerator { + + /** + * Accessor info which describes the accessor + */ + protected final AccessorInfo info; + + public AccessorGenerator(AccessorInfo info) { + this.info = info; + } + + /** + * Create an empty accessor method based on the source method + * + * @param maxLocals max locals size for method + * @param maxStack max stack size for method + * @return new method + */ + protected final MethodNode createMethod(int maxLocals, int maxStack) { + MethodNode method = this.info.getMethod(); + MethodNode accessor = new MethodNode(Opcodes.ASM5, method.access & ~Opcodes.ACC_ABSTRACT, method.name, method.desc, null, null); + accessor.visibleAnnotations = new ArrayList(); + accessor.visibleAnnotations.add(this.info.getAnnotation()); + accessor.maxLocals = maxLocals; + accessor.maxStack = maxStack; + return accessor; + } + + /** + * Generate the accessor method + * + * @return generated accessor method + */ + public abstract MethodNode generate(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java new file mode 100644 index 00000000..15c38a2a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java @@ -0,0 +1,58 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.FieldNode; + +/** + * Accessor generator for field accessors + */ +public abstract class AccessorGeneratorField extends AccessorGenerator { + + /** + * The target field, identified by the accessor info + */ + protected final FieldNode targetField; + + /** + * The type of the target member + */ + protected final Type targetType; + + /** + * True for instance field, false for static field + */ + protected final boolean isInstanceField; + + public AccessorGeneratorField(AccessorInfo info) { + super(info); + this.targetField = info.getTargetField(); + this.targetType = info.getTargetFieldType(); + this.isInstanceField = (this.targetField.access & Opcodes.ACC_STATIC) == 0; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java new file mode 100644 index 00000000..da48ae67 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java @@ -0,0 +1,57 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; + +/** + * Generator for instance field getters + */ +public class AccessorGeneratorFieldGetter extends AccessorGeneratorField { + + public AccessorGeneratorFieldGetter(AccessorInfo info) { + super(info); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.gen.AccessorGenerator#generate() + */ + @Override + public MethodNode generate() { + MethodNode method = this.createMethod(this.targetType.getSize(), this.targetType.getSize()); + if (this.isInstanceField) { + method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + int opcode = this.isInstanceField ? Opcodes.GETFIELD : Opcodes.GETSTATIC; + method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc)); + method.instructions.add(new InsnNode(this.targetType.getOpcode(Opcodes.IRETURN))); + return method; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java new file mode 100644 index 00000000..012457f8 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java @@ -0,0 +1,61 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; + +/** + * Generator for field setters + */ +public class AccessorGeneratorFieldSetter extends AccessorGeneratorField { + + public AccessorGeneratorFieldSetter(AccessorInfo info) { + super(info); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.gen.AccessorGenerator#generate() + */ + @Override + public MethodNode generate() { + int stackSpace = this.isInstanceField ? 1 : 0; + int maxLocals = stackSpace + this.targetType.getSize(); + int maxStack = stackSpace + this.targetType.getSize(); + MethodNode method = this.createMethod(maxLocals, maxStack); + if (this.isInstanceField) { + method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + method.instructions.add(new VarInsnNode(this.targetType.getOpcode(Opcodes.ILOAD), stackSpace)); + int opcode = this.isInstanceField ? Opcodes.PUTFIELD : Opcodes.PUTSTATIC; + method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc)); + method.instructions.add(new InsnNode(Opcodes.RETURN)); + return method; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java new file mode 100644 index 00000000..d5c985e3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java @@ -0,0 +1,83 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Generator for proxy methods + */ +public class AccessorGeneratorMethodProxy extends AccessorGenerator { + + /** + * The target field, identified by the accessor info + */ + private final MethodNode targetMethod; + + /** + * Accessor method argument types (raw, from method) + */ + private final Type[] argTypes; + + /** + * Accessor method return type (raw, from method) + */ + private final Type returnType; + + /** + * True for instance method, false for static method + */ + private final boolean isInstanceMethod; + + public AccessorGeneratorMethodProxy(AccessorInfo info) { + super(info); + this.targetMethod = info.getTargetMethod(); + this.argTypes = info.getArgTypes(); + this.returnType = info.getReturnType(); + this.isInstanceMethod = !ASMHelper.hasFlag(this.targetMethod, Opcodes.ACC_STATIC); + } + + @Override + public MethodNode generate() { + int size = ASMHelper.getArgsSize(this.argTypes) + this.returnType.getSize(); + MethodNode method = this.createMethod(size, size); + if (this.isInstanceMethod) { + method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + ASMHelper.loadArgs(this.argTypes, method.instructions, 1); + boolean isPrivate = ASMHelper.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE); + int opcode = this.isInstanceMethod ? (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL) : Opcodes.INVOKESTATIC; + method.instructions.add(new MethodInsnNode(opcode, this.info.getClassNode().name, this.targetMethod.name, this.targetMethod.desc, false)); + method.instructions.add(new InsnNode(this.returnType.getOpcode(Opcodes.IRETURN))); + return method; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java new file mode 100644 index 00000000..7da66b91 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -0,0 +1,378 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.logging.log4j.LogManager; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +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.Strings; +import com.google.common.collect.ImmutableSet; + +/** + * Information about an accessor + */ +public class AccessorInfo extends SpecialMethodInfo { + + /** + * Accessor types + */ + public enum AccessorType { + + /** + * A field getter, accessor must accept no args and return field type + */ + FIELD_GETTER(ImmutableSet.of("get", "is")) { + @Override + AccessorGenerator getGenerator(AccessorInfo info) { + return new AccessorGeneratorFieldGetter(info); + } + }, + + /** + * A field setter, accessor must accept single arg of the field type and + * return void + */ + FIELD_SETTER(ImmutableSet.of("set")) { + @Override + AccessorGenerator getGenerator(AccessorInfo info) { + return new AccessorGeneratorFieldSetter(info); + } + }, + + /** + * An invoker (proxy) method + */ + METHOD_PROXY(ImmutableSet.of("call", "invoke")) { + @Override + AccessorGenerator getGenerator(AccessorInfo info) { + return new AccessorGeneratorMethodProxy(info); + } + }; + + private final Set expectedPrefixes; + + private AccessorType(Set expectedPrefixes) { + this.expectedPrefixes = expectedPrefixes; + } + + public boolean isExpectedPrefix(String prefix) { + return this.expectedPrefixes.contains(prefix); + } + + public String getExpectedPrefixes() { + return this.expectedPrefixes.toString(); + } + + abstract AccessorGenerator getGenerator(AccessorInfo info); + } + + /** + * Pattern for matching accessor names (for inflector) + */ + protected static final Pattern PATTERN_ACCESSOR = Pattern.compile("^(get|set|is|invoke|call)(([A-Z])(.*))$"); + + /** + * Accessor method argument types (raw, from method) + */ + protected final Type[] argTypes; + + /** + * Accessor method return type (raw, from method) + */ + protected final Type returnType; + + /** + * Type of accessor to generate, computed based on the signature of the + * target method. + */ + protected final AccessorType type; + + /** + * For field accessors, the expected type of the target field + */ + private final Type targetFieldType; + + /** + * Computed information about the target field or method, name and + * descriptor + */ + protected final MemberInfo target; + + /** + * For accessors, stores the discovered target field + */ + protected FieldNode targetField; + + /** + * For invokers, stores the discovered target method + */ + protected MethodNode targetMethod; + + public AccessorInfo(MixinTargetContext mixin, MethodNode method) { + this(mixin, method, Accessor.class); + } + + protected AccessorInfo(MixinTargetContext mixin, MethodNode method, Class annotationClass) { + super(mixin, method, ASMHelper.getVisibleAnnotation(method, annotationClass)); + this.argTypes = Type.getArgumentTypes(method.desc); + this.returnType = Type.getReturnType(method.desc); + this.type = this.initType(); + this.targetFieldType = this.initTargetFieldType(); + this.target = this.initTarget(); + } + + protected AccessorType initType() { + if (this.returnType.equals(Type.VOID_TYPE)) { + return AccessorType.FIELD_SETTER; + } + return AccessorType.FIELD_GETTER; + } + + protected Type initTargetFieldType() { + switch (this.type) { + case FIELD_GETTER: + if (this.argTypes.length > 0) { + throw new InvalidAccessorException(this.mixin, this + " must take exactly 0 arguments, found " + this.argTypes.length); + } + return this.returnType; + + case FIELD_SETTER: + if (this.argTypes.length != 1) { + throw new InvalidAccessorException(this.mixin, this + " must take exactly 1 argument, found " + this.argTypes.length); + } + return this.argTypes[0]; + + default: + throw new InvalidAccessorException(this.mixin, "Computed unsupported accessor type " + this.type + " for " + this); + } + } + + protected MemberInfo initTarget() { + MemberInfo target = new MemberInfo(this.getTargetName(), null, this.targetFieldType.getDescriptor()); + this.annotation.visit("target", target.toString()); + return target; + } + + protected String getTargetName() { + String name = ASMHelper.getAnnotationValue(this.annotation); + if (Strings.isNullOrEmpty(name)) { + String inflectedTarget = this.inflectTarget(); + if (inflectedTarget == null) { + throw new InvalidAccessorException(this.mixin, "Failed to inflect target name for " + this + ", supported prefixes: [get, set, is]"); + } + return inflectedTarget; + } + return MemberInfo.parse(name, this.mixin).name; + } + + protected String inflectTarget() { + return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin, + this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE)); + } + + public static String inflectTarget(String accessorName, AccessorType accessorType, String accessorDescription, + IReferenceMapperContext context, boolean verbose) { + Matcher nameMatcher = AccessorInfo.PATTERN_ACCESSOR.matcher(accessorName); + if (nameMatcher.matches()) { + String prefix = nameMatcher.group(1); + String firstChar = nameMatcher.group(3); + String remainder = nameMatcher.group(4); + // If the entire name is upper case, do not lowercase the first char + String name = String.format("%s%s", AccessorInfo.toLowerCase(firstChar, !AccessorInfo.isUpperCase(remainder)), remainder); + if (!accessorType.isExpectedPrefix(prefix) && verbose) { + LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", accessorDescription, prefix, + accessorType.getExpectedPrefixes()); + } + return MemberInfo.parse(name, context).name; + } + return null; + } + + /** + * Get the inflected/specified target member for this accessor + */ + public final MemberInfo getTarget() { + return this.target; + } + + /** + * For field accessors, returns the field type, returns null for invokers + */ + public final Type getTargetFieldType() { + return this.targetFieldType; + } + + /** + * For field accessors, returns the target field, returns null for invokers + */ + public final FieldNode getTargetField() { + return this.targetField; + } + + /** + * For invokers, returns the target method, returns null for field accessors + */ + public final MethodNode getTargetMethod() { + return this.targetMethod; + } + + /** + * Get the return type of the annotated method + */ + public final Type getReturnType() { + return this.returnType; + } + + /** + * Get the argument types of the annotated method + */ + public final Type[] getArgTypes() { + return this.argTypes; + } + + @Override + public String toString() { + return String.format("%s->@%s[%s]::%s%s", this.mixin.toString(), ASMHelper.getSimpleName(this.annotation), this.type.toString(), + this.method.name, this.method.desc); + } + + /** + * First pass, locate the target field in the class. This is done after all + * other mixins are applied so that mixin-added fields and methods can be + * targetted. + */ + public void locate() { + this.targetField = this.findTargetField(); + } + + /** + * Second pass, generate the actual accessor method for this accessor. The + * method still respects intrinsic/mixinmerged rules so is not guaranteed to + * be added to the target class + * + * @return generated accessor method + */ + public MethodNode generate() { + return this.type.getGenerator(this).generate(); + } + + private FieldNode findTargetField() { + return this.findTarget(this.classNode.fields); + } + + /** + * Generified candidate search, since the search logic is the same for both + * fields and methods. + * + * @param nodes Node list to search (method/field list) + * @return best match + */ + protected TNode findTarget(List nodes) { + TNode exactMatch = null; + List candidates = new ArrayList(); + + for (TNode node : nodes) { + String desc = AccessorInfo.getNodeDesc(node); + if (desc == null || !desc.equals(this.target.desc)) { + continue; + } + + String name = AccessorInfo.getNodeName(node); + if (name != null) { + if (name.equals(this.target.name)) { + exactMatch = node; + } + if (name.equalsIgnoreCase(this.target.name)) { + candidates.add(node); + } + } + } + + if (exactMatch != null) { + if (candidates.size() > 1) { + LogManager.getLogger("mixin").debug("{} found an exact match for {} but other candidates were found!", this, this.target); + } + return exactMatch; + } + + if (candidates.size() == 1) { + return candidates.get(0); + } + + throw new InvalidAccessorException(this, "Multiple candidates were found matching " + this.target + " in " + this.classNode.name + + " for " + this); + } + + private static String getNodeDesc(TNode node) { + return (node instanceof MethodNode) ? ((MethodNode)node).desc : ((node instanceof FieldNode) ? ((FieldNode)node).desc : null); + } + + private static String getNodeName(TNode node) { + return (node instanceof MethodNode) ? ((MethodNode)node).name : ((node instanceof FieldNode) ? ((FieldNode)node).name : null); + } + + /** + * Return a wrapper AccessorInfo of the correct type based on the method + * passed in. + * + * @param mixin mixin context which owns this accessor + * @param method annotated method + * @param type annotation type to process + * @return parsed AccessorInfo + */ + public static AccessorInfo of(MixinTargetContext mixin, MethodNode method, Class type) { + if (type == Accessor.class) { + return new AccessorInfo(mixin, method); + } else if (type == Invoker.class) { + return new InvokerInfo(mixin, method); + } + throw new InvalidAccessorException(mixin, "Could not parse accessor for unknown type " + type.getName()); + } + + private static String toLowerCase(String string, boolean condition) { + return condition ? string.toLowerCase() : string; + } + + private static boolean isUpperCase(String string) { + return string.toUpperCase().equals(string); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java b/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java new file mode 100644 index 00000000..db3bfeff --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java @@ -0,0 +1,76 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.Shadow; + +/** + * Defines an invoker method (also known as a proxy method in + * a mixin, the method. The annotated method must be abstract and the + * signature of the method must match the target method precisely. + * + *

Invokers provide a simple way of gaining access to internal class members + * in a target class without needing to resort to access transformers, and + * without the usual need to {@link Shadow} a target method. This can both + * greatly simplify mixins which only contain accessors, and provide for + * faster development than with access transformers since no re-decompile is + * needed to put the changes into effect.

+ * + *

Invokers can be used in regular mixins as a way to provide access to a + * private method without needing to shadow and then manually proxy the method + * call. They can also be used to create "Accessor Mixins" which are + * special mixins defined as interfaces which must only contain + * {@link Accessor} and {@link Invoker} methods. Unlike normal mixins however, + * Accessor Mixins are accessible via user code and thus no surrogate + * "Duck" interface is required to expose the generated methods, the + * mixin itself acts as its own Duck.

+ * + *
  • See also {@link Accessor}
+ */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Invoker { + + /** + * Normally the target method name is inflected by examining the annotated + * method name. If the annotated method starts with "call" or "invoke" + * followed by a capital letter, then the prefix is stripped and the + * remainder of the method name is used as the target method name. + * + *

However sometimes it maye be desirable to name an accessor method + * differently to the target method. In this case you may specify the method + * using its name.

+ * + * @return name for the target method, or empty string to inflect using the + * annotated method name + */ + public String value() default ""; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java new file mode 100644 index 00000000..bc418bf9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -0,0 +1,65 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + * Information about an invoker + */ +public class InvokerInfo extends AccessorInfo { + + public InvokerInfo(MixinTargetContext mixin, MethodNode method) { + super(mixin, method, Invoker.class); + } + + @Override + protected AccessorType initType() { + return AccessorType.METHOD_PROXY; + } + + @Override + protected Type initTargetFieldType() { + return null; + } + + @Override + protected MemberInfo initTarget() { + return new MemberInfo(this.getTargetName(), null, this.method.desc); + } + + @Override + public void locate() { + this.targetMethod = this.findTargetMethod(); + } + + private MethodNode findTargetMethod() { + return this.findTarget(this.classNode.methods); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java new file mode 100644 index 00000000..0308a77c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java @@ -0,0 +1,74 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen.throwables; + +import org.spongepowered.asm.mixin.gen.AccessorInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; + +/** + * Thrown when an accessor fails a state check + */ +public class InvalidAccessorException extends InvalidMixinException { + + private static final long serialVersionUID = 2L; + + private final AccessorInfo info; + + public InvalidAccessorException(IReferenceMapperContext context, String message) { + super(context, message); + this.info = null; + } + + public InvalidAccessorException(AccessorInfo info, String message) { + super(info.getContext(), message); + this.info = info; + } + + public InvalidAccessorException(IReferenceMapperContext context, Throwable cause) { + super(context, cause); + this.info = null; + } + + public InvalidAccessorException(AccessorInfo info, Throwable cause) { + super(info.getContext(), cause); + this.info = info; + } + + public InvalidAccessorException(IReferenceMapperContext context, String message, Throwable cause) { + super(context, message, cause); + this.info = null; + } + + public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) { + super(info.getContext(), message, cause); + this.info = info; + } + + public AccessorInfo getAccessorInfo() { + return this.info; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 77b0c719..dbc3a3ac 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -35,7 +35,6 @@ import java.util.Map.Entry; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.MixinEnvironment; @@ -52,6 +51,7 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; 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.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; @@ -61,24 +61,7 @@ import org.spongepowered.asm.util.ASMHelper; * Contructs information about an injection from an {@link Inject} annotation * and allows the injection to be processed. */ -public abstract class InjectionInfo { - - protected final AnnotationNode annotation; - - /** - * Class - */ - protected final ClassNode classNode; - - /** - * Annotated method - */ - protected final MethodNode method; - - /** - * Mixin data - */ - protected final MixinTargetContext mixin; +public abstract class InjectionInfo extends SpecialMethodInfo { /** * Annotated method is static @@ -139,10 +122,7 @@ public abstract class InjectionInfo { * @param annotation Annotation to parse */ protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { - this.mixin = mixin; - this.method = method; - this.annotation = annotation; - this.classNode = mixin.getTargetClassNode(); + super(mixin, method, annotation); this.isStatic = ASMHelper.methodIsStatic(method); this.readAnnotation(); } @@ -287,42 +267,6 @@ public abstract class InjectionInfo { return InjectionInfo.describeInjector(this.mixin, this.annotation, this.method); } - /** - * Get the mixin target context for this injection - * - * @return the target context - */ - public MixinTargetContext getContext() { - return this.mixin; - } - - /** - * Get the annotation which this InjectionInfo was created from - * - * @return The annotation which this InjectionInfo was created from - */ - public AnnotationNode getAnnotation() { - return this.annotation; - } - - /** - * Get the class node for this injection - * - * @return the class containing the injector and the target - */ - public ClassNode getClassNode() { - return this.classNode; - } - - /** - * Get method being called - * - * @return injector method - */ - public MethodNode getMethod() { - return this.method; - } - /** * Get methods being injected into * diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index e88d6409..3afeff53 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -127,6 +127,18 @@ public class MemberInfo { this(name, owner, null, matchAll); } + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + */ + public MemberInfo(String name, String owner, String desc) { + this(name, owner, desc, false); + } + /** * ctor * @@ -429,7 +441,7 @@ public class MemberInfo { * @param newOwner New owner for this member */ public MemberInfo move(String newOwner) { - if (newOwner.equals(this.owner)) { + if ((newOwner == null && this.owner == null) || (newOwner != null && newOwner.equals(this.owner))) { return this; } return new MemberInfo(this, newOwner); diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java new file mode 100644 index 00000000..c73ac73d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -0,0 +1,100 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.struct; + +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + * Information about a special mixin method such as an injector or accessor + */ +public abstract class SpecialMethodInfo { + + /** + * Annotation on the method + */ + protected final AnnotationNode annotation; + + /** + * Class + */ + protected final ClassNode classNode; + + /** + * Annotated method + */ + protected final MethodNode method; + + /** + * Mixin data + */ + protected final MixinTargetContext mixin; + + public SpecialMethodInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + this.mixin = mixin; + this.method = method; + this.annotation = annotation; + this.classNode = mixin.getTargetClassNode(); + } + + /** + * Get the mixin target context for this injection + * + * @return the target context + */ + public final MixinTargetContext getContext() { + return this.mixin; + } + + /** + * Get the annotation which this InjectionInfo was created from + * + * @return The annotation which this InjectionInfo was created from + */ + public final AnnotationNode getAnnotation() { + return this.annotation; + } + + /** + * Get the class node for this injection + * + * @return the class containing the injector and the target + */ + public final ClassNode getClassNode() { + return this.classNode; + } + + /** + * Get method being called + * + * @return injector method + */ + public final MethodNode getMethod() { + return this.method; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index adff0c6b..c18df3cc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -48,6 +48,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.util.ASMHelper; @@ -357,19 +359,26 @@ public class ClassInfo extends TreeInfo { private final List frames; + private boolean isAccessor; + public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; } + @SuppressWarnings("unchecked") public Method(MethodNode method) { this(method, false); this.setUnique(ASMHelper.getVisibleAnnotation(method, Unique.class) != null); + this.isAccessor = ASMHelper.getSingleVisibleAnnotation(method, Accessor.class, Invoker.class) != null; } + @SuppressWarnings("unchecked") public Method(MethodNode method, boolean injected) { super(Type.METHOD, method.name, method.desc, method.access, injected); this.frames = this.gatherFrames(method); + this.setUnique(ASMHelper.getVisibleAnnotation(method, Unique.class) != null); + this.isAccessor = ASMHelper.getSingleVisibleAnnotation(method, Accessor.class, Invoker.class) != null; } public Method(String name, String desc) { @@ -407,6 +416,10 @@ public class ClassInfo extends TreeInfo { return ClassInfo.this; } + public boolean isAccessor() { + return this.isAccessor; + } + @Override public boolean equals(Object obj) { if (!(obj instanceof Method)) { @@ -415,6 +428,7 @@ public class ClassInfo extends TreeInfo { return super.equals(obj); } + } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java index 3f422627..1f11f64c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java @@ -37,7 +37,7 @@ import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinE * Applicator for interface mixins, mainly just disables things which aren't * supported for interface mixins */ -public class MixinApplicatorInterface extends MixinApplicatorStandard { +class MixinApplicatorInterface extends MixinApplicatorStandard { /** * ctor diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index fac67f44..7f0fc8e4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -68,7 +68,7 @@ import com.google.common.collect.ImmutableList; /** * Applies mixins to a target class */ -public class MixinApplicatorStandard { +class MixinApplicatorStandard { /** * Annotations which can have constraints @@ -289,6 +289,7 @@ public class MixinApplicatorStandard { break; case INJECT: + this.applyAccessors(mixin); this.applyInjections(mixin); break; @@ -379,24 +380,32 @@ public class MixinApplicatorStandard { */ protected void applyMethods(MixinTargetContext mixin) { for (MethodNode shadow : mixin.getShadowMethods()) { - MethodNode target = this.findTargetMethod(shadow); - if (target != null) { - this.mergeAnnotations(shadow, target); - } + this.applyShadowMethod(mixin, shadow); } for (MethodNode mixinMethod : mixin.getMethods()) { - // Reparent all mixin methods into the target class - mixin.transformMethod(mixinMethod); + this.applyNormalMethod(mixin, mixinMethod); + } + } - if (!mixinMethod.name.startsWith("<")) { - this.checkMethodVisibility(mixin, mixinMethod); - this.checkMethodConstraints(mixin, mixinMethod); - this.mergeMethod(mixin, mixinMethod); - } else if (Constants.CLINIT.equals(mixinMethod.name)) { - // Class initialiser insns get appended - this.appendInsns(mixinMethod); - } + protected void applyShadowMethod(MixinTargetContext mixin, MethodNode shadow) { + MethodNode target = this.findTargetMethod(shadow); + if (target != null) { + this.mergeAnnotations(shadow, target); + } + } + + protected void applyNormalMethod(MixinTargetContext mixin, MethodNode mixinMethod) { + // Reparent all mixin methods into the target class + mixin.transformMethod(mixinMethod); + + if (!mixinMethod.name.startsWith("<")) { + this.checkMethodVisibility(mixin, mixinMethod); + this.checkMethodConstraints(mixin, mixinMethod); + this.mergeMethod(mixin, mixinMethod); + } else if (Constants.CLINIT.equals(mixinMethod.name)) { + // Class initialiser insns get appended + this.appendInsns(mixinMethod); } } @@ -860,6 +869,20 @@ public class MixinApplicatorStandard { protected void applyInjections(MixinTargetContext mixin) { mixin.applyInjections(); } + + /** + * Apply all accessors discovered during preprocessing + * + * @param mixin Mixin being applied + */ + protected void applyAccessors(MixinTargetContext mixin) { + List accessorMethods = mixin.generateAccessors(); + for (MethodNode method : accessorMethods) { + if (!method.name.startsWith("<")) { + this.mergeMethod(mixin, method); + } + } + } /** * Check visibility before merging a mixin method diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index 14eed789..dc1535f2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -41,7 +41,10 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.MixinInitialisationError; +import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Option; @@ -113,6 +116,11 @@ class MixinConfig implements Comparable, IMixinConfig { */ private final transient Set syntheticInnerClasses = new HashSet(); + /** + * Accessor mixins in this set + */ + private final transient Set passThroughClasses = new HashSet(); + /** * Marshal */ @@ -475,6 +483,9 @@ class MixinConfig implements Comparable, IMixinConfig { if (hotSwapper != null) { hotSwapper.registerMixinClass(mixin.getClassName()); } + if (mixin.isLoadable()) { + this.passThroughClasses.add(mixin.getClassName()); + } this.mixins.add(mixin); } } catch (InvalidMixinException ex) { @@ -673,14 +684,52 @@ class MixinConfig implements Comparable, IMixinConfig { } /** - * Get whether this config can allow passthrough for the specified class + * Get whether the specified class is a synthetic inner class for this + * config * * @param className Class name to check * @return True if the specified class name is in this config's passthrough * set */ public boolean canPassThrough(String className) { - return this.syntheticInnerClasses.contains(className); + return this.syntheticInnerClasses.contains(className) || this.passThroughClasses.contains(className); + } + + public ClassNode passThrough(String className, ClassNode passThroughClassNode) { + if (this.syntheticInnerClasses.contains(className)) { + return this.passThroughSyntheticInner(passThroughClassNode); + } + + return passThroughClassNode; + } + + /** + * "Pass through" a synthetic inner class. Transforms package-private + * members in the class into public so that they are accessible from their + * new home in the target class + * + * @param classNode Class to pass through as tree + * @return transformed class + */ + private ClassNode passThroughSyntheticInner(ClassNode classNode) { + // Make the class public + classNode.access |= Opcodes.ACC_PUBLIC; + + // Make package-private fields public + for (FieldNode field : classNode.fields) { + if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) { + field.access |= Opcodes.ACC_PUBLIC; + } + } + + // Make package-private methods public + for (MethodNode method : classNode.methods) { + if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) { + method.access |= Opcodes.ACC_PUBLIC; + } + } + + return classNode; } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index 3f9aa5d2..895750db 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.transformer; import java.io.IOException; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -57,6 +58,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.Surrogate; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException; @@ -100,7 +102,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } public boolean isSurrogate() { - return ASMHelper.getVisibleAnnotation(this, Surrogate.class) != null; + return this.getVisibleAnnotation(Surrogate.class) != null; + } + + public AnnotationNode getVisibleAnnotation(Class annotationClass) { + return ASMHelper.getVisibleAnnotation(this, annotationClass); } public AnnotationNode getInjectorAnnotation() { @@ -277,7 +283,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { this.validateRemappables(targetClasses); // Read information from the mixin - this.readImplementations(); + this.readImplementations(type); this.readInnerClasses(); // Takeoff validation @@ -334,8 +340,9 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Read and process any {@link Implements} annotations on the mixin */ - void readImplementations() { + void readImplementations(SubType type) { this.interfaces.addAll(this.classNode.interfaces); + this.interfaces.addAll(type.getInterfaces()); AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(this.classNode, Implements.class); if (implementsAnnotation == null) { @@ -454,6 +461,10 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { this.targetMustBeInterface = targetMustBeInterface; } + Collection getInterfaces() { + return Collections.emptyList(); + } + /** * Get whether this mixin is detached super, must call {@link #validate} * first @@ -463,7 +474,16 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { boolean isDetachedSuper() { return this.detached; } - + + /** + * True if this mixin class can actually be classloaded + * + * @return + */ + boolean isLoadable() { + return false; + } + /** * Validate a single target before adding * @@ -555,7 +575,74 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) { return new MixinPreProcessorInterface(this.mixin, classNode); } + } + + /** + * An accessor mixin + */ + static class Accessor extends SubType { + + private final Collection interfaces = new ArrayList(); + + Accessor(MixinInfo info) { + super(info, "@Mixin", false); + this.interfaces.add(info.getClassRef()); + } + + @Override + boolean isLoadable() { + return true; + } + + @Override + Collection getInterfaces() { + return this.interfaces; + } + + @Override + void validateTarget(String targetName, ClassInfo targetInfo) { + boolean targetIsInterface = targetInfo.isInterface(); + if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces()) { + throw new InvalidMixinException(this.mixin, "Accessor mixin targetting an interface is not supported in current enviromnment"); + } + } + + @Override + void validate(State state, List targetClasses) { + ClassNode classNode = state.getClassNode(); + + if (!"java/lang/Object".equals(classNode.superName)) { + throw new InvalidMixinException(this.mixin, "Super class of " + this + " is invalid, found " + + classNode.superName.replace('/', '.')); + } + } + + @Override + MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) { + return new MixinPreProcessorAccessor(this.mixin, classNode); + } + } + + static SubType getTypeFor(MixinInfo mixin) { + if (!mixin.getClassInfo().isInterface()) { + return new SubType.Standard(mixin); + } + + boolean containsNonAccessorMethod = false; + for (Method method : mixin.getClassInfo().getMethods()) { + containsNonAccessorMethod |= !method.isAccessor(); + } + + if (containsNonAccessorMethod) { + // If the mixin contains any other methods, treat it as a regular interface mixin + return new SubType.Interface(mixin); + } + + // The mixin contains no non-accessor methods, so we can treat it as an accessor + return new SubType.Accessor(mixin); + } + } /** @@ -666,13 +753,20 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { byte[] mixinBytes = this.loadMixinClass(this.className, runTransformers); this.pendingState = new State(mixinBytes); this.info = this.pendingState.getClassInfo(); - this.type = this.initType(); + this.type = SubType.getTypeFor(this); } catch (InvalidMixinException ex) { throw ex; } catch (Exception ex) { throw new InvalidMixinException(this, ex); } + if (!this.type.isLoadable()) { + // Inject the mixin class name into the LaunchClassLoader's invalid + // classes set so that any classes referencing the mixin directly will + // cause the game to crash + MixinInfo.classLoaderUtil.registerInvalidClass(this.className); + } + // Read the class bytes and transform try { this.priority = this.readPriority(this.pendingState.getClassNode()); @@ -684,18 +778,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { throw new InvalidMixinException(this, ex); } } - - /** - * Initialise the mixin subtype handler - * - * @return subtype - */ - private SubType initType() { - if (this.info.isInterface()) { - return new SubType.Interface(this); - } - return new SubType.Standard(this); - } /** * Run validation pass @@ -910,6 +992,13 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { return this.getState().isUnique(); } + /** + * True if the mixin class is actually class-loadable + */ + public boolean isLoadable() { + return this.type.isLoadable(); + } + /** * Get the logging level for this mixin */ @@ -1000,11 +1089,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { throw new InvalidMixinException(this, "An error was encountered whilst loading the mixin class", ex); } - // Inject the mixin class name into the LaunchClassLoader's invalid - // classes set so that any classes referencing the mixin directly will - // cause the game to crash - MixinInfo.classLoaderUtil.registerInvalidClass(mixinClassName); - return mixinBytes; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorAccessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorAccessor.java new file mode 100644 index 00000000..f454740a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorAccessor.java @@ -0,0 +1,38 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; + +/** + * Bytecode preprocessor for accessor mixins + */ +class MixinPreProcessorAccessor extends MixinPreProcessorInterface { + + public MixinPreProcessorAccessor(MixinInfo mixin, MixinClassNode classNode) { + super(mixin, classNode); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index edf29b9d..64d6132c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -40,6 +40,9 @@ import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; +import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; @@ -208,26 +211,30 @@ class MixinPreProcessorStandard { continue; } - if (mixinMethod.isInjector()) { + if (this.attachInjectorMethod(context, mixinMethod)) { continue; } - if (this.processShadowMethod(context, mixinMethod)) { - iter.remove(); - context.addShadowMethod(mixinMethod); - continue; - } - - if (this.processOverwriteMethod(context, mixinMethod)) { - continue; - } - - if (this.processUniqueMethod(context, mixinMethod)) { + if (this.attachAccessorMethod(context, mixinMethod)) { iter.remove(); continue; } - this.processMethod(mixinMethod); + if (this.attachShadowMethod(context, mixinMethod)) { + iter.remove(); + continue; + } + + if (this.attachOverwriteMethod(context, mixinMethod)) { + continue; + } + + if (this.attachUniqueMethod(context, mixinMethod)) { + iter.remove(); + continue; + } + + this.attachMethod(mixinMethod); } } @@ -235,33 +242,60 @@ class MixinPreProcessorStandard { return true; } - protected boolean processShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { - return this.processSpecialMethod(context, mixinMethod, Shadow.class, false); + protected boolean attachInjectorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return mixinMethod.isInjector(); } - - protected boolean processOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { - return this.processSpecialMethod(context, mixinMethod, Overwrite.class, true); + + protected boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return this.attachAccessorMethod(context, mixinMethod, Accessor.class) || this.attachAccessorMethod(context, mixinMethod, Invoker.class); } - - protected boolean processSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class type, - boolean overwrite) { - - AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, type); + + private boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class type) { + AnnotationNode annotation = mixinMethod.getVisibleAnnotation(type); if (annotation == null) { return false; } - if (this.mixin.isUnique() && overwrite) { - throw new InvalidMixinException(this.mixin, "@Overwrite method " + mixinMethod.name + " found in a @Unique mixin"); + Method method = this.getSpecialMethod(mixinMethod, type); + if (!method.isAbstract()) { + throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " is not abstract"); + } + + if (method.isStatic()) { + throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be static"); } - Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + context.addAccessorMethod(mixinMethod, type); + return true; + } + + protected boolean attachShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + if (this.attachSpecialMethod(context, mixinMethod, Shadow.class, false)) { + context.addShadowMethod(mixinMethod); + return true; + } + + return false; + } + + protected boolean attachOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return this.attachSpecialMethod(context, mixinMethod, Overwrite.class, true); + } + + protected boolean attachSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class type, + boolean overwrite) { + + AnnotationNode annotation = mixinMethod.getVisibleAnnotation(type); + if (annotation == null) { + return false; + } + + if (overwrite) { + this.checkMixinNotUnique(mixinMethod, type); + } + + Method method = this.getSpecialMethod(mixinMethod, type); MethodNode target = context.findMethod(mixinMethod, annotation); - - if (method.isUnique()) { - throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be @Unique"); - } - if (target == null) { if (overwrite) { return false; @@ -275,7 +309,7 @@ class MixinPreProcessorStandard { } if (Constants.CTOR.equals(target.name)) { - throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!"); + throw new InvalidMixinException(this.mixin, "Nice try! " + mixinMethod.name + " cannot alias a constructor!"); } if (!target.name.equals(mixinMethod.name)) { @@ -289,7 +323,27 @@ class MixinPreProcessorStandard { return true; } - protected boolean processUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + protected Method getSpecialMethod(MixinMethodNode mixinMethod, Class type) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + this.checkMethodNotUnique(type, method); + return method; + } + + protected void checkMethodNotUnique(Class type, Method method) { + if (method.isUnique()) { + String annotation = "@" + ASMHelper.getSimpleName(type); + throw new InvalidMixinException(this.mixin, annotation + " method " + method.getName() + " cannot be @Unique"); + } + } + + protected void checkMixinNotUnique(MixinMethodNode mixinMethod, Class type) { + if (this.mixin.isUnique()) { + String annotation = "@" + ASMHelper.getSimpleName(type); + throw new InvalidMixinException(this.mixin, annotation + " method " + mixinMethod.name + " found in a @Unique mixin"); + } + } + + protected boolean attachUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); if (method == null || (!method.isUnique() && !this.mixin.isUnique())) { return false; @@ -319,7 +373,7 @@ class MixinPreProcessorStandard { return true; } - protected void processMethod(MixinMethodNode mixinMethod) { + protected void attachMethod(MixinMethodNode mixinMethod) { Method method = this.mixin.getClassInfo().findMethod(mixinMethod); if (method == null) { return; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 9842f3bd..c8a27f9a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.transformer; +import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; @@ -47,6 +48,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.SoftOverride; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.gen.AccessorInfo; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; @@ -128,7 +130,12 @@ public class MixinTargetContext implements IReferenceMapperContext { * Injectors for this target */ private final List injectors = new ArrayList(); - + + /** + * Accessor method list + */ + private final List accessors = new ArrayList(); + /** * True if this mixin inherits from a mixin at any point in its hierarchy */ @@ -178,6 +185,13 @@ public class MixinTargetContext implements IReferenceMapperContext { this.shadowFields.put(fieldNode, fieldInfo); } + /** + * @param method + */ + void addAccessorMethod(MethodNode method, Class type) { + this.accessors.add(AccessorInfo.of(this, method, type)); + } + /** * Callback from the applicator which notifies us that a method was merged * @@ -1016,4 +1030,17 @@ public class MixinTargetContext implements IReferenceMapperContext { this.injectors.clear(); } + public List generateAccessors() { + for (AccessorInfo accessor : this.accessors) { + accessor.locate(); + } + + List methods = new ArrayList(); + + for (AccessorInfo accessor : this.accessors) { + methods.add(accessor.generate()); + } + + return methods; + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index b9211b8b..dccaf7b4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -43,10 +43,7 @@ import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; @@ -55,11 +52,11 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; import org.spongepowered.asm.mixin.throwables.MixinApplyError; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.mixin.throwables.MixinPrepareError; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.transformer.MixinTransformerModuleCheckClass.ValidationFailedException; import org.spongepowered.asm.mixin.transformer.debug.IDecompiler; import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; @@ -492,7 +489,7 @@ public class MixinTransformer extends TreeTransformer { for (MixinConfig config : this.configs) { if (config.packageMatch(transformedName)) { if (config.canPassThrough(transformedName)) { - return this.passThrough(name, transformedName, basicClass); + return this.passThrough(config, name, transformedName, basicClass); } invalidRef = true; continue; @@ -678,36 +675,18 @@ public class MixinTransformer extends TreeTransformer { } /** - * "Pass through" a synthetic inner class. Transforms package-private - * members in the class into public so that they are accessible from their - * new home in the target class + * Pass a class through a specific config, used to access classes within a + * mixin package through a pinhole * + * @param config * @param name original class name * @param transformedName deobfuscated class name * @param basicClass class bytecode * @return public-ified class bytecode */ - private byte[] passThrough(String name, String transformedName, byte[] basicClass) { - ClassNode passThroughClass = this.readClass(basicClass, true); - - // Make the class public - passThroughClass.access |= Opcodes.ACC_PUBLIC; - - // Make package-private fields public - for (FieldNode field : passThroughClass.fields) { - if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) { - field.access |= Opcodes.ACC_PUBLIC; - } - } - - // Make package-private methods public - for (MethodNode method : passThroughClass.methods) { - if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) { - method.access |= Opcodes.ACC_PUBLIC; - } - } - - return this.writeClass(transformedName, passThroughClass, false); + private byte[] passThrough(MixinConfig config, String name, String transformedName, byte[] basicClass) { + ClassNode classNode = config.passThrough(transformedName, this.readClass(basicClass, true)); + return this.writeClass(transformedName, classNode, false); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java index 9af19373..2a597bf7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java @@ -29,14 +29,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard; - /** *

For internal use only! Contains small parts. Keep out of reach of * children.

* - *

Decoration annotation used by the {@link MixinApplicatorStandard} to mark - * methods in a class which have been added or overwritten by a mixin.

+ *

Decoration annotation used by the mixin applicator to mark methods in a + * class which have been added or overwritten by a mixin.

*/ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME)