Allow static methods in accessor mixins with Java 8 and above, ver 0.6.6

This commit is contained in:
Mumfrey committed 2017-01-16 15:59:21 +00:00
1 parent 376660e8ca
commit 4e75544ca5
10 files changed
+458 -215

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.5
buildVersion=0.6.6
buildType=SNAPSHOT
@@ -62,7 +62,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.6.5";
public static final String VERSION = "0.6.6";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
@@ -107,7 +107,7 @@ public class AccessorInfo extends SpecialMethodInfo {
/**
* Pattern for matching accessor names (for inflector)
*/
protected static final Pattern PATTERN_ACCESSOR = Pattern.compile("^(get|set|is|invoke|call)(([A-Z])(.*))$");
protected static final Pattern PATTERN_ACCESSOR = Pattern.compile("^(get|set|is|invoke|call)(([A-Z])(.*?))(_\\$md.*)$");
/**
* Accessor method argument types (raw, from method)
@@ -337,7 +337,8 @@ public class AccessorInfo extends SpecialMethodInfo {
return candidates.get(0);
}
throw new InvalidAccessorException(this, "Multiple candidates were found matching " + this.target + " in " + this.classNode.name
String number = candidates.size() == 0 ? "No" : "Multiple";
throw new InvalidAccessorException(this, number + " candidates were found matching " + this.target + " in " + this.classNode.name
+ " for " + this);
}
@@ -41,10 +41,7 @@ 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;
@@ -53,7 +50,6 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.VersionNumber;
@@ -80,6 +76,27 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
/**
* Callback listener for certain mixin init steps
*/
interface IListener {
/**
* Called when a mixin has been successfully prepared
*
* @param mixin mixin which was prepared
*/
public abstract void onPrepare(MixinInfo mixin);
/**
* Called when a mixin has completed post-initialisation
*
* @param mixin mixin which completed postinit
*/
public abstract void onInit(MixinInfo mixin);
}
/**
* Global order of mixin configs, used to determine ordering between configs
* with equivalent priority
@@ -111,16 +128,6 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
private final transient List<MixinInfo> mixins = new ArrayList<MixinInfo>();
/**
* Synthetic inner classes for mixins in this set
*/
private final transient Set<String> syntheticInnerClasses = new HashSet<String>();
/**
* Accessor mixins in this set
*/
private final transient Set<String> passThroughClasses = new HashSet<String>();
/**
* Marshal
*/
@@ -218,6 +225,8 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
private final transient int order = MixinConfig.configOrder++;
private final transient List<IListener> listeners = new ArrayList<IListener>();
// /**
// * Phase selector
// */
@@ -264,7 +273,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Spawn via GSON, no public ctor for you
*/
private MixinConfig() {}
/**
* Called immediately after deserialisation
*
@@ -349,6 +358,15 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
return true;
}
/**
* Add a new listener
*
* @param listener listener to add
*/
void addListener(IListener listener) {
this.listeners.add(listener);
}
/**
* Initialise the config once it's selected
@@ -399,20 +417,20 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em> methods.
* </p>
*/
void prepare(IHotSwap hotSwapper) {
void prepare() {
if (this.prepared) {
return;
}
this.prepared = true;
this.prepareMixins(this.mixinClasses, false, hotSwapper);
this.prepareMixins(this.mixinClasses, false);
switch (this.env.getSide()) {
case CLIENT:
this.prepareMixins(this.mixinClassesClient, false, hotSwapper);
this.prepareMixins(this.mixinClassesClient, false);
break;
case SERVER:
this.prepareMixins(this.mixinClassesServer, false, hotSwapper);
this.prepareMixins(this.mixinClassesServer, false);
break;
case UNKNOWN:
//$FALL-THROUGH$
@@ -422,18 +440,18 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
void postInitialise(IHotSwap hotSwapper) {
void postInitialise() {
if (this.plugin != null) {
List<String> pluginMixins = this.plugin.getMixins();
this.prepareMixins(pluginMixins, true, hotSwapper);
this.prepareMixins(pluginMixins, true);
}
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
MixinInfo mixin = iter.next();
try {
mixin.validate();
for (String innerClass : mixin.getSyntheticInnerClasses()) {
this.syntheticInnerClasses.add(innerClass.replace('/', '.'));
for (IListener listener : this.listeners) {
listener.onInit(mixin);
}
} catch (InvalidMixinException ex) {
this.logger.error(ex.getMixin() + ": " + ex.getMessage(), ex);
@@ -457,7 +475,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void prepareMixins(List<String> mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) {
private void prepareMixins(List<String> mixinClasses, boolean suppressPlugin) {
if (mixinClasses == null) {
return;
}
@@ -480,11 +498,8 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.mixinsFor(targetClassName).add(mixin);
this.unhandledTargets.add(targetClassName);
}
if (hotSwapper != null) {
hotSwapper.registerMixinClass(mixin.getClassName());
}
if (mixin.isLoadable()) {
this.passThroughClasses.add(mixin.getClassName());
for (IListener listener : this.listeners) {
listener.onPrepare(mixin);
}
this.mixins.add(mixin);
}
@@ -683,55 +698,6 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
return className.startsWith(this.mixinPackage);
}
/**
* 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) || 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;
}
/**
* Check whether this configuration bundle has a mixin for the specified
* class
@@ -1007,9 +1007,19 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
return this.getState().isUnique();
}
/**
* True if this mixin is decorated with {@link Pseudo}
*/
public boolean isVirtual() {
return this.virtual;
}
/**
* True if the mixin class is actually class-loadable
*/
public boolean isAccessor() {
return this.type instanceof SubType.Accessor;
}
/**
* True if the mixin class is actually class-loadable
@@ -0,0 +1,217 @@
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldNode;
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.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.ASMHelper;
/**
* TODO Description for MixinPostProcessor
*/
class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListener {
/**
* Synthetic inner classes in mixins
*/
private final Set<String> syntheticInnerClasses = new HashSet<String>();
/**
* Accessor mixins
*/
private final Map<String, MixinInfo> accessorMixins = new HashMap<String, MixinInfo>();
/**
* Loadable classes within mixin packages
*/
private final Set<String> loadable = new HashSet<String>();
@Override
public void onInit(MixinInfo mixin) {
for (String innerClass : mixin.getSyntheticInnerClasses()) {
this.registerSyntheticInner(innerClass.replace('/', '.'));
}
}
@Override
public void onPrepare(MixinInfo mixin) {
String className = mixin.getClassName();
if (mixin.isLoadable()) {
this.registerLoadable(className);
}
if (mixin.isAccessor()) {
this.registerAccessor(mixin);
}
}
void registerSyntheticInner(String className) {
this.syntheticInnerClasses.add(className);
}
void registerLoadable(String className) {
this.loadable.add(className);
}
void registerAccessor(MixinInfo mixin) {
this.registerLoadable(mixin.getClassName());
this.accessorMixins.put(mixin.getClassName(), mixin);
}
/**
* Get whether the specified class can be piped through the postprocessor
* rather than being classloaded normally
*
* @param className Class name to check
* @return True if the specified class name has been registered for post-
* processing
*/
boolean canTransform(String className) {
return this.syntheticInnerClasses.contains(className) || this.loadable.contains(className);
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.IClassTransformer
* #transform(java.lang.String, java.lang.String, byte[])
*/
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
if (this.syntheticInnerClasses.contains(transformedName)) {
return this.processSyntheticInner(bytes);
}
if (this.accessorMixins.containsKey(transformedName)) {
MixinInfo mixin = this.accessorMixins.get(transformedName);
return this.processAccessor(bytes, mixin);
}
return bytes;
}
/**
* "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
*/
private byte[] processSyntheticInner(byte[] bytes) {
ClassNode classNode = this.readClass(bytes, true);
// 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 this.writeClass(classNode);
}
private byte[] processAccessor(byte[] bytes, MixinInfo mixin) {
if (!MixinEnvironment.getCompatibilityLevel().isAtLeast(CompatibilityLevel.JAVA_8)) {
return bytes;
}
boolean transformed = false;
MixinClassNode classNode = mixin.getClassNode(0);
ClassInfo targetClass = mixin.getTargets().get(0);
for (Iterator<MixinMethodNode> iter = classNode.mixinMethods.iterator(); iter.hasNext();) {
MixinMethodNode methodNode = iter.next();
if (!ASMHelper.hasFlag(methodNode, Opcodes.ACC_STATIC)) {
continue;
}
AnnotationNode accessor = methodNode.getVisibleAnnotation(Accessor.class);
AnnotationNode invoker = methodNode.getVisibleAnnotation(Invoker.class);
if (accessor != null || invoker != null) {
Method method = MixinPostProcessor.getAccessorMethod(mixin, methodNode, targetClass);
MixinPostProcessor.createProxy(methodNode, targetClass, method);
transformed = true;
}
}
if (transformed) {
return this.writeClass(classNode);
}
return bytes;
}
private static Method getAccessorMethod(MixinInfo mixin, MethodNode methodNode, ClassInfo targetClass) throws MixinTransformerError {
Method method = mixin.getClassInfo().findMethod(methodNode, ClassInfo.INCLUDE_ALL);
// Normally the target will be renamed when the mixin is conformed to the target, if we get here
// without this happening then we will end up invoking an undecorated method, which is bad!
if (!method.isRenamed()) {
throw new MixinTransformerError("Unexpected state: " + mixin + " loaded before " + targetClass + " was conformed");
}
return method;
}
private static void createProxy(MethodNode methodNode, ClassInfo targetClass, Method method) {
methodNode.instructions.clear();
Type[] args = Type.getArgumentTypes(methodNode.desc);
Type returnType = Type.getReturnType(methodNode.desc);
ASMHelper.loadArgs(args, methodNode.instructions, 0);
methodNode.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, targetClass.getName(), method.getName(), methodNode.desc, false));
methodNode.instructions.add(new InsnNode(returnType.getOpcode(Opcodes.IRETURN)));
methodNode.maxStack = ASMHelper.getFirstNonArgLocalIndex(args, false);
methodNode.maxLocals = 0;
}
}
@@ -37,6 +37,7 @@ import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
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;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
@@ -89,6 +90,8 @@ class MixinPreProcessorStandard {
*/
protected final MixinClassNode classNode;
protected final MixinEnvironment env;
private final boolean verboseLogging, strictUnique;
private boolean prepared, attached;
@@ -96,9 +99,9 @@ class MixinPreProcessorStandard {
MixinPreProcessorStandard(MixinInfo mixin, MixinClassNode classNode) {
this.mixin = mixin;
this.classNode = classNode;
MixinEnvironment env = mixin.getParent().getEnvironment();
this.verboseLogging = env.getOption(Option.DEBUG_VERBOSE);
this.strictUnique = env.getOption(Option.DEBUG_UNIQUE);
this.env = mixin.getParent().getEnvironment();
this.verboseLogging = this.env.getOption(Option.DEBUG_VERBOSE);
this.strictUnique = this.env.getOption(Option.DEBUG_UNIQUE);
}
/**
@@ -251,19 +254,32 @@ class MixinPreProcessorStandard {
return this.attachAccessorMethod(context, mixinMethod, Accessor.class) || this.attachAccessorMethod(context, mixinMethod, Invoker.class);
}
private boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
protected boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
AnnotationNode annotation = mixinMethod.getVisibleAnnotation(type);
if (annotation == null) {
return false;
}
String description = "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name;
Method method = this.getSpecialMethod(mixinMethod, type);
if (!method.isAbstract()) {
throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " is not abstract");
}
if (MixinEnvironment.getCompatibilityLevel().isAtLeast(CompatibilityLevel.JAVA_8) && method.isStatic()) {
if (this.mixin.getTargets().size() > 1) {
throw new InvalidAccessorException(context, description + " in multi-target mixin is invalid. Mixin must have exactly 1 target.");
}
String uniqueName = context.getUniqueName(mixinMethod, true);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique method {}{} to {} in {}",
mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = method.renameTo(uniqueName);
if (method.isStatic()) {
throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be static");
} else {
if (!method.isAbstract()) {
throw new InvalidAccessorException(context, description + " is not abstract");
}
if (method.isStatic()) {
throw new InvalidAccessorException(context, description + " cannot be static");
}
}
context.addAccessorMethod(mixinMethod, type);
@@ -356,7 +372,7 @@ class MixinPreProcessorStandard {
}
if ((mixinMethod.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0) {
String uniqueName = context.getUniqueName(mixinMethod);
String uniqueName = context.getUniqueName(mixinMethod, false);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique method {}{} to {} in {}",
mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = method.renameTo(uniqueName);
@@ -159,7 +159,6 @@ public class MixinTargetContext implements IReferenceMapperContext {
*/
private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion();
/**
* ctor
*
@@ -1006,8 +1005,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.mixin.postApply(transformedName, targetClass);
}
public String getUniqueName(MethodNode method) {
return this.targetClass.getUniqueName(method);
public String getUniqueName(MethodNode method, boolean preservePrefix) {
return this.targetClass.getUniqueName(method, preservePrefix);
}
public String getUniqueName(FieldNode field) {
@@ -57,6 +57,7 @@ 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.transformer.MixinConfig.IListener;
import org.spongepowered.asm.mixin.transformer.MixinTransformerModuleCheckClass.ValidationFailedException;
import org.spongepowered.asm.mixin.transformer.debug.IDecompiler;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
@@ -296,12 +297,97 @@ public class MixinTransformer extends TreeTransformer {
}
}
/**
* Debug exporter
*/
static class Exporter {
/**
* Directory to export classes to when debug.export is enabled
*/
private final File classExportDir = new File(MixinTransformer.DEBUG_OUTPUT, "class");
/**
* Runtime decompiler for exported classes
*/
private final IDecompiler decompiler;
Exporter() {
this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java"));
try {
FileUtils.deleteDirectory(this.classExportDir);
} catch (IOException ex) {
MixinTransformer.logger.warn("Error cleaning class output directory: {}", ex.getMessage());
}
}
private IDecompiler initDecompiler(File outputPath) {
MixinEnvironment env = MixinEnvironment.getCurrentEnvironment();
if (!env.getOption(Option.DEBUG_EXPORT_DECOMPILE)) {
return null;
}
try {
boolean as = env.getOption(Option.DEBUG_EXPORT_DECOMPILE_THREADED);
MixinTransformer.logger.info("Attempting to load Fernflower decompiler{}", as ? " (Threaded mode)" : "");
String className = "org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler" + (as ? "Async" : "");
@SuppressWarnings("unchecked")
Class<? extends IDecompiler> clazz =
(Class<? extends IDecompiler>)Class.forName(className);
Constructor<? extends IDecompiler> ctor = clazz.getDeclaredConstructor(File.class);
IDecompiler decompiler = ctor.newInstance(outputPath);
MixinTransformer.logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled{}",
as ? " in a separate thread" : "");
return decompiler;
} catch (Throwable th) {
MixinTransformer.logger.info("Fernflower could not be loaded, exported classes will not be decompiled. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
}
private String prepareFilter(String filter) {
filter = "^\\Q" + filter.replace("**", "\201").replace("*", "\202").replace("?", "\203") + "\\E$";
return filter.replace("\201", "\\E.*\\Q").replace("\202", "\\E[^\\.]+\\Q").replace("\203", "\\E.\\Q").replace("\\Q\\E", "");
}
private boolean applyFilter(String filter, String subject) {
return Pattern.compile(this.prepareFilter(filter), Pattern.CASE_INSENSITIVE).matcher(subject).matches();
}
void export(String transformedName, boolean force, byte[] bytes) {
// Export transformed class for debugging purposes
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
if (force || environment.getOption(Option.DEBUG_EXPORT)) {
String filter = environment.getOptionValue(Option.DEBUG_EXPORT_FILTER);
if (force || filter == null || this.applyFilter(filter, transformedName)) {
File outputFile = this.dumpClass(transformedName.replace('.', '/'), bytes);
if (this.decompiler != null) {
this.decompiler.decompile(outputFile);
}
}
}
}
File dumpClass(String fileName, byte[] bytes) {
File outputFile = new File(this.classExportDir, fileName + ".class");
try {
FileUtils.writeByteArrayToFile(outputFile, bytes);
} catch (IOException ex) {
// don't care
}
return outputFile;
}
}
static final File DEBUG_OUTPUT = new File(Constants.DEBUG_OUTPUT_PATH);
/**
* Log all the things
*/
private final Logger logger = LogManager.getLogger("mixin");
static final Logger logger = LogManager.getLogger("mixin");
/**
* All mixin configuration bundles
@@ -317,11 +403,6 @@ public class MixinTransformer extends TreeTransformer {
* Transformer modules
*/
private final List<IMixinTransformerModule> modules = new ArrayList<IMixinTransformerModule>();
/**
* Current environment
*/
private MixinEnvironment currentEnvironment;
/**
* Re-entrance detector
@@ -334,7 +415,27 @@ public class MixinTransformer extends TreeTransformer {
* circumvent mixin application
*/
private final String sessionId = UUID.randomUUID().toString();
/**
* Export manager
*/
private final Exporter exporter;
/**
* Hot-Swap agent
*/
private final IHotSwap hotSwapper;
/**
* Postprocessor for passthrough
*/
private final MixinPostProcessor postProcessor;
/**
* Current environment
*/
private MixinEnvironment currentEnvironment;
/**
* Logging level for verbose messages
*/
@@ -344,21 +445,6 @@ public class MixinTransformer extends TreeTransformer {
* Handling an error state, do not process further mixins
*/
private boolean errorState = false;
/**
* Directory to export classes to when debug.export is enabled
*/
private final File classExportDir = new File(MixinTransformer.DEBUG_OUTPUT, "class");
/**
* Runtime decompiler for exported classes
*/
private final IDecompiler decompiler;
/**
* Hot-Swap agent
*/
private final IHotSwap hotSwapper;
/**
* ctor
@@ -376,38 +462,9 @@ public class MixinTransformer extends TreeTransformer {
TreeInfo.setLock(this.lock);
this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java"));
this.exporter = new Exporter();
this.hotSwapper = this.initHotSwapper();
try {
FileUtils.deleteDirectory(this.classExportDir);
} catch (IOException ex) {
this.logger.warn("Error cleaning class output directory: {}", ex.getMessage());
}
}
private IDecompiler initDecompiler(File outputPath) {
MixinEnvironment env = MixinEnvironment.getCurrentEnvironment();
if (!env.getOption(Option.DEBUG_EXPORT_DECOMPILE)) {
return null;
}
try {
boolean as = env.getOption(Option.DEBUG_EXPORT_DECOMPILE_THREADED);
this.logger.info("Attempting to load Fernflower decompiler{}", as ? " (Threaded mode)" : "");
@SuppressWarnings("unchecked")
Class<? extends IDecompiler> clazz =
(Class<? extends IDecompiler>)Class.forName("org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler" + (as ? "Async" : ""));
Constructor<? extends IDecompiler> ctor = clazz.getDeclaredConstructor(File.class);
IDecompiler decompiler = ctor.newInstance(outputPath);
this.logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled{}",
as ? " in a separate thread" : "");
return decompiler;
} catch (Throwable th) {
this.logger.info("Fernflower could not be loaded, exported classes will not be decompiled. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
this.postProcessor = new MixinPostProcessor();
}
private IHotSwap initHotSwapper() {
@@ -416,14 +473,14 @@ public class MixinTransformer extends TreeTransformer {
}
try {
this.logger.info("Attempting to load Hot-Swap agent");
MixinTransformer.logger.info("Attempting to load Hot-Swap agent");
@SuppressWarnings("unchecked")
Class<? extends IHotSwap> clazz =
(Class<? extends IHotSwap>)Class.forName("org.spongepowered.tools.agent.MixinAgent");
Constructor<? extends IHotSwap> ctor = clazz.getDeclaredConstructor(MixinTransformer.class);
return ctor.newInstance(this);
} catch (Throwable th) {
this.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}",
MixinTransformer.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
@@ -483,14 +540,17 @@ public class MixinTransformer extends TreeTransformer {
}
try {
if (this.postProcessor.canTransform(transformedName)) {
byte[] bytes = this.postProcessor.transform(name, transformedName, basicClass);
this.exporter.export(transformedName, false, bytes);
return bytes;
}
SortedSet<MixinInfo> mixins = null;
boolean invalidRef = false;
for (MixinConfig config : this.configs) {
if (config.packageMatch(transformedName)) {
if (config.canPassThrough(transformedName)) {
return this.passThrough(config, name, transformedName, basicClass);
}
invalidRef = true;
continue;
}
@@ -512,7 +572,7 @@ public class MixinTransformer extends TreeTransformer {
if (mixins != null) {
// Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now
if (locked) {
this.logger.warn("Re-entrance detected, this will cause serious problems.", new MixinException());
MixinTransformer.logger.warn("Re-entrance detected, this will cause serious problems.", new MixinException());
throw new MixinApplyError("Re-entrance error.");
}
@@ -561,7 +621,7 @@ public class MixinTransformer extends TreeTransformer {
private void select(MixinEnvironment environment) {
this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG;
this.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment);
MixinTransformer.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment);
long startTime = System.currentTimeMillis();
this.selectConfigs(environment);
@@ -573,7 +633,7 @@ public class MixinTransformer extends TreeTransformer {
if (elapsedTime > 0.25D) {
String elapsed = new DecimalFormat("###0.000").format(elapsedTime);
String perMixinTime = new DecimalFormat("###0.0").format((elapsedTime / totalMixins) * 1000.0);
this.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({} msec avg.)", totalMixins, elapsed, perMixinTime);
MixinTransformer.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({} msec avg.)", totalMixins, elapsed, perMixinTime);
}
}
@@ -589,12 +649,12 @@ public class MixinTransformer extends TreeTransformer {
MixinConfig config = handle.get();
if (config.select(environment)) {
iter.remove();
this.logger.log(this.verboseLoggingLevel, "Selecting config {}", config);
MixinTransformer.logger.log(this.verboseLoggingLevel, "Selecting config {}", config);
config.onSelect();
this.pendingConfigs.add(config);
}
} catch (Exception ex) {
this.logger.warn(String.format("Failed to select mixin config: %s", handle), ex);
MixinTransformer.logger.warn(String.format("Failed to select mixin config: %s", handle), ex);
}
}
@@ -629,15 +689,32 @@ public class MixinTransformer extends TreeTransformer {
private int prepareConfigs(MixinEnvironment environment) {
int totalMixins = 0;
final IHotSwap hotSwapper = this.hotSwapper;
for (MixinConfig config : this.pendingConfigs) {
config.addListener(this.postProcessor);
if (hotSwapper != null) {
config.addListener(new IListener() {
@Override
public void onPrepare(MixinInfo mixin) {
hotSwapper.registerMixinClass(mixin.getClassName());
}
@Override
public void onInit(MixinInfo mixin) {
}
});
}
}
for (MixinConfig config : this.pendingConfigs) {
try {
this.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount());
config.prepare(this.hotSwapper);
MixinTransformer.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount());
config.prepare();
totalMixins += config.getMixinCount();
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
} catch (Exception ex) {
this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex);
String message = ex.getMessage();
MixinTransformer.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + message, ex);
}
}
@@ -659,11 +736,12 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.pendingConfigs) {
try {
config.postInitialise(this.hotSwapper);
config.postInitialise();
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
} catch (Exception ex) {
this.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + ex.getMessage(), ex);
String message = ex.getMessage();
MixinTransformer.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + message, ex);
}
}
@@ -674,21 +752,6 @@ public class MixinTransformer extends TreeTransformer {
return totalMixins;
}
/**
* 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(MixinConfig config, String name, String transformedName, byte[] basicClass) {
ClassNode classNode = config.passThrough(transformedName, this.readClass(basicClass, true));
return this.writeClass(transformedName, classNode, false);
}
/**
* Apply mixins for specified target class to the class described by the
* supplied byte array.
@@ -702,7 +765,7 @@ public class MixinTransformer extends TreeTransformer {
try {
this.postApply(context);
} catch (ValidationFailedException ex) {
this.logger.info(ex.getMessage());
MixinTransformer.logger.info(ex.getMessage());
// If verify is enabled and failed, write out the bytecode to allow us to inspect it
if (context.isExportForced() || MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT)) {
this.writeClass(context);
@@ -756,7 +819,7 @@ public class MixinTransformer extends TreeTransformer {
IMixinInfo mixin = ex.getMixin();
if (mixin == null) {
this.logger.error("InvalidMixinException has no mixin!", ex);
MixinTransformer.logger.error("InvalidMixinException has no mixin!", ex);
throw ex;
}
@@ -789,7 +852,7 @@ public class MixinTransformer extends TreeTransformer {
}
}
this.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex);
MixinTransformer.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex);
this.errorState = false;
@@ -803,7 +866,7 @@ public class MixinTransformer extends TreeTransformer {
for (String handlerClassName : Mixins.getErrorHandlerClasses()) {
try {
this.logger.info("Instancing error handler class {}", handlerClassName);
MixinTransformer.logger.info("Instancing error handler class {}", handlerClassName);
Class<?> handlerClass = Class.forName(handlerClassName, true, Launch.classLoader);
IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.newInstance();
if (handler != null) {
@@ -817,15 +880,6 @@ public class MixinTransformer extends TreeTransformer {
return handlers;
}
private String prepareFilter(String filter) {
filter = "^\\Q" + filter.replace("**", "\201").replace("*", "\202").replace("?", "\203") + "\\E$";
return filter.replace("\201", "\\E.*\\Q").replace("\202", "\\E[^\\.]+\\Q").replace("\203", "\\E.\\Q").replace("\\Q\\E", "");
}
private boolean applyFilter(String filter, String subject) {
return Pattern.compile(this.prepareFilter(filter), Pattern.CASE_INSENSITIVE).matcher(subject).matches();
}
private byte[] writeClass(TargetClassContext context) {
return this.writeClass(context.getClassName(), context.getClassNode(), context.isExportForced());
}
@@ -833,35 +887,14 @@ public class MixinTransformer extends TreeTransformer {
private byte[] writeClass(String transformedName, ClassNode targetClass, boolean forceExport) {
// Collapse tree to bytes
byte[] bytes = this.writeClass(targetClass);
// Export transformed class for debugging purposes
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
if (forceExport || environment.getOption(Option.DEBUG_EXPORT)) {
String filter = environment.getOptionValue(Option.DEBUG_EXPORT_FILTER);
if (forceExport || filter == null || this.applyFilter(filter, transformedName)) {
File outputFile = this.dumpClass(transformedName.replace('.', '/'), bytes);
if (this.decompiler != null) {
this.decompiler.decompile(outputFile);
}
}
}
this.exporter.export(transformedName, forceExport, bytes);
return bytes;
}
private void dumpClassOnFailure(String className, byte[] bytes, MixinEnvironment env) {
if (env.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(className.replace('.', '/') + ".target", bytes);
this.exporter.dumpClass(className.replace('.', '/') + ".target", bytes);
}
}
private File dumpClass(String fileName, byte[] bytes) {
File outputFile = new File(this.classExportDir, fileName + ".class");
try {
FileUtils.writeByteArrayToFile(outputFile, bytes);
} catch (IOException ex) {
// don't care
}
return outputFile;
}
}
@@ -241,9 +241,10 @@ class TargetClassContext {
return target;
}
public String getUniqueName(MethodNode method) {
public String getUniqueName(MethodNode method, boolean preservePrefix) {
String uniqueIndex = Integer.toHexString(this.nextUniqueMethodIndex++);
return String.format("md%s$%s$%s", this.sessionId.substring(30), method.name, uniqueIndex);
String pattern = preservePrefix ? "%2$s_$md$%1$s$%3$s" : "md%s$%s$%s";
return String.format(pattern, this.sessionId.substring(30), method.name, uniqueIndex);
}
public String getUniqueName(FieldNode field) {