Add java agent to reload mixin

This commit is contained in:
BenLewis committed 2015-10-20 10:53:41 +13:00
1 parent f3c4945019
commit a8558bb5f0
7 files changed
+322 -14

No files matched your search

@@ -0,0 +1,148 @@
/*
* 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.agent;
import net.minecraft.launchwrapper.Launch;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
/**
* A java agent that re-transforms a mixin's target class if the mixin has been
* redefined. This agent enables hot-swapping of mixins.
*
* This class is a singleton because it needs to conofrm to the IHotSwap interface.
*/
public class MixinAgent implements IHotSwap{
private class Transformer implements ClassFileTransformer{
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if(classBeingRedefined == null)
return null;
byte[] mixinBytecode = MixinAgent.classLoader.getOriginalBytecode(classBeingRedefined);
if(mixinBytecode != null){
List<String> targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer);
try {
for (String target:targets) {
instrumentation.retransformClasses(Launch.classLoader.findClass(target));
}
} catch (UnmodifiableClassException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return mixinBytecode;
}
return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer);
}
}
/**
* Class loader used to load mixin classes
*/
private static final MixinClassLoader classLoader = new MixinClassLoader();
/**
* Instance used to register the transformer
*/
private static Instrumentation instrumentation = null;
/**
* Instances of all agents
*/
private static List<MixinAgent> agents = new ArrayList<MixinAgent>();
private final MixinTransformer classTransformer;
/**
* Constructs an agent from a class transformer in which it will use to
* transform the class.
*
* @param classTransformer Class transformer that will transform a mixin's
* target class
*/
public MixinAgent(MixinTransformer classTransformer) {
this.classTransformer = classTransformer;
MixinAgent.agents.add(this);
if (MixinAgent.instrumentation != null)
initTransformer();
}
private void initTransformer() {
MixinAgent.instrumentation.addTransformer(new Transformer());
}
@Override
public void registerMixinClass(String name, byte[] bytecode) {
MixinAgent.classLoader.addMixinClass(name, bytecode);
}
/**
* Initialize the agents
*
* @param instrumentation Instance to use to transform the mixins
*/
public static void init(Instrumentation instrumentation) {
MixinAgent.instrumentation = instrumentation;
for (MixinAgent agent:agents) {
agent.initTransformer();
}
}
/**
* Initialize the agent
*
* This will be called automatically if the jar is in a -javaagent java
* command line argument
*
* @param arg Ignored
* @param instrumentation Instance to use to transform the mixins
*/
public static void premain(String arg, Instrumentation instrumentation){
init(instrumentation);
}
/**
* Initialize the agent
*
* This will be called automatically if the agent is loaded after jvm
* startup
*
* @param arg Ignored
* @param instrumentation Instance to use to transform the mixins
*/
public static void agentmain(String arg, Instrumentation instrumentation) {
init(instrumentation);
}
}
@@ -0,0 +1,49 @@
/*
* 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.agent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
class MixinClassLoader extends ClassLoader {
private static final Logger logger = LogManager.getLogger("mixin.agent");
private Map<Class<?>, byte[]> bytecodes = new HashMap<Class<?>, byte[]>();
void addMixinClass(String name, byte[] bytes){
logger.debug("add class "+name+" to class loader");
try {
logger.catching(e);
}
}
byte[] getOriginalBytecode(Class<?> clazz){
return this.bytecodes.get(clazz);
}
}
@@ -290,8 +290,13 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Ignore all constraints on mixin annotations, output warnings instead
*/
IGNORE_CONSTRAINTS("ignoreConstraints");
IGNORE_CONSTRAINTS("ignoreConstraints"),
/**
* Enables the hot-swap agent
*/
HOT_SWAP("hotSwap");
/**
* Prefix for mixin options
*/
@@ -46,6 +46,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.util.VersionNumber;
import com.google.gson.Gson;
@@ -274,20 +275,20 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em> methods.
* </p>
*/
void initialise() {
void initialise(IHotSwap hotSwapper) {
if (this.initialised) {
return;
}
this.initialised = true;
this.initialiseMixins(this.mixinClasses, false);
this.initialiseMixins(this.mixinClasses, false, hotSwapper);
switch (MixinEnvironment.getCurrentEnvironment().getSide()) {
case CLIENT:
this.initialiseMixins(this.mixinClassesClient, false);
this.initialiseMixins(this.mixinClassesClient, false, hotSwapper);
break;
case SERVER:
this.initialiseMixins(this.mixinClassesServer, false);
this.initialiseMixins(this.mixinClassesServer, false, hotSwapper);
break;
case UNKNOWN:
//$FALL-THROUGH$
@@ -297,10 +298,10 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
void postInitialise() {
void postInitialise(IHotSwap hotSwapper) {
if (this.plugin != null) {
List<String> pluginMixins = this.plugin.getMixins();
this.initialiseMixins(pluginMixins, true);
this.initialiseMixins(pluginMixins, true, hotSwapper);
}
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
@@ -328,7 +329,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void initialiseMixins(List<String> mixinClasses, boolean suppressPlugin) {
private void initialiseMixins(List<String> mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) {
if (mixinClasses == null) {
return;
}
@@ -349,6 +350,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.mixinsFor(targetClassName).add(mixin);
this.unhandledTargets.add(targetClassName);
}
hotSwapper.registerMixinClass(mixin.getClassName(), mixin.getClassBytes());
this.mixins.add(mixin);
}
} catch (Exception ex) {
@@ -504,6 +506,25 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
return mixins;
}
public List<String> reloadMixin(String mixinClass, byte[] bytes) {
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
MixinInfo mixin = iter.next();
if (mixin.getClassName().equals(mixinClass)) {
mixin.reloadMixin(bytes);
try {
mixin.validate();
} catch (Exception e) {
this.logger.error(e.getMessage(), e);
this.removeMixin(mixin);
iter.remove();
return Collections.<String>emptyList();
}
return mixin.getTargetClasses();
}
}
return null;
}
@Override
public String toString() {
@@ -122,7 +122,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Mixin bytes (read once, generate tree on demand)
*/
private final transient byte[] mixinBytes;
private transient byte[] mixinBytes;
/**
* Configuration plugin
@@ -539,6 +539,11 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
return mixinBytes;
}
void reloadMixin(byte[] mixinBytes) {
this.mixinBytes = mixinBytes;
this.validationClassNode = getClassNode(0);
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@@ -56,6 +56,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction;
import org.spongepowered.asm.mixin.transformer.debug.IDecompiler;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.Constants;
@@ -277,6 +278,11 @@ public class MixinTransformer extends TreeTransformer {
*/
private final IDecompiler decompiler;
/**
* Hot-Swap agent
*/
private final IHotSwap hotSwapper;
/**
* ctor
*/
@@ -294,7 +300,9 @@ public class MixinTransformer extends TreeTransformer {
TreeInfo.setLock(this.lock);
this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java"));
this.hotSwapper = this.initHotSwapper();
try {
FileUtils.deleteDirectory(this.classExportDir);
} catch (IOException ex) {
@@ -321,6 +329,26 @@ public class MixinTransformer extends TreeTransformer {
return null;
}
private IHotSwap initHotSwapper() {
if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.HOT_SWAP)) {
return null;
}
try {
this.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. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
}
/**
* Force-load all classes targetted by mixins but not yet applied
*/
@@ -404,7 +432,7 @@ public class MixinTransformer extends TreeTransformer {
if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass);
}
this.handleMixinErrorState(transformedName, th);
}
}
@@ -421,6 +449,16 @@ public class MixinTransformer extends TreeTransformer {
}
}
public List<String> reload(String mixinClass, byte[] bytes) {
if (this.lock.getDepth() > 0)
throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered");
List<String> targets = new ArrayList<String>();
for (MixinConfig config:this.configs) {
targets.addAll(config.reloadMixin(mixinClass, bytes));
}
return targets;
}
private void init(MixinEnvironment environment) {
this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG;
this.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment);
@@ -481,7 +519,7 @@ public class MixinTransformer extends TreeTransformer {
private void initConfigs() {
for (MixinConfig config : this.pendingConfigs) {
try {
config.initialise();
config.initialise(this.hotSwapper);
} catch (Exception ex) {
this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex);
}
@@ -505,7 +543,7 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.pendingConfigs) {
try {
config.postInitialise();
config.postInitialise(this.hotSwapper);
} catch (Exception ex) {
this.logger.error("Error encountered during mixin config postInit setp'" + config.getName() + "': " + ex.getMessage(), ex);
}
@@ -0,0 +1,42 @@
/*
* 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.debug;
/**
* Interface to allow the hot-swap agent to be loaded on-demand
*/
public interface IHotSwap {
/**
* Registers a mixin class with the agent.
*
* This is needed as the mixin needs to be loaded to be redefined.
*
* @param name Fully qualified name of the mixin class
* @param bytecode Bytecode of the mixin
*/
public abstract void registerMixinClass(String name, byte[] bytecode);
}