0.6.13 Add support for conforming visibility of overwritten methods

This commit is contained in:
Mumfrey committed 2017-07-02 15:52:44 +01:00
commit 64232fe110
25 files changed
+549 -114

No files matched your search

+1 -1
View File
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
buildVersion=0.6.12
buildVersion=0.6.13
buildType=SNAPSHOT
@@ -88,6 +88,11 @@ class AnnotatedMixin {
* Mixin class
*/
private final TypeElement mixin;
/**
* Methods
*/
private final List<ExecutableElement> methods;
/**
* Mixin class
@@ -146,6 +151,11 @@ class AnnotatedMixin {
* Soft implementation handler;
*/
private final AnnotatedMixinElementHandlerSoftImplements softImplements;
/**
* True once the FINAL
*/
private boolean validated = false;
public AnnotatedMixin(IMixinAnnotationProcessor ap, TypeElement type) {
this.typeProvider = ap.getTypeProvider();
@@ -154,11 +164,11 @@ class AnnotatedMixin {
this.messager = ap;
this.mixin = type;
this.handle = new TypeHandle(type);
this.methods = new ArrayList<ExecutableElement>(this.handle.<ExecutableElement>getEnclosedElements(ElementKind.METHOD));
this.virtual = this.handle.getAnnotation(Pseudo.class).exists();
this.annotation = this.handle.getAnnotation(Mixin.class);
this.classRef = type.getQualifiedName().toString().replace('.', '/');
this.primaryTarget = this.initTargets();
// this.remap = !this.virtual && this.annotation.getBoolean("remap", true) && this.targets.size() > 0;
this.remap = this.annotation.getBoolean("remap", true) && this.targets.size() > 0;
this.overwrites = new AnnotatedMixinElementHandlerOverwrite(ap, this);
@@ -174,6 +184,11 @@ class AnnotatedMixin {
break;
}
}
if (pass == ValidationPass.FINAL && !this.validated) {
this.validated = true;
this.runFinalValidation();
}
return this;
}
@@ -319,7 +334,14 @@ class AnnotatedMixin {
return this.mappings;
}
private void runFinalValidation() {
for (ExecutableElement method : this.methods) {
this.overwrites.registerMerge(method);
}
}
public void registerOverwrite(ExecutableElement method, AnnotationHandle overwrite) {
this.methods.remove(method);
this.overwrites.registerOverwrite(new AnnotatedElementOverwrite(method, overwrite));
}
@@ -328,10 +350,12 @@ class AnnotatedMixin {
}
public void registerShadow(ExecutableElement method, AnnotationHandle shadow, boolean shouldRemap) {
this.methods.remove(method);
this.shadows.registerShadow(this.shadows.new AnnotatedElementShadowMethod(method, shadow, shouldRemap));
}
public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) {
this.methods.remove(method);
this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, remap));
List<AnnotationHandle> ats = inject.getAnnotationList("at");
@@ -360,10 +384,12 @@ class AnnotatedMixin {
}
public void registerAccessor(ExecutableElement element, AnnotationHandle accessor, boolean shouldRemap) {
this.methods.remove(element);
this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, shouldRemap));
}
public void registerInvoker(ExecutableElement element, AnnotationHandle invoker, boolean shouldRemap) {
this.methods.remove(element);
this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, shouldRemap));
}
@@ -49,6 +49,7 @@ import org.spongepowered.tools.obfuscation.mirror.FieldHandle;
import org.spongepowered.tools.obfuscation.mirror.MethodHandle;
import org.spongepowered.tools.obfuscation.mirror.TypeHandle;
import org.spongepowered.tools.obfuscation.mirror.TypeUtils;
import org.spongepowered.tools.obfuscation.mirror.Visibility;
/**
* Base class for module for {@link AnnotatedMixin} which handle different
@@ -153,6 +154,10 @@ abstract class AnnotatedMixinElementHandler {
return this.originalName;
}
public boolean hasPrefix() {
return false;
}
}
/**
@@ -232,6 +237,11 @@ abstract class AnnotatedMixinElementHandler {
this.obfuscated = name;
return this;
}
@Override
public boolean hasPrefix() {
return this.hasPrefix;
}
/**
* Get the prefix (if set), does not return the expected prefix
@@ -369,7 +379,7 @@ abstract class AnnotatedMixinElementHandler {
protected final void validateTarget(Element element, AnnotationHandle annotation, AliasedElementName name, String type) {
if (element instanceof ExecutableElement) {
this.validateTargetMethod((ExecutableElement)element, annotation, name, type);
this.validateTargetMethod((ExecutableElement)element, annotation, name, type, false, false);
} else if (element instanceof VariableElement) {
this.validateTargetField((VariableElement)element, annotation, name, type);
}
@@ -379,7 +389,8 @@ abstract class AnnotatedMixinElementHandler {
* Checks whether the specified method exists in all targets and raises
* warnings where appropriate
*/
protected final void validateTargetMethod(ExecutableElement method, AnnotationHandle annotation, AliasedElementName name, String type) {
protected final void validateTargetMethod(ExecutableElement method, AnnotationHandle annotation, AliasedElementName name, String type,
boolean overwrite, boolean merge) {
String signature = TypeUtils.getJavaSignature(method);
for (TypeHandle target : this.mixin.getTargets()) {
@@ -389,31 +400,47 @@ abstract class AnnotatedMixinElementHandler {
// Find method as-is
MethodHandle targetMethod = target.findMethod(method);
if (targetMethod != null) {
continue;
}
if (!name.baseName().equals(name.elementName())) {
// Find method without prefix
// Find method without prefix
if (targetMethod == null && name.hasPrefix()) {
targetMethod = target.findMethod(name.baseName(), signature);
if (targetMethod != null) {
continue;
}
}
// Check aliases
for (String alias : name.getAliases()) {
if ((targetMethod = target.findMethod(alias, signature)) != null) {
break;
if (targetMethod == null && name.hasAliases()) {
for (String alias : name.getAliases()) {
if ((targetMethod = target.findMethod(alias, signature)) != null) {
break;
}
}
}
if (targetMethod == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation.asMirror());
if (targetMethod != null) {
if (overwrite) {
this.validateMethodVisibility(method, annotation, type, target, targetMethod);
}
} else if (!merge) {
this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation);
}
}
}
private void validateMethodVisibility(ExecutableElement method, AnnotationHandle annotation, String type, TypeHandle target,
MethodHandle targetMethod) {
Visibility visTarget = targetMethod.getVisibility();
if (visTarget == null) {
return;
}
Visibility visMethod = TypeUtils.getVisibility(method);
String visibility = "visibility of " + visTarget + " method in " + target;
if (visTarget.ordinal() > visMethod.ordinal()) {
this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation);
} else if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > visTarget.ordinal()) {
this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation);
}
}
/**
* Checks whether the specified field exists in all targets and raises
* warnings where appropriate
@@ -465,6 +492,14 @@ abstract class AnnotatedMixinElementHandler {
}
}
private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation) {
if (annotation == null) {
this.ap.printMessage(kind, msg, e);
} else {
this.ap.printMessage(kind, msg, e, annotation.asMirror());
}
}
protected static <T extends IMapping<T>> ObfuscationData<T> stripOwnerData(ObfuscationData<T> data) {
ObfuscationData<T> stripped = new ObfuscationData<T>();
for (ObfuscationType type : data) {
@@ -55,9 +55,13 @@ class AnnotatedMixinElementHandlerOverwrite extends AnnotatedMixinElementHandler
super(ap, mixin);
}
public void registerMerge(ExecutableElement method) {
this.validateTargetMethod(method, null, new AliasedElementName(method, AnnotationHandle.MISSING), "overwrite", true, true);
}
public void registerOverwrite(AnnotatedElementOverwrite elem) {
AliasedElementName name = new AliasedElementName(elem.getElement(), elem.getAnnotation());
this.validateTargetMethod(elem.getElement(), elem.getAnnotation(), name, "@Overwrite");
this.validateTargetMethod(elem.getElement(), elem.getAnnotation(), name, "@Overwrite", true, false);
this.checkConstraints(elem.getElement(), elem.getAnnotation());
if (!this.mixin.remap()) {
@@ -38,6 +38,7 @@ import java.util.regex.Pattern;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
@@ -472,13 +473,13 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
/**
* Called from each AP when a pass is completed
*/
public void onPassCompleted() {
public void onPassCompleted(RoundEnvironment roundEnv) {
if (!"true".equalsIgnoreCase(this.getOption(SupportedOptions.DISABLE_TARGET_EXPORT))) {
this.targets.write(true);
}
for (AnnotatedMixin mixin : this.mixinsForPass) {
mixin.runValidators(ValidationPass.LATE, this.validators);
for (AnnotatedMixin mixin : roundEnv.processingOver() ? this.mixins.values() : this.mixinsForPass) {
mixin.runValidators(roundEnv.processingOver() ? ValidationPass.FINAL : ValidationPass.LATE, this.validators);
}
}
@@ -75,7 +75,7 @@ public abstract class MixinObfuscationProcessor extends AbstractProcessor {
}
protected void postProcess(RoundEnvironment roundEnv) {
this.mixins.onPassCompleted();
this.mixins.onPassCompleted(roundEnv);
}
@Override
@@ -66,6 +66,7 @@ public class MixinObfuscationProcessorInjection extends MixinObfuscationProcesso
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
this.postProcess(roundEnv);
return true;
}
@@ -64,6 +64,7 @@ public class MixinObfuscationProcessorTargets extends MixinObfuscationProcessor
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
this.postProcess(roundEnv);
return true;
}
@@ -42,7 +42,8 @@ public interface IMixinValidator {
*/
public enum ValidationPass {
EARLY,
LATE
LATE,
FINAL
}
/**
@@ -44,6 +44,8 @@ import com.google.common.collect.ImmutableList;
*/
public final class AnnotationHandle {
public static final AnnotationHandle MISSING = new AnnotationHandle(null);
/**
* Annotation being wrapped
*/
@@ -86,6 +86,11 @@ public class FieldHandle extends MemberHandle<MappingField> {
public VariableElement getElement() {
return this.element;
}
@Override
public Visibility getVisibility() {
return TypeUtils.getVisibility(this.element);
}
/**
* Returns true if the searched type had a type specifier but the returned
@@ -57,6 +57,11 @@ public abstract class MemberHandle<T extends IMapping<T>> {
return this.desc;
}
/**
* Get the visibility level for this member
*/
public abstract Visibility getVisibility();
/**
* Return this handle as a mapping
*
@@ -46,7 +46,7 @@ public class MethodHandle extends MemberHandle<MappingMethod> {
}
public MethodHandle(String owner, ExecutableElement element) {
this(owner, TypeUtils.getName(element), TypeUtils.getDescriptor(element));
this(owner, element, TypeUtils.getName(element), TypeUtils.getDescriptor(element));
}
protected MethodHandle(String owner, String name, String desc) {
@@ -71,6 +71,11 @@ public class MethodHandle extends MemberHandle<MappingMethod> {
public ExecutableElement getElement() {
return this.element;
}
@Override
public Visibility getVisibility() {
return TypeUtils.getVisibility(this.element);
}
@Override
public MappingMethod asMapping(boolean includeOwner) {
@@ -27,6 +27,7 @@ package org.spongepowered.tools.obfuscation.mirror;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
@@ -372,4 +373,27 @@ public abstract class TypeUtils {
return processingEnv.getElementUtils().getTypeElement(((TypeElement)targetType.asElement()).getQualifiedName()).asType();
}
/**
* Get the ordinal visibility for the specified element
*
* @param element element to inspect
* @return visibility level or null if element is null
*/
public static Visibility getVisibility(Element element) {
if (element == null) {
return null;
}
for (Modifier modifier : element.getModifiers()) {
switch (modifier) {
case PUBLIC: return Visibility.PUBLIC;
case PROTECTED: return Visibility.PROTECTED;
case PRIVATE: return Visibility.PRIVATE;
default: break;
}
}
return Visibility.PACKAGE;
}
}
@@ -0,0 +1,38 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.mirror;
/**
* Ordinal member visibility level. This is used to represent visibility of
* a member in a formal way from lowest to highest.
*/
public enum Visibility {
PRIVATE,
PROTECTED,
PACKAGE,
PUBLIC
}
@@ -62,7 +62,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.6.12";
public static final String VERSION = "0.6.13";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
@@ -45,7 +45,6 @@ public class ModifyArgsInjector extends InvokeInjector {
/**
* @param info Injection info
* @param index target arg index
*/
public ModifyArgsInjector(InjectionInfo info) {
super(info, "@ModifyArgs");
@@ -0,0 +1,118 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
/**
* Base for class context objects
*/
abstract class ClassContext {
/**
* Methods in the this class which have been upgraded from
* <tt>private</tt> to either <tt>protected</tt> or <tt>public</tt> and
* therefore require the invocation opcode to be upgraded from INVOKESPECIAL
* to INVOKEVIRTUAL.
*/
private final Set<Method> upgradedMethods = new HashSet<Method>();
/**
* Get the internal class name
*
* @return class reference
*/
abstract String getClassRef();
/**
* Get the class tree for this context
*
* @return tree
*/
abstract ClassNode getClassNode();
/**
* Get the meta class for this context
*
* @return ClassInfo
*/
abstract ClassInfo getClassInfo();
/**
* Add a method to this context which is private in the Mixin but has higher
* visibility in the target class.
*
* @param method method to add
*/
void addUpgradedMethod(MethodNode method) {
Method md = this.getClassInfo().findMethod(method);
if (md == null) {
// wat
throw new IllegalStateException("Meta method for " + method.name + " not located in " + this);
}
this.upgradedMethods.add(md);
}
protected void upgradeMethods() {
for (MethodNode method : this.getClassNode().methods) {
this.upgradeMethod(method);
}
}
private void upgradeMethod(MethodNode method) {
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (!(insn instanceof MethodInsnNode)) {
continue;
}
MemberRef methodRef = new MemberRef.Method((MethodInsnNode)insn);
if (methodRef.getOwner().equals(this.getClassRef())) {
Method md = this.getClassInfo().findMethod(methodRef.getName(), methodRef.getDesc(), ClassInfo.INCLUDE_ALL);
this.upgradeMethodRef(method, methodRef, md);
}
}
}
protected void upgradeMethodRef(MethodNode containingMethod, MemberRef methodRef, Method method) {
if (methodRef.getOpcode() != Opcodes.INVOKESPECIAL) {
return;
}
if (this.upgradedMethods.contains(method)) {
methodRef.setOpcode(Opcodes.INVOKEVIRTUAL);
}
}
}
@@ -42,6 +42,8 @@ public abstract class MemberRef {
* A static reference to a method backed by an invoke instruction
*/
public static final class Method extends MemberRef {
private static final int OPCODES = Opcodes.INVOKEVIRTUAL | Opcodes.INVOKESPECIAL | Opcodes.INVOKESTATIC | Opcodes.INVOKEINTERFACE;
/**
* Method invocation instruction
@@ -66,6 +68,15 @@ public abstract class MemberRef {
public int getOpcode() {
return this.insn.getOpcode();
}
@Override
public void setOpcode(int opcode) {
if ((opcode | Method.OPCODES) == 0) {
throw new IllegalArgumentException("Invalid opcode for method instruction: 0x" + Integer.toHexString(opcode));
}
this.insn.setOpcode(opcode);
}
@Override
public String getOwner() {
@@ -102,6 +113,8 @@ public abstract class MemberRef {
* A static reference to a field backed by field get/put instruction
*/
public static final class Field extends MemberRef {
private static final int OPCODES = Opcodes.GETSTATIC | Opcodes.PUTSTATIC | Opcodes.GETFIELD | Opcodes.PUTFIELD;
/**
* Field accessor instruction
@@ -126,6 +139,15 @@ public abstract class MemberRef {
public int getOpcode() {
return this.insn.getOpcode();
}
@Override
public void setOpcode(int opcode) {
if ((opcode | Field.OPCODES) == 0) {
throw new IllegalArgumentException("Invalid opcode for field instruction: 0x" + Integer.toHexString(opcode));
}
this.insn.setOpcode(opcode);
}
@Override
public String getOwner() {
@@ -206,27 +228,20 @@ public abstract class MemberRef {
@Override
public int getOpcode() {
switch (this.handle.getTag()) {
case Opcodes.H_INVOKEVIRTUAL:
return Opcodes.INVOKEVIRTUAL;
case Opcodes.H_INVOKESTATIC:
return Opcodes.INVOKESTATIC;
case Opcodes.H_INVOKEINTERFACE:
return Opcodes.INVOKEINTERFACE;
case Opcodes.H_INVOKESPECIAL:
case Opcodes.H_NEWINVOKESPECIAL:
return Opcodes.INVOKESPECIAL;
case Opcodes.H_GETFIELD:
return Opcodes.GETFIELD;
case Opcodes.H_GETSTATIC:
return Opcodes.GETSTATIC;
case Opcodes.H_PUTFIELD:
return Opcodes.PUTFIELD;
case Opcodes.H_PUTSTATIC:
return Opcodes.PUTSTATIC;
default:
throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
int opcode = MemberRef.opcodeFromTag(this.handle.getTag());
if (opcode == 0) {
throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
}
return opcode;
}
@Override
public void setOpcode(int opcode) {
int tag = MemberRef.tagFromOpcode(opcode);
if (tag == 0) {
throw new MixinTransformerError("Invalid opcode " + Bytecode.getOpcodeName(opcode) + " for method handle " + this.handle + ".");
}
this.handle = new org.spongepowered.asm.lib.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc());
}
@Override
@@ -259,6 +274,19 @@ public abstract class MemberRef {
this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
}
}
private static final int[] H_OPCODES = {
0, // invalid
Opcodes.GETFIELD, // H_GETFIELD
Opcodes.GETSTATIC, // H_GETSTATIC
Opcodes.PUTFIELD, // H_PUTFIELD
Opcodes.PUTSTATIC, // H_PUTSTATIC
Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL
Opcodes.INVOKESTATIC, // H_INVOKESTATIC
Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL
Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL
Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE
};
/**
* Whether this member is a field.
@@ -274,6 +302,13 @@ public abstract class MemberRef {
*/
public abstract int getOpcode();
/**
* Set the opcode of the invocation.
*
* @param opcode new opcode
*/
public abstract void setOpcode(int opcode);
/**
* The internal name for the owner of this member.
*
@@ -318,8 +353,8 @@ public abstract class MemberRef {
@Override
public String toString() {
return Bytecode.getOpcodeName(this.getOpcode()) + " for "
+ this.getOwner() + "." + this.getName() + (this.isField() ? ":" : "") + this.getDesc();
String name = Bytecode.getOpcodeName(this.getOpcode());
return String.format("%s for %s.%s%s%s", name, this.getOwner(), this.getName(), this.isField() ? ":" : "", this.getDesc());
}
@Override
@@ -339,4 +374,18 @@ public abstract class MemberRef {
public int hashCode() {
return this.toString().hashCode();
}
static int opcodeFromTag(int tag) {
return (tag >= 0 && tag < MemberRef.H_OPCODES.length) ? MemberRef.H_OPCODES[tag] : 0;
}
static int tagFromOpcode(int opcode) {
for (int tag = 1; tag < MemberRef.H_OPCODES.length; tag++) {
if (MemberRef.H_OPCODES[tag] == opcode) {
return tag;
}
}
return 0;
}
}
@@ -80,6 +80,16 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
/**
* Wrapper for overwrite options
*/
static class OverwriteOptions {
@SerializedName("conformVisibility")
boolean conformAccessModifiers;
}
/**
* Callback listener for certain mixin init steps
*/
@@ -258,6 +268,12 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
@SerializedName("injectors")
private InjectorOptions injectorOptions = new InjectorOptions();
/**
* Overwrite options
*/
@SerializedName("overwrites")
private OverwriteOptions overwriteOptions = new OverwriteOptions();
/**
* Config plugin, if supplied
*/
@@ -630,6 +646,16 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
String defaultGroup = this.injectorOptions.defaultGroup;
return defaultGroup != null && !defaultGroup.isEmpty() ? defaultGroup : "default";
}
/**
* Get whether visibility levelfor overwritten methods should be conformed
* to the target class
*
* @return true if conform is enabled
*/
public boolean conformOverwriteVisibility() {
return this.overwriteOptions.conformAccessModifiers;
}
// AMS - temp
public boolean select(MixinEnvironment environment) {
@@ -242,7 +242,7 @@ class MixinPreProcessorStandard {
continue;
}
this.attachMethod(mixinMethod);
this.attachMethod(context, mixinMethod);
context.addMixinMethod(mixinMethod);
}
}
@@ -340,14 +340,7 @@ class MixinPreProcessorStandard {
+ " does not match the target");
}
if (overwrite) {
Visibility visTarget = Bytecode.getVisibility(target);
Visibility visMethod = Bytecode.getVisibility(mixinMethod);
if (visMethod.ordinal() < visTarget.ordinal()) {
throw new InvalidMixinException(this.mixin, visMethod + " " + description + " method " + mixinMethod.name + " in " + this.mixin
+ " cannot reduce visibiliy of " + visTarget + " target method");
}
}
this.conformVisibility(context, mixinMethod, description, overwrite, target);
if (!target.name.equals(mixinMethod.name)) {
if (!overwrite && (target.access & Opcodes.ACC_PRIVATE) == 0) {
@@ -360,6 +353,32 @@ class MixinPreProcessorStandard {
return true;
}
private void conformVisibility(MixinTargetContext context, MixinMethodNode mixinMethod, String type, boolean overwrite, MethodNode target) {
Visibility visTarget = Bytecode.getVisibility(target);
Visibility visMethod = Bytecode.getVisibility(mixinMethod);
if (visMethod.ordinal() >= visTarget.ordinal()) {
if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > Visibility.PRIVATE.ordinal()) {
context.getTarget().addUpgradedMethod(target);
}
return;
}
String message = String.format("%s %s method %s in %s cannot reduce visibiliy of %s target method", visMethod, type, mixinMethod.name,
this.mixin, visTarget);
if (overwrite && !this.mixin.getParent().conformOverwriteVisibility()) {
throw new InvalidMixinException(this.mixin, message);
}
if (visMethod == Visibility.PRIVATE) {
if (overwrite) {
MixinPreProcessorStandard.logger.warn("Static binding violation: {}, visibility will be upgraded.", message);
}
context.addUpgradedMethod(mixinMethod);
Bytecode.setVisibility(mixinMethod, visTarget);
}
}
protected Method getSpecialMethod(MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
this.checkMethodNotUnique(method, type);
@@ -412,7 +431,7 @@ class MixinPreProcessorStandard {
return true;
}
protected void attachMethod(MixinMethodNode mixinMethod) {
protected void attachMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
if (method == null) {
return;
@@ -422,6 +441,11 @@ class MixinPreProcessorStandard {
if (parentMethod != null && parentMethod.isRenamed()) {
mixinMethod.name = method.renameTo(parentMethod.getName());
}
MethodNode target = context.findMethod(mixinMethod, null);
if (target != null) {
this.conformVisibility(context, mixinMethod, "overwrite", true, target);
}
}
protected void attachFields(MixinTargetContext context) {
@@ -25,16 +25,8 @@
package org.spongepowered.asm.mixin.transformer;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
@@ -66,8 +58,8 @@ import org.spongepowered.asm.mixin.transformer.meta.SourceMap.File;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.obfuscation.RemapperChain;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.ClassSignature;
import org.spongepowered.asm.util.Constants;
@@ -79,7 +71,7 @@ import org.spongepowered.asm.util.Constants;
* context-sensitive operations such as re-targetting method and field accesses
* in the mixin to the appropriate members in the target class hierarchy.
*/
public class MixinTargetContext implements IMixinContext {
public class MixinTargetContext extends ClassContext implements IMixinContext {
/**
* Logger
@@ -173,10 +165,10 @@ public class MixinTargetContext implements IMixinContext {
this.mixin = mixin;
this.classNode = classNode;
this.targetClass = context;
this.targetClassInfo = ClassInfo.forName(this.targetClass.getName());
this.targetClassInfo = ClassInfo.forName(this.getTarget().getClassRef());
this.stratum = context.getSourceMap().addFile(this.classNode);
this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy();
this.detachedSuper = !this.classNode.superName.equals(this.targetClass.getClassNode().superName);
this.detachedSuper = !this.classNode.superName.equals(this.getTarget().getClassNode().superName);
this.sessionId = context.getSessionId();
this.requireVersion(classNode.version);
}
@@ -189,7 +181,7 @@ public class MixinTargetContext implements IMixinContext {
void addShadowMethod(MethodNode method) {
this.shadowMethods.add(method);
}
/**
* Add a shadow field to this mixin context, called by the preprocessor
*
@@ -211,7 +203,7 @@ public class MixinTargetContext implements IMixinContext {
}
void addMixinMethod(MethodNode method) {
this.targetClass.addMixinMethod(method);
this.getTarget().addMixinMethod(method);
}
/**
@@ -222,7 +214,7 @@ public class MixinTargetContext implements IMixinContext {
void methodMerged(MethodNode method) {
this.mergedMethods.add(method);
this.targetClassInfo.addMethod(method);
this.targetClass.methodMerged(method);
this.getTarget().methodMerged(method);
Annotations.setVisible(method, MixinMerged.class,
"mixin", this.getClassName(),
@@ -261,6 +253,7 @@ public class MixinTargetContext implements IMixinContext {
*
* @return mixin tree
*/
@Override
public ClassNode getClassNode() {
return this.classNode;
}
@@ -299,7 +292,7 @@ public class MixinTargetContext implements IMixinContext {
* mixins)
*/
public String getTargetClassRef() {
return this.targetClass.getName();
return this.getTarget().getClassRef();
}
/**
@@ -308,7 +301,7 @@ public class MixinTargetContext implements IMixinContext {
* @return the target class
*/
public ClassNode getTargetClassNode() {
return this.targetClass.getClassNode();
return this.getTarget().getClassNode();
}
/**
@@ -320,13 +313,23 @@ public class MixinTargetContext implements IMixinContext {
return this.targetClassInfo;
}
/**
* Get the class info for this class
*
* @return the local class info
*/
@Override
protected ClassInfo getClassInfo() {
return this.mixin.getClassInfo();
}
/**
* Get the signature for this mixin class
*
* @return signature
*/
public ClassSignature getSignature() {
return this.mixin.getClassInfo().getSignature();
return this.getClassInfo().getSignature();
}
/**
@@ -381,7 +384,7 @@ public class MixinTargetContext implements IMixinContext {
* @return Transformed
*/
public ClassInfo findRealType(ClassInfo mixin) {
if (mixin == this.mixin.getClassInfo()) {
if (mixin == this.getClassInfo()) {
return this.targetClassInfo;
}
@@ -443,7 +446,7 @@ public class MixinTargetContext implements IMixinContext {
Traversal.SUPER);
if (superMethod == null || !superMethod.isInjected()) {
throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no "
+ "valid method was found in superclasses of " + this.targetClass.getName());
+ "valid method was found in superclasses of " + this.getTarget().getClassName());
}
}
}
@@ -460,18 +463,20 @@ public class MixinTargetContext implements IMixinContext {
this.transformDescriptor(methodRef);
if (methodRef.getOwner().equals(this.getClassRef())) {
methodRef.setOwner(this.targetClass.getName());
Method md = this.mixin.getClassInfo().findMethod(methodRef.getName(), methodRef.getDesc(), ClassInfo.INCLUDE_ALL);
methodRef.setOwner(this.getTarget().getClassRef());
Method md = this.getClassInfo().findMethod(methodRef.getName(), methodRef.getDesc(), ClassInfo.INCLUDE_ALL);
if (md != null && md.isRenamed() && md.getOriginalName().equals(methodRef.getName()) && md.isSynthetic()) {
methodRef.setName(md.getName());
}
} else if ((this.detachedSuper || this.inheritsFromMixin)) {
this.upgradeMethodRef(method, methodRef, md);
} else if (this.detachedSuper || this.inheritsFromMixin) {
if (methodRef.getOpcode() == Opcodes.INVOKESPECIAL) {
this.updateStaticBinding(method, methodRef);
} else if (methodRef.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodRef.getOwner()).isMixin()) {
this.updateDynamicBinding(method, methodRef);
}
}
}
/**
@@ -497,9 +502,9 @@ public class MixinTargetContext implements IMixinContext {
this.transformDescriptor(fieldRef);
if (fieldRef.getOwner().equals(this.getClassRef())) {
fieldRef.setOwner(this.targetClass.getName());
fieldRef.setOwner(this.getTarget().getClassRef());
Field field = this.mixin.getClassInfo().findField(fieldRef.getName(), fieldRef.getDesc(), ClassInfo.INCLUDE_ALL);
Field field = this.getClassInfo().findField(fieldRef.getName(), fieldRef.getDesc(), ClassInfo.INCLUDE_ALL);
// Fixes a problem with Forge not remapping static field references properly
if (field != null && field.isRenamed() && field.getOriginalName().equals(fieldRef.getName()) && field.isStatic()) {
fieldRef.setName(field.getName());
@@ -508,13 +513,13 @@ public class MixinTargetContext implements IMixinContext {
ClassInfo fieldOwner = ClassInfo.forName(fieldRef.getOwner());
if (fieldOwner.isMixin()) {
ClassInfo actualOwner = this.targetClassInfo.findCorrespondingType(fieldOwner);
fieldRef.setOwner(actualOwner != null ? actualOwner.getName() : this.targetClass.getName());
fieldRef.setOwner(actualOwner != null ? actualOwner.getName() : this.getTarget().getClassRef());
}
}
}
private void checkFinal(MethodNode method, Iterator<AbstractInsnNode> iter, FieldInsnNode fieldNode) {
if (!fieldNode.owner.equals(this.targetClass.getName())) {
if (!fieldNode.owner.equals(this.getTarget().getClassRef())) {
return;
}
@@ -562,7 +567,7 @@ public class MixinTargetContext implements IMixinContext {
*/
private void transformTypeNode(MethodNode method, Iterator<AbstractInsnNode> iter, TypeInsnNode typeInsn, AbstractInsnNode lastNode) {
if (typeInsn.getOpcode() == Opcodes.CHECKCAST
&& typeInsn.desc.equals(this.targetClass.getName())
&& typeInsn.desc.equals(this.getTarget().getClassRef())
&& lastNode.getOpcode() == Opcodes.ALOAD
&& ((VarInsnNode)lastNode).var == 0) {
iter.remove();
@@ -570,7 +575,7 @@ public class MixinTargetContext implements IMixinContext {
}
if (typeInsn.desc.equals(this.getClassRef())) {
typeInsn.desc = this.targetClass.getName();
typeInsn.desc = this.getTarget().getClassRef();
}
this.transformDescriptor(typeInsn);
@@ -716,8 +721,8 @@ public class MixinTargetContext implements IMixinContext {
private void updateBinding(MethodNode method, MemberRef methodRef, Traversal traversal) {
if (Constants.CTOR.equals(method.name)
|| methodRef.getOwner().equals(this.targetClass.getName())
|| this.targetClass.getName().startsWith("<")) {
|| methodRef.getOwner().equals(this.getTarget().getClassRef())
|| this.getTarget().getClassRef().startsWith("<")) {
return;
}
@@ -843,7 +848,7 @@ public class MixinTargetContext implements IMixinContext {
*/
@Override
public Target getTargetMethod(MethodNode method) {
return this.targetClass.getTargetMethod(method);
return this.getTarget().getTargetMethod(method);
}
MethodNode findMethod(MethodNode method, AnnotationNode annotation) {
@@ -856,12 +861,12 @@ public class MixinTargetContext implements IMixinContext {
}
}
return this.targetClass.findMethod(aliases, method.desc);
return this.getTarget().findMethod(aliases, method.desc);
}
MethodNode findRemappedMethod(MethodNode method) {
RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers();
String remappedName = remapperChain.mapMethodName(this.targetClass.getName(), method.name, method.desc);
String remappedName = remapperChain.mapMethodName(this.getTarget().getClassRef(), method.name, method.desc);
if (remappedName.equals(method.name)) {
return null;
}
@@ -869,7 +874,7 @@ public class MixinTargetContext implements IMixinContext {
Deque<String> aliases = new LinkedList<String>();
aliases.add(remappedName);
return this.targetClass.findAliasedMethod(aliases, method.desc);
return this.getTarget().findAliasedMethod(aliases, method.desc);
}
FieldNode findField(FieldNode field, AnnotationNode shadow) {
@@ -882,19 +887,19 @@ public class MixinTargetContext implements IMixinContext {
}
}
return this.targetClass.findAliasedField(aliases, field.desc);
return this.getTarget().findAliasedField(aliases, field.desc);
}
FieldNode findRemappedField(FieldNode field) {
RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers();
String remappedName = remapperChain.mapFieldName(this.targetClass.getName(), field.name, field.desc);
String remappedName = remapperChain.mapFieldName(this.getTarget().getClassRef(), field.name, field.desc);
if (remappedName.equals(field.name)) {
return null;
}
Deque<String> aliases = new LinkedList<String>();
aliases.add(remappedName);
return this.targetClass.findAliasedField( aliases, field.desc);
return this.getTarget().findAliasedField( aliases, field.desc);
}
/**
@@ -1061,7 +1066,7 @@ public class MixinTargetContext implements IMixinContext {
* @return unique method name
*/
public String getUniqueName(MethodNode method, boolean preservePrefix) {
return this.targetClass.getUniqueName(method, preservePrefix);
return this.getTarget().getUniqueName(method, preservePrefix);
}
/**
@@ -1072,7 +1077,7 @@ public class MixinTargetContext implements IMixinContext {
* @return unique field name
*/
public String getUniqueName(FieldNode field) {
return this.targetClass.getUniqueName(field);
return this.getTarget().getUniqueName(field);
}
/**
@@ -1125,7 +1130,7 @@ public class MixinTargetContext implements IMixinContext {
for (AccessorInfo accessor : this.accessors) {
MethodNode generated = accessor.generate();
this.targetClass.addMixinMethod(generated);
this.getTarget().addMixinMethod(generated);
methods.add(generated);
}
@@ -50,7 +50,7 @@ import org.spongepowered.asm.util.ClassSignature;
/**
* Struct for containing target class information during mixin application
*/
class TargetClassContext {
class TargetClassContext extends ClassContext {
/**
* Logger
@@ -155,7 +155,8 @@ class TargetClassContext {
/**
* Get the internal class name
*/
String getName() {
@Override
String getClassRef() {
return this.classNode.name;
}
@@ -169,6 +170,7 @@ class TargetClassContext {
/**
* Get the class tree
*/
@Override
ClassNode getClassNode() {
return this.classNode;
}
@@ -190,6 +192,7 @@ class TargetClassContext {
/**
* Get the target class metadata
*/
@Override
ClassInfo getClassInfo() {
return this.classInfo;
}
@@ -324,8 +327,11 @@ class TargetClassContext {
throw new IllegalStateException("Mixins already applied to target class " + this.className);
}
this.applied = true;
this.createApplicator().apply(this.mixins);
this.classNode.signature = this.signature.toString();
MixinApplicatorStandard applicator = this.createApplicator();
applicator.apply(this.mixins);
this.applySignature();
this.upgradeMethods();
this.checkMerges();
}
@@ -336,6 +342,10 @@ class TargetClassContext {
return new MixinApplicatorStandard(this);
}
private void applySignature() {
this.getClassNode().signature = this.signature.toString();
}
private void checkMerges() {
for (MethodNode method : this.mixinMethods) {
if (!method.name.startsWith("<")) {
@@ -63,22 +63,30 @@ public final class Bytecode {
/**
* Members decorated with {@link Opcodes#ACC_PRIVATE}
*/
PRIVATE,
PRIVATE(Opcodes.ACC_PRIVATE),
/**
* Members decorated with {@link Opcodes#ACC_PROTECTED}
*/
PROTECTED,
PROTECTED(Opcodes.ACC_PROTECTED),
/**
* Members not decorated with any access flags
*/
PACKAGE,
PACKAGE(0),
/**
* Members decorated with {@link Opcodes#ACC_PUBLIC}
*/
PUBLIC
PUBLIC(Opcodes.ACC_PUBLIC);
static final int MASK = Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC;
final int access;
private Visibility(int access) {
this.access = access;
}
}
@@ -785,10 +793,10 @@ public final class Bytecode {
* higher value equals higher "visibility":
*
* <ol start="0">
* <li>{@link #Visibility.PRIVATE}</li>
* <li>{@link #Visibility.PROTECTED}</li>
* <li>{@link #Visibility.PACKAGE}</li>
* <li>{@link #Visibility.PUBLIC}</li>
* <li>{@link Visibility#PRIVATE}</li>
* <li>{@link Visibility#PROTECTED}</li>
* <li>{@link Visibility#PACKAGE}</li>
* <li>{@link Visibility#PUBLIC}</li>
* </ol>
*
* @param method method to get visibility for
@@ -841,6 +849,54 @@ public final class Bytecode {
return Bytecode.Visibility.PACKAGE;
}
/**
* Set the visibility of the specified member, leaving other access flags
* unchanged
*
* @param method method to change
* @param visibility new visibility
*/
public static void setVisibility(MethodNode method, Visibility visibility) {
method.access = Bytecode.setVisibility(method.access, visibility.access);
}
/**
* Set the visibility of the specified member, leaving other access flags
* unchanged
*
* @param field field to change
* @param visibility new visibility
*/
public static void setVisibility(FieldNode field, Visibility visibility) {
field.access = Bytecode.setVisibility(field.access, visibility.access);
}
/**
* Set the visibility of the specified member, leaving other access flags
* unchanged
*
* @param method method to change
* @param access new visibility
*/
public static void setVisibility(MethodNode method, int access) {
method.access = Bytecode.setVisibility(method.access, access);
}
/**
* Set the visibility of the specified member, leaving other access flags
* unchanged
*
* @param field field to change
* @param access new visibility
*/
public static void setVisibility(FieldNode field, int access) {
field.access = Bytecode.setVisibility(field.access, access);
}
private static int setVisibility(int oldAccess, int newAccess) {
return oldAccess & ~Visibility.MASK | (newAccess & Visibility.MASK);
}
/**
* Compute the largest line number found in the specified class
*
@@ -219,7 +219,7 @@ public class SignaturePrinter {
String name = typesOnly ? null : Strings.isNullOrEmpty(this.argNames[var]) ? "unnamed" + var : this.argNames[var];
this.appendType(sb, this.argTypes[var], name);
} catch (Exception ex) {
System.err.printf("\n\n>>> argTypes=%d, argNames=%d\n\n", this.argTypes.length, this.argNames.length);
// System.err.printf("\n\n>>> argTypes=%d, argNames=%d\n\n", this.argTypes.length, this.argNames.length);
throw new RuntimeException(ex);
}
}