Class loading fixes for production, references SpongePowered/Sponge#133

This commit is contained in:
Mumfrey committed 2015-01-10 13:01:36 +00:00
1 parent b55b14c5ce
commit 3fd6c5fc02
8 files changed
+451 -37

No files matched your search

@@ -0,0 +1,50 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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.launch;
import net.minecraft.launchwrapper.Launch;
import org.spongepowered.asm.mixin.MixinEnvironment;
public abstract class MixinBootstrap {
public static final String VERSION = "0.1";
public static final String INIT_KEY = "mixin.initialised";
public static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin.";
public static final String TRANSFORMER_CLASS = MixinBootstrap.MIXIN_PACKAGE + "transformer.MixinTransformer";
static {
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.MIXIN_PACKAGE);
}
private MixinBootstrap() {}
public static void init() {
Launch.blackboard.put(MixinBootstrap.INIT_KEY, MixinBootstrap.VERSION);
MixinEnvironment.getCurrentEnvironment();
}
}
@@ -0,0 +1,179 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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.launch;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import org.spongepowered.asm.mixin.MixinEnvironment;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* TweakClass for running mixins in production. Being a tweaker ensures that we get injected into the AppClassLoader but does mean that we will
* need to inject the FML coremod by hand if running under FML.
*/
public class MixinTweaker implements ITweaker {
/**
* File containing this tweaker
*/
private final File container;
/**
* If running under FML, we will attempt to inject any coremod specified in the metadata, FML's CoremodManager returns an ITweaker instance
* which is the "handle" to the injected mod, we will need to proxy calls through to the wrapper. If initialisation fails (for example if we are
* not running under FML or if an FMLCorePlugin key is not specified in the metadata) then this handle will be NULL and the tweaker will attempt
* to start the Mixin subsystem automatically by looking for a MixinConfigs key in the jar metadata, this should be a comma-separated list of
* mixin config JSON file names.
*/
private final ITweaker fmlWrapper;
/**
* If FML init fails the tweaker will look for configs, if it finds any then it will set this flag to signify that it needs to inject the
* transformer
*/
private boolean injectTransformer;
/**
* Hello world
*/
public MixinTweaker() {
MixinBootstrap.init();
this.container = this.findJarFile();
this.fmlWrapper = this.initFMLCoreMod();
}
/**
* Find and return the file containing this class
*/
private File findJarFile() {
URI uri = null;
try {
uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
return uri != null ? new File(uri) : null;
}
/**
* Attempts to initialise the FML coremod (if specified in the jar metadata)
*/
private ITweaker initFMLCoreMod() {
try {
String coreModName = this.getManifestAttribute("FMLCorePlugin");
if (coreModName == null) {
return null;
}
Class<?> coreModManager = Class.forName("net.minecraftforge.fml.relauncher.CoreModManager");
Method mdLoadCoreMod = coreModManager.getDeclaredMethod("loadCoreMod", LaunchClassLoader.class, String.class, File.class);
mdLoadCoreMod.setAccessible(true);
return (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.container);
} catch (Exception ex) {
// ex.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#acceptOptions(java.util.List, java.io.File, java.io.File, java.lang.String)
*/
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
if (this.fmlWrapper == null) {
String mixinConfigs = this.getManifestAttribute("MixinConfigs");
if (mixinConfigs == null) {
return;
}
for (String config : mixinConfigs.split(",")) {
if (config.endsWith(".json")) {
this.injectTransformer = true;
MixinEnvironment.getCurrentEnvironment().addConfiguration(config);
}
}
}
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader)
*/
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
if (this.fmlWrapper != null) {
this.fmlWrapper.injectIntoClassLoader(Launch.classLoader);
} else if (this.injectTransformer) {
classLoader.registerTransformer(MixinBootstrap.TRANSFORMER_CLASS);
}
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#getLaunchTarget()
*/
@Override
public String getLaunchTarget() {
return "net.minecraft.client.main.Main";
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#getLaunchArguments()
*/
@Override
public String[] getLaunchArguments() {
return new String[]{};
}
private String getManifestAttribute(String key) {
if (this.container == null) {
return null;
}
JarFile jarFile = null;
try {
jarFile = new JarFile(this.container);
Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
return manifestAttributes.getValue(key);
} catch (IOException ex) {
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException ex) {
// this could be an issue later on :(
}
}
}
return null;
}
}
@@ -27,6 +27,8 @@ package org.spongepowered.asm.mixin;
import java.util.ArrayList;
import java.util.List;
import org.spongepowered.asm.launch.MixinBootstrap;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
@@ -36,20 +38,22 @@ import net.minecraft.launchwrapper.Launch;
*/
public class MixinEnvironment {
public static final String CONFIGS_KEY = "mixin.configs";
public static final String TRANSFORMER_KEY = "mixin.transformer";
public static final String MIXIN_TRANSFORMER_PACKAGE = "org.spongepowered.asm.mixin.transformer.";
public static final String MIXIN_TRANSFORMER_CLASS = MixinEnvironment.MIXIN_TRANSFORMER_PACKAGE + "MixinTransformer";
private static final String CONFIGS_KEY = "mixin.configs";
private static final String TRANSFORMER_KEY = "mixin.transformer";
private static MixinEnvironment env;
private MixinEnvironment() {
// Sanity check
Object version = Launch.blackboard.get(MixinBootstrap.INIT_KEY);
if (version == null || !MixinBootstrap.VERSION.equals(version)) {
throw new RuntimeException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()");
}
// Also sanity check
if (this.getClass().getClassLoader() != Launch.class.getClassLoader()) {
throw new RuntimeException("Attempted to init the mixin environment in the wrong classloader");
}
Launch.classLoader.addClassLoaderExclusion(MixinEnvironment.MIXIN_TRANSFORMER_PACKAGE);
}
/**
@@ -69,7 +73,10 @@ public class MixinEnvironment {
* Add a mixin configuration to the blackboard
*/
public MixinEnvironment addConfiguration(String config) {
this.getMixinConfigs().add(config);
List<String> configs = this.getMixinConfigs();
if (!configs.contains(config)) {
configs.add(config);
}
return this;
}
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -41,13 +42,17 @@ import com.google.common.collect.ImmutableList;
*/
class ClassInfo extends TreeInfo {
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
/**
* Loading and parsing classes is expensive, so keep a cache of all the information we generate
*/
private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>();
private static final ClassInfo OBJECT = new ClassInfo();
static {
ClassInfo.cache.put("java/lang/Object", new ClassInfo());
ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT);
}
/**
@@ -60,6 +65,11 @@ class ClassInfo extends TreeInfo {
*/
private final String superName;
/**
* Interfaces
*/
private final List<String> interfaces;
/**
* Public and protected methods (instance) methods in this class
*/
@@ -70,13 +80,18 @@ class ClassInfo extends TreeInfo {
*/
private ClassInfo superClass;
/**
* True if this is an interface
*/
private boolean isInterface;
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
*/
private ClassInfo() {
this.name = "java/lang/Object";
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.methods = ImmutableList.<String>of (
this.methods = ImmutableList.<String>of(
"getClass()Ljava/lang/Class;",
"hashCode()I",
"equals(Ljava/lang/Object;)Z",
@@ -89,6 +104,8 @@ class ClassInfo extends TreeInfo {
"wait()V",
"finalize()V"
);
this.isInterface = false;
this.interfaces = Collections.<String>emptyList();
}
/**
@@ -97,13 +114,11 @@ class ClassInfo extends TreeInfo {
* @param classNode Class node to inspect
*/
private ClassInfo(ClassNode classNode) {
if ((classNode.access & Opcodes.ACC_INTERFACE) != 0) {
throw new RuntimeException("Unexpected hierarchy: " + classNode.name + " is an interface");
}
this.name = classNode.name;
this.superName = classNode.superName;
this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT;
this.methods = new ArrayList<String>();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = Collections.unmodifiableList(classNode.interfaces);
for (MethodNode method : classNode.methods) {
if (!method.name.startsWith("<")
@@ -114,6 +129,20 @@ class ClassInfo extends TreeInfo {
}
}
/**
* Get whether this is an interface or not
*/
public boolean isInterface() {
return this.isInterface;
}
/**
* Returns the answer to life, the universe and everything
*/
public List<String> getInterfaces() {
return this.interfaces;
}
/**
* Get the class name (binary name)
*/
@@ -145,7 +174,7 @@ class ClassInfo extends TreeInfo {
* @return true if the specified class appears in the class's hierarchy anywhere
*/
public boolean hasSuperClass(String superClass) {
if ("java/lang/Object".equals(superClass)) {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
return true;
}
@@ -160,6 +189,23 @@ class ClassInfo extends TreeInfo {
return false;
}
public boolean isAssignableFrom(ClassInfo superClass) {
if (ClassInfo.OBJECT == superClass) {
return true;
}
ClassInfo superClassInfo = this.getSuperClass();
while (superClassInfo != null) {
if (superClass == superClassInfo) {
return true;
}
superClassInfo = superClassInfo.getSuperClass();
}
return false;
}
/**
* Finds the owner of the specified private or protected method in this class's hierarchy
@@ -192,7 +238,7 @@ class ClassInfo extends TreeInfo {
public boolean hasMethod(String name, String desc) {
return this.methods.contains(name + desc);
}
/**
* Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for the class was already defined, then the original ClassInfo is
* returned from the internal cache. Otherwise a new ClassInfo is created and returned.
@@ -0,0 +1,74 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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 org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
/**
* ClassWriter which resolves common superclasses using Mixin's metadata instead of calling Class.forName
*/
public class MixinClassWriter extends ClassWriter {
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
public MixinClassWriter(int flags) {
super(flags);
}
public MixinClassWriter(ClassReader classReader, int flags) {
super(classReader, flags);
}
/* (non-Javadoc)
* @see org.objectweb.asm.ClassWriter#getCommonSuperClass(java.lang.String, java.lang.String)
*/
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
ClassInfo c = ClassInfo.forName(type1);
ClassInfo d = ClassInfo.forName(type2);
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return MixinClassWriter.JAVA_LANG_OBJECT;
}
do {
c = c.getSuperClass();
if (c == null) {
return MixinClassWriter.JAVA_LANG_OBJECT;
}
} while (!c.isAssignableFrom(d));
return c.getName();
}
}
@@ -30,6 +30,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.launchwrapper.Launch;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import com.google.gson.Gson;
@@ -85,6 +87,23 @@ class MixinConfig {
*/
private MixinConfig() {}
/**
* Called immediately after deserialisation
*/
private void onLoad() {
if (!this.mixinPackage.endsWith(".")) {
this.mixinPackage += ".";
}
Launch.classLoader.addClassLoaderExclusion(this.mixinPackage);
if (this.refMapperConfig == null) {
this.refMapperConfig = ReferenceMapper.DEFAULT_RESOURCE;
}
this.refMapper = ReferenceMapper.read(this.refMapperConfig);
}
/**
* <p>Initialisation routine. It's important that we call this routine as late as possible. In general we want to call it on the first call to
* transform() in the parent transformer. At the very least we want to be called <em>after</em> all the transformers for the current environment
@@ -97,26 +116,16 @@ class MixinConfig {
private void initialise() {
this.initialised = true;
if (!this.mixinPackage.endsWith(".")) {
this.mixinPackage += ".";
}
for (String mixinClass : this.mixinClasses) {
try {
MixinInfo mixin = new MixinInfo(this, mixinClass, true);
for (String targetClass : mixin.getTargetClasses()) {
this.getMixinsFor(targetClass).add(mixin);
this.mixinsFor(targetClass).add(mixin);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (this.refMapperConfig == null) {
this.refMapperConfig = ReferenceMapper.DEFAULT_RESOURCE;
}
this.refMapper = ReferenceMapper.read(this.refMapperConfig);
}
/**
@@ -172,6 +181,10 @@ class MixinConfig {
this.initialise();
}
return this.mixinsFor(targetClass);
}
private List<MixinInfo> mixinsFor(String targetClass) {
List<MixinInfo> mixins = this.mixinMapping.get(targetClass);
if (mixins == null) {
mixins = new ArrayList<MixinInfo>();
@@ -188,7 +201,9 @@ class MixinConfig {
*/
static MixinConfig create(String configFile) {
try {
return new Gson().fromJson(new InputStreamReader(MixinConfig.class.getResourceAsStream("/" + configFile)), MixinConfig.class);
MixinConfig config = new Gson().fromJson(new InputStreamReader(MixinConfig.class.getResourceAsStream("/" + configFile)), MixinConfig.class);
config.onLoad();
return config;
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException(String.format("The specified configuration file '%s' was invalid or could not be read", configFile));
@@ -25,19 +25,33 @@
package org.spongepowered.asm.mixin.transformer;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLClassLoader;
import java.util.List;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.IOUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
/**
* Base class for "info" objects which use ASM tree API to do stuff, with things
*/
abstract class TreeInfo {
private static IClassNameTransformer nameTransformer;
static {
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
TreeInfo.nameTransformer = (IClassNameTransformer) transformer;
}
}
}
static ClassNode getClassNode(String className) throws ClassNotFoundException, IOException {
return TreeInfo.getClassNode(TreeInfo.loadClass(className, true), 0);
}
@@ -75,12 +89,26 @@ abstract class TreeInfo {
}
/**
* @param mixinClassName
* @param className
* @return
* @throws IOException
*/
private static byte[] getClassBytes(String mixinClassName) throws IOException {
return Launch.classLoader.getClassBytes(mixinClassName);
private static byte[] getClassBytes(String className) throws IOException {
byte[] classBytes = Launch.classLoader.getClassBytes(TreeInfo.unmap(className));
if (classBytes != null) {
return classBytes;
}
URLClassLoader appClassLoader = (URLClassLoader)Launch.class.getClassLoader();
InputStream classStream = null;
try {
final String resourcePath = className.replace('.', '/').concat(".class");
classStream = appClassLoader.getResourceAsStream(resourcePath);
return IOUtils.toByteArray(classStream);
} finally {
IOUtils.closeQuietly(classStream);
}
}
/**
@@ -101,4 +129,18 @@ abstract class TreeInfo {
return basicClass;
}
/**
* Map a class name back to its obfuscated counterpart
*
* @param className
* @return
*/
static String unmap(String className) {
if (TreeInfo.nameTransformer != null) {
return TreeInfo.nameTransformer.unmapClassName(className);
}
return className;
}
}
@@ -29,6 +29,7 @@ import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.transformer.MixinClassWriter;
/**
* Base class for transformers which work with ASM tree model
@@ -68,7 +69,7 @@ public abstract class TreeTransformer implements IClassTransformer {
// Use optimised writer for speed
if (this.classReader != null && this.classNode == classNode) {
this.classNode = null;
ClassWriter writer = new ClassWriter(this.classReader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
ClassWriter writer = new MixinClassWriter(this.classReader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
this.classReader = null;
classNode.accept(writer);
return writer.toByteArray();
@@ -76,7 +77,7 @@ public abstract class TreeTransformer implements IClassTransformer {
this.classNode = null;
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
ClassWriter writer = new MixinClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
classNode.accept(writer);
return writer.toByteArray();
}