diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 27a50530..09fcc44f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -226,7 +226,7 @@ class AnnotatedMixin { this.printMessage(Kind.ERROR, "Mixin target " + softTarget + " could not be found", this); return null; } else if (type.isPublic()) { - SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : null; + SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : SuppressedBy.PUBLIC_TARGET; this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " is public and must be specified in value", this, suppressedBy); return null; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 53827a82..6517e6c1 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; import org.spongepowered.asm.util.throwables.ConstraintViolationException; import org.spongepowered.asm.util.throwables.InvalidConstraintException; +import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; @@ -97,6 +98,10 @@ abstract class AnnotatedMixinElementHandler { messager.printMessage(kind, msg, this.element, this.annotation.asMirror()); } + public final void printMessage(IMessagerSuppressible messager, Diagnostic.Kind kind, CharSequence msg, SuppressedBy suppressedBy) { + messager.printMessage(kind, msg, this.element, this.annotation.asMirror(), suppressedBy); + } + } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index 57f46220..dce6143c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -52,6 +52,8 @@ 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.TypeUtils.Equivalency; +import org.spongepowered.tools.obfuscation.mirror.TypeUtils.EquivalencyResult; import com.google.common.base.Strings; @@ -349,11 +351,23 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } private void registerFactoryForTarget(AnnotatedElementInvoker elem, TypeHandle target) { - if (!elem.getReturnType().equals(target.getType())) { - throw new RuntimeException("Invalid Factory @Invoker return type, expected " + target.getType()); + EquivalencyResult equivalency = TypeUtils.isEquivalentType(this.ap.getProcessingEnvironment(), elem.getReturnType(), target.getType()); + if (equivalency.type != Equivalency.EQUIVALENT) { + if (equivalency.type == Equivalency.EQUIVALENT_BUT_RAW && equivalency.rawType == 1) { + elem.printMessage(this.ap, Kind.WARNING, "Raw return type for Factory @Invoker", SuppressedBy.RAW_TYPES); + } else if (equivalency.type == Equivalency.BOUNDS_MISMATCH) { + elem.printMessage(this.ap, Kind.ERROR, "Invalid Factory @Invoker return type, generic type arguments of " + target.getType() + + " are incompatible with " + elem.getReturnType() + ". " + equivalency); + return; + } else { + elem.printMessage(this.ap, Kind.ERROR, "Invalid Factory @Invoker return type, expected " + target.getType() + " but found " + + elem.getReturnType()); + return; + } } if (!elem.isStatic()) { - throw new RuntimeException("Factory @Invoker must be static"); + elem.printMessage(this.ap, Kind.ERROR, "Factory @Invoker must be static"); + return; } if (!elem.shouldRemap()) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java index b16f75d4..022c63e7 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -62,7 +62,18 @@ public enum SuppressedBy { * Suppress warnings when a mixin target specified by name is located in the * default package */ - DEFAULT_PACKAGE("default-package"); + DEFAULT_PACKAGE("default-package"), + + /** + * Suppress warnings when a mixin target is resolved by the AP as visible + * but cannot be referenced with a class literal for some reason + */ + PUBLIC_TARGET("public-target"), + + /** + * The default java "raw types" suppressions + */ + RAW_TYPES("rawtypes"); private final String token; diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java index 6e5c83ae..fcc7b2f7 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java @@ -226,7 +226,16 @@ public class TypeHandle { * Get whether the element is probably public */ public boolean isPublic() { - return this.getTargetElement() != null && this.getTargetElement().getModifiers().contains(Modifier.PUBLIC); + TypeElement targetElement = this.getTargetElement(); + if (targetElement == null || !targetElement.getModifiers().contains(Modifier.PUBLIC)) { + return false; + } + for (Element e = targetElement.getEnclosingElement(); e != null && e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) { + if (!e.getModifiers().contains(Modifier.PUBLIC)) { + return false; + } + } + return true; } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java index e9c3f3b2..0c03a2cb 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java @@ -24,20 +24,23 @@ */ package org.spongepowered.tools.obfuscation.mirror; +import java.util.List; + 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.Name; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.SignaturePrinter; @@ -45,7 +48,91 @@ import org.spongepowered.asm.util.SignaturePrinter; * Convenience functions for mirror types */ public abstract class TypeUtils { + + /** + * Result type returned by {@link TypeUtils#isEquivalentType} + */ + public enum Equivalency { + + /** + * Types are not equivalent + */ + NOT_EQUIVALENT, + + /** + * Types are equivalent, but one type is raw + */ + EQUIVALENT_BUT_RAW, + + /** + * Types are equivalent, but generic type parameters do not match + */ + BOUNDS_MISMATCH, + + /** + * Types are equivalent, any generic type parameters are also equivalent + * or both types are raw + */ + EQUIVALENT + + } + + /** + * Result bundle from a type equivalency check. See + * {@link TypeUtils#isEquivalentType} for details + */ + public static class EquivalencyResult { + + /** + * Singleton for equivalent type results + */ + static final EquivalencyResult EQUIVALENT = new EquivalencyResult(Equivalency.EQUIVALENT, "", 0); + + /** + * The equivalency result type + */ + public final Equivalency type; + + /** + * Detail string for use in user-facing error messages describing the + * nature of match failures + */ + public final String detail; + + /** + * For {@link Equivalency#EQUIVALENT_BUT_RAW} indicates which argument + * was the raw one. This should only ever have the values 0 (for not + * relevant), 1 or 2. It is up to the outer scope (the caller) to + * determine whether to warn based on the rawness of the respective + * "left" and "right" types. + */ + public final int rawType; + + EquivalencyResult(Equivalency type, String detail, int rawType) { + this.type = type; + this.detail = detail; + this.rawType = rawType; + } + + @Override + public String toString() { + return this.detail; + } + + static EquivalencyResult notEquivalent(String format, Object... args) { + return new EquivalencyResult(Equivalency.NOT_EQUIVALENT, String.format(format, args), 0); + } + static EquivalencyResult boundsMismatch(String format, Object... args) { + return new EquivalencyResult(Equivalency.BOUNDS_MISMATCH, String.format(format, args), 0); + } + + static EquivalencyResult equivalentButRaw(int rawType) { + return new EquivalencyResult(Equivalency.EQUIVALENT_BUT_RAW, String.format("Type %d is raw", rawType), rawType); + } + + } + /** * Number of times to recurse into TypeMirrors when trying to determine the * upper bound of a TYPEVAR @@ -193,7 +280,9 @@ public abstract class TypeUtils { * @return type name */ public static String getSimpleName(TypeMirror type) { - return Bytecode.getSimpleName(TypeUtils.getTypeName(type)); + String name = TypeUtils.getTypeName(type); + int pos = name.lastIndexOf('.'); + return pos > 0 ? name.substring(pos + 1) : name; } /** @@ -372,6 +461,25 @@ public abstract class TypeUtils { } return null; } + + private static String describeGenericBound(TypeMirror type) { + if (type instanceof TypeVariable) { + StringBuilder description = new StringBuilder("<"); + TypeVariable typeVar = (TypeVariable)type; + description.append(typeVar.toString()); + TypeMirror lowerBound = typeVar.getLowerBound(); + if (lowerBound.getKind() != TypeKind.NULL) { + description.append(" super ").append(lowerBound); + } + TypeMirror upperBound = typeVar.getUpperBound(); + if (upperBound.getKind() != TypeKind.NULL) { + description.append(" extends ").append(upperBound); + } + return description.append(">").toString(); + } + + return type.toString(); + } /** * Get whether the target type is assignable to the specified superclass @@ -391,9 +499,79 @@ public abstract class TypeUtils { return assignable; } + + /** + * Get whether the two supplied type mirrors represent the same type. For + * generic types the type arguments must also be equivalent in order to + * fully satisfy the equivalence condition. If one of the supplied types is + * a raw type then a relevant result indicated by EQUIVALENT_BUT_RAW + * will be returned and the caller can inspect which argument (t1 or + * t2) was raw by querying the rawType member. + * + * @param processingEnv processing environment + * @param t1 first type for comparison + * @param t2 second type for comparison + * @return true if the supplied types are equivalent + */ + public static EquivalencyResult isEquivalentType(ProcessingEnvironment processingEnv, TypeMirror t1, TypeMirror t2) { + if (t1 == null || t2 == null) { + return EquivalencyResult.notEquivalent("Invalid types supplied: %s, %s", t1, t2); + } + + if (processingEnv.getTypeUtils().isSameType(t1, t2)) { + return EquivalencyResult.EQUIVALENT; + } + + if (t1 instanceof TypeVariable && t2 instanceof TypeVariable) { + t1 = TypeUtils.getUpperBound(t1); + t2 = TypeUtils.getUpperBound(t2); + if (processingEnv.getTypeUtils().isSameType(t1, t2)) { + return EquivalencyResult.EQUIVALENT; + } + } + + if (t1 instanceof DeclaredType && t2 instanceof DeclaredType) { + DeclaredType dtT1 = (DeclaredType)t1; + DeclaredType dtT2 = (DeclaredType)t2; + TypeMirror rawT1 = TypeUtils.toRawType(processingEnv, dtT1); + TypeMirror rawT2 = TypeUtils.toRawType(processingEnv, dtT2); + if (!processingEnv.getTypeUtils().isSameType(rawT1, rawT2)) { + return EquivalencyResult.notEquivalent("Base types %s and %s are not compatible", rawT1, rawT2); + } + List argsT1 = dtT1.getTypeArguments(); + List argsT2 = dtT2.getTypeArguments(); + if (argsT1.size() != argsT2.size()) { + if (argsT1.size() == 0) { + return EquivalencyResult.equivalentButRaw(1); + } + if (argsT2.size() == 0) { + return EquivalencyResult.equivalentButRaw(2); + } + return EquivalencyResult.notEquivalent("Mismatched generic argument counts %s<[%d]> and %s<[%d]>", rawT1, argsT1.size(), rawT2, argsT2.size()); + } + + for (int arg = 0; arg < argsT1.size(); arg++) { + TypeMirror argT1 = argsT1.get(arg); + TypeMirror argT2 = argsT2.get(arg); + if (TypeUtils.isEquivalentType(processingEnv, argT1, argT2).type != Equivalency.EQUIVALENT) { + return EquivalencyResult.boundsMismatch("Generic bounds mismatch between %s and %s", + TypeUtils.describeGenericBound(argT1), TypeUtils.describeGenericBound(argT2)); + } + } + + return EquivalencyResult.EQUIVALENT; + } + + return EquivalencyResult.notEquivalent("%s and %s do not match", t1, t2); + } private static TypeMirror toRawType(ProcessingEnvironment processingEnv, DeclaredType targetType) { - return processingEnv.getElementUtils().getTypeElement(((TypeElement)targetType.asElement()).getQualifiedName()).asType(); + if (targetType.getKind() == TypeKind.INTERSECTION) { + return targetType; + } + Name qualifiedName = ((TypeElement)targetType.asElement()).getQualifiedName(); + TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(qualifiedName); + return typeElement != null ? typeElement.asType() : targetType; } /** diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java index b126e56a..ca195b70 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java @@ -139,16 +139,23 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl private boolean initInjectionState; @Override - public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { - if (!(handle instanceof ContainerHandleURI) || !super.accept(manager, handle)) { - return false; + public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) { + try { + this.clCoreModManager = MixinPlatformAgentFMLLegacy.getCoreModManagerClass(); + } catch (ClassNotFoundException ex) { + MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.", + ex.getMessage()); + return AcceptResult.INVALID; } + if (!(handle instanceof ContainerHandleURI) || super.accept(manager, handle) != AcceptResult.ACCEPTED) { + return AcceptResult.REJECTED; + } + this.file = ((ContainerHandleURI)handle).getFile(); this.fileName = this.file.getName(); this.coreModWrapper = this.initFMLCoreMod(); - - return true; + return this.coreModWrapper != null ? AcceptResult.ACCEPTED : AcceptResult.REJECTED; } /** @@ -156,14 +163,6 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl */ private ITweaker initFMLCoreMod() { try { - try { - this.clCoreModManager = MixinPlatformAgentFMLLegacy.getCoreModManagerClass(); - } catch (ClassNotFoundException ex) { - MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.", - ex.getMessage()); - return null; - } - if ("true".equalsIgnoreCase(this.handle.getAttribute(MixinPlatformAgentFMLLegacy.MFATT_FORCELOADASMOD))) { MixinPlatformAgentAbstract.logger.debug("ForceLoadAsMod was specified for {}, attempting force-load", this.fileName); this.loadAsMod(); @@ -424,7 +423,11 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl public String getSideName() { // Using this method first prevents us from accidentally loading FML // classes too early when using the tweaker in dev - for (ITweaker tweaker : GlobalProperties.>get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKS)) { + List tweakerList = GlobalProperties.>get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKS); + if (tweakerList == null) { + return null; + } + for (ITweaker tweaker : tweakerList) { if (tweaker.getClass().getName().endsWith(MixinPlatformAgentFMLLegacy.SERVER_TWEAKER_TAIL)) { return Constants.SIDE_SERVER; } else if (tweaker.getClass().getName().endsWith(MixinPlatformAgentFMLLegacy.CLIENT_TWEAKER_TAIL)) { diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java index 0aa026c8..01cbe9fc 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java @@ -39,8 +39,8 @@ public class MixinPlatformAgentLiteLoaderLegacy extends MixinPlatformAgentAbstra private static final String LITELOADER_TWEAKER_NAME = "com.mumfrey.liteloader.launch.LiteLoaderTweaker"; @Override - public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { - return false; + public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) { + return AcceptResult.REJECTED; } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java index 6f9487ae..46dd8804 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java @@ -38,6 +38,29 @@ import org.spongepowered.asm.launch.platform.container.IContainerHandle; */ public interface IMixinPlatformAgent { + /** + * Result type returned from {@link IMixinPlatformAgent#accept} + */ + public enum AcceptResult { + + /** + * The container was accepted + */ + ACCEPTED, + + /** + * The container was rejected + */ + REJECTED, + + /** + * The agent encountered an error and no further containers should be + * offered + */ + INVALID; + + } + /** * Accept and bind to a container handle. This method is called for agents * hosted by {@link MixinContainer} and the agent should react accordingly. @@ -47,11 +70,10 @@ public interface IMixinPlatformAgent { * * @param manager platform manager instance * @param handle handle to container - * @return true if this agent can accept a container of the supplied type, - * false if the agent cannot handle the container (in which case it - * will be discarded) + * @return AcceptResult representing this agent's acceptance of the supplied + * container */ - public abstract boolean accept(MixinPlatformManager manager, IContainerHandle handle); + public abstract AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle); /** * Get the phase provider for this agent diff --git a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java index 495279ac..3f9d69cf 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java @@ -28,6 +28,7 @@ import java.util.Collection; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.IConsumer; /** @@ -43,7 +44,10 @@ public interface IMixinPlatformServiceAgent extends IMixinPlatformAgent { public abstract void init(); /** - * Attempt to determine the side name from the current environment + * Attempt to determine the side name from the current environment. Return + * null if the side name cannot be determined by this agent. Return + * side name or {@link Constants#SIDE_UNKNOWN} if the agent is able to + * determine the side. */ public abstract String getSideName(); diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 4723ca00..4e6491ad 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -26,11 +26,13 @@ package org.spongepowered.asm.launch.platform; import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.GlobalProperties; +import org.spongepowered.asm.launch.platform.IMixinPlatformAgent.AcceptResult; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.service.MixinService; @@ -59,22 +61,25 @@ public class MixinContainer { public MixinContainer(MixinPlatformManager manager, IContainerHandle handle) { this.handle = handle; - for (String agentClass : MixinContainer.agentClasses) { + for (Iterator iter = MixinContainer.agentClasses.iterator(); iter.hasNext();) { + String agentClass = iter.next(); try { @SuppressWarnings("unchecked") Class clazz = (Class)Class.forName(agentClass); String simpleName = clazz.getSimpleName(); - String acceptAction = "rejected"; MixinContainer.logger.debug("Instancing new {} for {}", simpleName, this.handle); IMixinPlatformAgent agent = clazz.newInstance(); - if (agent.accept(manager, this.handle)) { + AcceptResult acceptAction = agent.accept(manager, this.handle); + if (acceptAction == AcceptResult.ACCEPTED) { this.agents.add(agent); - acceptAction = "accepted"; + } else if (acceptAction == AcceptResult.INVALID) { + iter.remove(); + continue; } - MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction, this.handle); + MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(), this.handle); } catch (InstantiationException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java index 79637f51..af49997b 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java @@ -56,10 +56,10 @@ public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent } @Override - public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) { this.manager = manager; this.handle = handle; - return true; + return AcceptResult.ACCEPTED; } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 5f0e5bce..2dbe3f0d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -33,6 +33,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.GlobalProperties; @@ -1041,7 +1042,14 @@ public final class MixinEnvironment implements ITokenProvider { return "Unknown"; } } - + + /** + * Get logging level info/debug based on verbose setting + */ + private Level getVerboseLoggingLevel() { + return this.getOption(Option.DEBUG_VERBOSE) ? Level.INFO : Level.DEBUG; + } + /** * Get the phase for this environment * @@ -1119,7 +1127,7 @@ public final class MixinEnvironment implements ITokenProvider { if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) { String providerName = provider.getClass().getName(); TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this); - MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this); + MixinEnvironment.logger.log(this.getVerboseLoggingLevel(), "Adding new token provider {} to {}", providerName, this); this.tokenProviders.add(wrapper); this.tokenProviderClasses.add(providerName); Collections.sort(this.tokenProviders); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 6933654d..133a5a84 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -35,6 +35,7 @@ import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; @@ -121,16 +122,12 @@ public class ModifyVariableInjector extends Injector { protected void sanityCheck(Target target, List injectionPoints) { super.sanityCheck(target, injectionPoints); - if (target.isStatic != this.isStatic) { - throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this); - } - int ordinal = this.discriminator.getOrdinal(); if (ordinal < -1) { throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this); } - if (this.discriminator.getIndex() == 0 && !this.isStatic) { + if (this.discriminator.getIndex() == 0 && !target.isStatic) { throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this); } } @@ -149,6 +146,8 @@ public class ModifyVariableInjector extends Injector { if (this.discriminator.printLVT()) { this.printLocals(target, context); } + + this.checkTargetForNode(target, node, RestrictTargetLevel.ALLOW_ALL); InjectorData handler = new InjectorData(target, "handler", false); this.validateParams(handler, this.returnType, this.returnType); 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 1317592e..6d1da674 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -72,10 +72,27 @@ import com.google.common.collect.ImmutableSet; */ public final class ClassInfo { + /** + * Include private members when running a member search + */ public static final int INCLUDE_PRIVATE = Opcodes.ACC_PRIVATE; + + /** + * Include static members when running a member search + */ public static final int INCLUDE_STATIC = Opcodes.ACC_STATIC; + + /** + * Include private and static members when running + * a member search + */ public static final int INCLUDE_ALL = ClassInfo.INCLUDE_PRIVATE | ClassInfo.INCLUDE_STATIC; + /** + * Include instance and class initialisers when running a method search + */ + public static final int INCLUDE_INITIALISERS = 0x40000; + /** * Search type for the findInHierarchy methods, replaces a boolean flag * which made calling code difficult to read @@ -682,9 +699,14 @@ public final class ClassInfo { * Interfaces */ private final Set interfaces; + + /** + * Constructors and initialisers in this class + */ + private final Set initialisers; /** - * Public and protected methods (instance) methods in this class + * Methods in this class */ private final Set methods; @@ -754,6 +776,9 @@ public final class ClassInfo { this.superName = null; this.outerName = null; this.isProbablyStatic = true; + this.initialisers = ImmutableSet.of( + new Method("", "()V") + ); this.methods = ImmutableSet.of( new Method("getClass", "()Ljava/lang/Class;"), new Method("hashCode", "()I"), @@ -787,6 +812,7 @@ public final class ClassInfo { try { this.name = classNode.name; this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT; + this.initialisers = new HashSet(); this.methods = new HashSet(); this.fields = new HashSet(); this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0); @@ -839,7 +865,9 @@ public final class ClassInfo { } private void addMethod(MethodNode method, boolean injected) { - if (!method.name.startsWith("<")) { + if (method.name.startsWith("<")) { + this.initialisers.add(new Method(method, injected)); + } else { this.methods.add(new Method(method, injected)); } } @@ -1740,8 +1768,8 @@ public final class ClassInfo { * @param memberType Type of member list to search * @return the field object or null if the field could not be resolved */ + @SuppressWarnings("unchecked") private M findMember(String name, String desc, int flags, Type memberType) { - @SuppressWarnings("unchecked") Set members = (Set)(memberType == Type.METHOD ? this.methods : this.fields); for (M member : members) { @@ -1749,6 +1777,14 @@ public final class ClassInfo { return member; } } + + if (memberType == Type.METHOD && (flags & ClassInfo.INCLUDE_INITIALISERS) != 0) { + for (Method ctor : this.initialisers) { + if (ctor.equals(name, desc) && ctor.matchesFlags(flags)) { + return (M)ctor; + } + } + } return null; } 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 bac4de0c..a8922b02 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -37,6 +37,7 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.ClassReader; +import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -44,6 +45,7 @@ import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InnerClassNode; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Mixin; @@ -91,6 +93,17 @@ class MixinInfo implements Comparable, IMixinInfo { public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) { super(access, name, desc, signature, exceptions, MixinInfo.this); } + + @Override + public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrapMethodHandle, Object... bootstrapMethodArguments) { + // Create a shallow copy of the bootstrap method args because the + // base implementation just passes the array by reference. This + // causes any changes applied to the cloned classnode to leak into + // the "master" ClassNode! + Object[] bsmArgs = new Object[bootstrapMethodArguments.length]; + System.arraycopy(bootstrapMethodArguments, 0, bsmArgs, 0, bootstrapMethodArguments.length); + this.instructions.add(new InvokeDynamicInsnNode(name, descriptor, bootstrapMethodHandle, bsmArgs)); + } public boolean isInjector() { return (this.getInjectorAnnotation() != null || this.isSurrogate()); 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 e87253e3..6526519e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -500,17 +500,18 @@ class MixinPreProcessorStandard { return false; } - if (method.isSynthetic()) { + boolean synthetic = method.isSynthetic(); + if (synthetic) { context.transformDescriptor(mixinMethod); method.remapTo(mixinMethod.desc); } MethodNode target = context.findMethod(mixinMethod, null); - if (target == null) { + if (target == null && !synthetic) { return false; } - String type = method.isSynthetic() ? "synthetic" : "@Unique"; + String type = synthetic ? "synthetic" : "@Unique"; if (Bytecode.getVisibility(mixinMethod).ordinal() < Visibility.PUBLIC.ordinal()) { if (method.isConformed()) { @@ -524,6 +525,10 @@ class MixinPreProcessorStandard { return false; } + if (target == null) { + return false; + } + if (this.strictUnique) { throw new InvalidMixinException(this.mixin, String.format("Method conflict, %s method %s in %s cannot overwrite %s%s in %s", type, mixinMethod.name, this.mixin, target.name, target.desc, context.getTarget())); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java index 59667d63..be9ea134 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java @@ -371,13 +371,14 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte * Process {@link Debug} annotations on the class after application */ void processDebugTasks() { + AnnotationNode classDebugAnnotation = Annotations.getVisible(this.classNode, Debug.class); + this.forceExport = classDebugAnnotation != null && Boolean.TRUE.equals(Annotations.getValue(classDebugAnnotation, "export")); + if (!this.env.getOption(Option.DEBUG_VERBOSE)) { return; } - AnnotationNode classDebugAnnotation = Annotations.getVisible(this.classNode, Debug.class); if (classDebugAnnotation != null) { - this.forceExport = Boolean.TRUE.equals(Annotations.getValue(classDebugAnnotation, "export")); if (Boolean.TRUE.equals(Annotations.getValue(classDebugAnnotation, "print"))) { Bytecode.textify(this.classNode, System.err); } diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 94d1559e..0bc9e7a2 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -429,10 +429,14 @@ public final class Bytecode { out += String.format("[%s] %d", Bytecode.getOpcodeName(node), ((VarInsnNode)node).var); } else if (node instanceof MethodInsnNode) { MethodInsnNode mth = (MethodInsnNode)node; - out += String.format("[%s] %s %s %s", Bytecode.getOpcodeName(node), mth.owner, mth.name, mth.desc); + out += String.format("[%s] %s::%s%s", Bytecode.getOpcodeName(node), mth.owner, mth.name, mth.desc); } else if (node instanceof FieldInsnNode) { FieldInsnNode fld = (FieldInsnNode)node; - out += String.format("[%s] %s %s %s", Bytecode.getOpcodeName(node), fld.owner, fld.name, fld.desc); + out += String.format("[%s] %s::%s:%s", Bytecode.getOpcodeName(node), fld.owner, fld.name, fld.desc); + } else if (node instanceof InvokeDynamicInsnNode) { + InvokeDynamicInsnNode idc = (InvokeDynamicInsnNode)node; + out += String.format("[%s] %s%s { %s %s::%s%s }", Bytecode.getOpcodeName(node), idc.name, idc.desc, + Bytecode.getOpcodeName(idc.bsm.getTag(), "H_GETFIELD", 1), idc.bsm.getOwner(), idc.bsm.getName(), idc.bsm.getDesc()); } else if (node instanceof LineNumberNode) { LineNumberNode ln = (LineNumberNode)node; out += String.format("LINE=[%d] LABEL=[%s]", ln.line, ln.start.getLabel()); diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 4a30c68b..733b57f2 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -142,7 +142,7 @@ public final class Locals { if (classInfo == null) { throw new LVTGeneratorError("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); } - Method methodInfo = classInfo.findMethod(method); + Method methodInfo = classInfo.findMethod(method, method.access | ClassInfo.INCLUDE_INITIALISERS); if (methodInfo == null) { throw new LVTGeneratorError("Could not locate method metadata for " + method.name + " generating LVT in " + classNode.name); } diff --git a/src/main/java/org/spongepowered/asm/util/asm/ASM.java b/src/main/java/org/spongepowered/asm/util/asm/ASM.java index 4ce4cfcc..5174aaa5 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/ASM.java +++ b/src/main/java/org/spongepowered/asm/util/asm/ASM.java @@ -24,8 +24,9 @@ */ package org.spongepowered.asm.util.asm; +import java.lang.reflect.Field; + import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.ClassNode; /** * Utility methods for determining ASM version and other version-specific @@ -33,57 +34,71 @@ import org.objectweb.asm.tree.ClassNode; */ public final class ASM { - @SuppressWarnings("deprecation") - private static final int[] EXPERIMENTAL_VERSIONS = { }; - private static final int[] SUPPORTED_VERSIONS = { Opcodes.ASM6, Opcodes.ASM5, Opcodes.ASM7 }; + private static int majorVersion = 5; + private static int minorVersion = 0; + private static String maxVersion = "FALLBACK"; + /** + * The detected ASM API Version + */ public static final int API_VERSION = ASM.detectVersion(); - - private static boolean experimental; - + private ASM() { } + /** + * Get the major API version + */ + public static int getApiVersionMajor() { + return ASM.majorVersion; + } + + /** + * Get the minor API version + */ + public static int getApiVersionMinor() { + return ASM.minorVersion; + } + /** * Get the ASM API version as a string (mostly for debugging and the banner) * * @return ASM API version as string */ public static String getApiVersionString() { - String suffix = ""; - if (ASM.experimental) { - int version = ASM.detectVersion(ASM.SUPPORTED_VERSIONS); - suffix = String.format("-EXPERIMENTAL (%d.%d)", ((0xFF0000 & version) >> 16), ((0xFF00 & version) >> 8)); - } - return String.format("ASM %d.%d%s", ((0xFF0000 & ASM.API_VERSION) >> 16), ((0xFF00 & ASM.API_VERSION) >> 8), suffix); + return String.format("ASM %d.%d (%s)", ASM.majorVersion, ASM.minorVersion, ASM.maxVersion); } private static int detectVersion() { - int expVersion = ASM.detectVersion(ASM.EXPERIMENTAL_VERSIONS); - if (expVersion > 0) { - ASM.experimental = true; - return expVersion; - } + int apiVersion = Opcodes.ASM4; - ASM.experimental = false; - int version = ASM.detectVersion(ASM.SUPPORTED_VERSIONS); - if (version > 0) { - return version; - } - - return Opcodes.ASM5; - } - - private static int detectVersion(int[] versions) { - for (int version : versions) { + for (Field field : Opcodes.class.getDeclaredFields()) { + if (field.getType() != Integer.TYPE || !field.getName().startsWith("ASM")) { + continue; + } + try { - new ClassNode(version).hashCode(); - return version; - } catch (IllegalArgumentException ex) { - // expected, this version is not supported + int version = field.getInt(null); + + // int patch = version & 0xFF; + int minor = (version >> 8) & 0xFF; + int major = (version >> 16) & 0xFF; + boolean experimental = ((version >> 24) & 0xFF) != 0; + + if (major >= ASM.majorVersion) { + ASM.maxVersion = field.getName(); + if (!experimental) { + apiVersion = version; + ASM.majorVersion = major; + ASM.minorVersion = minor; + } + } + } catch (ReflectiveOperationException ex) { + throw new Error(ex); } } - return 0; + + return apiVersion; } } diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java index 82fc449a..700897d5 100644 --- a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java +++ b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java @@ -53,9 +53,9 @@ public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract * org.spongepowered.asm.launch.platform.container.IContainerHandle) */ @Override - public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) { // No containers plz - return false; + return AcceptResult.REJECTED; } /* (non-Javadoc) diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java index 8280d386..398748ce 100644 --- a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java @@ -91,11 +91,7 @@ public class ModLauncherClassTracker implements IClassProcessor, IClassTracker { } } - synchronized (this.loadedClasses) { - this.loadedClasses.add(name); - } - - return Phases.NONE; + return Phases.AFTER_ONLY; } /* (non-Javadoc) @@ -106,6 +102,10 @@ public class ModLauncherClassTracker implements IClassProcessor, IClassTracker { */ @Override public boolean processClass(Phase phase, ClassNode classNode, Type classType, String reason) { + synchronized (this.loadedClasses) { + this.loadedClasses.add(classType.getClassName()); + } + return false; }