Migrating mixin functionality from Sponge to new project

This commit is contained in:
Mumfrey committed 2014-12-14 16:45:00 +00:00
commit dacac515d9
22 files changed
+2607

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
/bin
.gradle
/build
.classpath
.project
.settings
+8
View File
@@ -0,0 +1,8 @@
language: java
notifications:
email: false
install: true
matrix:
include:
- jdk: openjdk6
script: gradle build
+22
View File
@@ -0,0 +1,22 @@
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.
+19
View File
@@ -0,0 +1,19 @@
The MIT License (MIT)
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.
+183
View File
@@ -0,0 +1,183 @@
// Gradle repositories and dependencies
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0'
}
}
// Apply plugin
apply plugin: 'java'
apply plugin: 'license'
apply plugin: 'checkstyle'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'idea'
// Default tasks
defaultTasks 'licenseFormat', 'check', 'build'
// Basic project information
group = 'org.spongepowered'
archivesBaseName = 'mixin'
version = '0.1-SNAPSHOT'
// Extended project information
ext.projectName = 'Mixin'
ext.inceptionYear = '2014'
ext.packaging = 'jar'
ext.url = 'http://spongepowered.org'
ext.description = 'Mixin'
ext.organization = 'SpongePowered'
// Define variables
ext.buildNumber = project.hasProperty("buildNumber") ? buildNumber : '0'
ext.ciSystem = project.hasProperty("ciSystem") ? ciSystem : 'unknown'
ext.commit = project.hasProperty("commit") ? commit : 'unknown'
// Minimum version of Java required
sourceCompatibility = '1.6'
targetCompatibility = '1.6'
// Project repositories
repositories {
mavenCentral()
maven {
name = 'minecraft'
url = 'https://libraries.minecraft.net/'
}
}
configurations {
deployerJars // maven stuff
}
// Project dependencies
dependencies {
compile 'org.slf4j:slf4j-api:1.7.7'
compile 'com.google.guava:guava:17.0'
compile 'org.ow2.asm:asm-debug-all:5.0.3'
compile 'net.minecraft:launchwrapper:1.11'
compile 'com.google.code.gson:gson:2.2.4'
compile 'commons-io:commons-io:2.4'
testCompile 'junit:junit:4.11'
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile 'org.mockito:mockito-core:1.9.0'
// maven
deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7'
}
// Filter, process, and include resources
processResources {
// Include in final JAR
from 'LICENSE.txt'
}
// License header formatting
license {
ext.name = project.name
ext.organization = project.organization
ext.url = project.url
ext.year = project.inceptionYear
exclude "**/*.info"
exclude "assets/**"
header file("HEADER.txt")
sourceSets = project.sourceSets
ignoreFailures false
strictCheck false
mapping {
java = 'SLASHSTAR_STYLE'
}
}
checkstyle {
configProperties = [
"name" : project.name,
"organization": project.organization,
"url" : project.url,
"year" : project.inceptionYear
]
configFile = file("checkstyle.xml")
}
// Source compiler configuration
configure([compileJava, compileTestJava]) {
options.compilerArgs += ['-Xlint:all', '-Xlint:-path']
options.deprecation = true
options.encoding = 'utf8'
}
// JAR manifest configuration
jar.manifest.mainAttributes(
"Built-By": System.properties['user.name'],
"Created-By": System.properties['java.vm.version'] + " (" + System.properties['java.vm.vendor'] + ")",
"Implementation-Title": name,
"Implementation-Version": version + "+" + ciSystem + "-b" + buildNumber + ".git-" + commit,
"Implementation-Vendor": url)
task sourceJar(type: Jar) {
from sourceSets.main.java
from sourceSets.main.resources
classifier = "sources"
}
task javadocJar(type: Jar, dependsOn: javadoc) {
from javadoc.destinationDir
classifier = "javadoc"
}
artifacts {
archives jar
archives sourceJar
archives javadocJar
}
uploadArchives {
repositories {
mavenDeployer {
configuration = configurations.deployerJars
if (project.hasProperty("chRepo"))
{
repository(url: project.chRepo) {
authentication(userName: project.chUsername, password: project.chPassword)
}
}
pom {
groupId = project.group
version = project.version
artifactId = project.archivesBaseName
project {
name project.archivesBaseName
packaging 'jar'
description 'Sponge API'
url 'http://www.spongepowered.org/'
scm {
url 'https://github.com/SpongePowered/SpongeAPI'
connection 'scm:git:git://github.com/SpongePowered/SpongeAPI.git'
developerConnection 'scm:git:[email protected]:SpongePowered/SpongeAPI.git'
}
issueManagement {
system 'youtrack'
url 'https://issues.spongepowered.org/'
}
licenses {
license {
name 'MIT license'
url 'http://opensource.org/licenses/MIT'
distribution 'repo'
}
}
}
}
}
}
}
+162
View File
@@ -0,0 +1,162 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<!--
Checkstyle configurartion that checks the Google coding conventions from:
- Google Java Style
https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
Most Checks are configurable, be sure to consult the documentation.
To completely disable a check, just comment it out or delete it from the file.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<!-- This seems to only exist in github versions of checkstyle. -->
<!--<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>-->
<module name="LineLength">
<property name="max" value="150"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="AvoidStarImport"/>
<!-- Check doesn't exist in current release of checkstyle -->
<!--<module name="OneTopLevelClass"/>-->
<!--<module name="NoLineWrap"/>-->
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="maxLineLength" value="150"/>
</module>
<module name="RightCurly"/>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<!--<property name="allowEmptyTypes" value="true"/>-->
<!--<property name="allowEmptyLoops" value="true"/>-->
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace."/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<!--<module name="EmptyLineSeparator">
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>-->
<!--<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>-->
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z](([a-z0-9])|([a-z0-9][a-zA-Z0-9]*))?$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z](([a-z0-9])|([a-z0-9][a-zA-Z0-9]*))?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z](([a-z0-9])|([a-z0-9][a-zA-Z0-9]*))?$"/>
<!--<property name="allowOneCharVarInForLoop" value="true"/>-->
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<!--<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="1"/>
</module>-->
<!--<module name="OverloadMethodsDeclarationOrder"/>-->
<!--<module name="VariableDeclarationUsageDistance"/>-->
<!--<module name="CustomImportOrder">
<property name="thirdPartyPackageRegExp" value=".*"/>
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="customImportOrderRules" value="STATIC###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE###STANDARD_JAVA_PACKAGE"/>
</module>-->
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
</module>
</module>
+6
View File
@@ -0,0 +1,6 @@
theName=Mixin
inceptionYear=2014
packaging=jar
url=http://spongepowered.org
description=SpongeAPI
organization=SpongePowered
+1
View File
@@ -0,0 +1 @@
rootProject.name = theName
@@ -0,0 +1,43 @@
/**
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Pseudo-implements decorator for Mixins with conflicting methods in a superclass to soft-implement an interface
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface Implements {
/**
* Interfaces implemented, see javadoc in {@link Interface}
*/
public Interface[] value();
}
@@ -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.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* I'm probably going to the special hell for this
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface Interface {
/**
* Interface that the parent {@link Implements} indicates the mixin implements. The interface will be hot-patched onto the target class as part
* of the mixin application.
*/
public Class<?> iface();
/**
* [Required] prefix for implementing interface methods. Works similarly to {@link Shadow} prefixes, but <b>must</b> end with a dollar sign ($)
*/
public String prefix();
}
@@ -0,0 +1,42 @@
/**
* 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;
public class InvalidMixinException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidMixinException(String message) {
super(message);
}
public InvalidMixinException(Throwable message) {
super(message);
}
public InvalidMixinException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,48 @@
/**
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Decorator for mixin classes
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface Mixin {
/**
* Target class(es) for this mixin
*/
public Class<?>[] value();
/**
* Priority for the mixin, relative to other mixins targetting the same classes
*/
public int priority() default 1000;
}
@@ -0,0 +1,90 @@
/**
* 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;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
/**
* Env interaction for mixins
*/
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 MixinEnvironment env;
private MixinEnvironment() {
// 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);
}
/**
* Get mixin configurations from the blackboard
*/
public List<String> getMixinConfigs() {
@SuppressWarnings("unchecked")
List<String> mixinConfigs = (List<String>) Launch.blackboard.get(MixinEnvironment.CONFIGS_KEY);
if (mixinConfigs == null) {
mixinConfigs = new ArrayList<String>();
Launch.blackboard.put(MixinEnvironment.CONFIGS_KEY, mixinConfigs);
}
return mixinConfigs;
}
/**
* Add a mixin configuration to the blackboard
*/
public void addConfiguration(String config) {
this.getMixinConfigs().add(config);
}
public Object getActiveTransformer() {
return Launch.blackboard.get(MixinEnvironment.TRANSFORMER_KEY);
}
public void setActiveTransformer(IClassTransformer transformer) {
Launch.blackboard.put(MixinEnvironment.TRANSFORMER_KEY, this);
}
public static MixinEnvironment getCurrentEnvironment() {
if (MixinEnvironment.env == null) {
MixinEnvironment.env = new MixinEnvironment();
}
return MixinEnvironment.env;
}
}
@@ -0,0 +1,39 @@
/**
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to indicate a Mixin class member which should overwrite a method in the target class
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Overwrite {
}
@@ -0,0 +1,68 @@
/**
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to indicate a Mixin class member which is acting as a placeholder for a method or field in the target class
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Shadow {
/**
* <p>In general, shadow methods can be declared using their name in the target class as you would expect, however we run into a problem when we
* want to mix in a method with the same name and arguments, but a different return type to the shadow method. While the JVM itself will happily
* support methods with signatures that differ only on return type, the compiler itself does not. This poses a problem, since we have no way to
* leverage this behaviour since our mixin class will not compile.</p>
*
* <p>To circumvent this compiler limitation, the prefix option can be used. By specifying a prefix for the shadow method, it is subsequently
* possible to compile the mixin class, the specified prefix will then be stripped from the method name prior to applying the mixin, and
* everything will work as expected. You may either use the default prefix: "shadow$", or you may specify your own. It is good practice to
* specify the prefix if you are using it, regardless of whether you use the default or not. For example consider the intrinsic readability of
* the following snippets</p>:
*
* <blockquote><pre>
* &#64;Shadow abstract void someMethod(int arg1, int arg2);
* &#64;Shadow abstract void shadow$someMethod(int arg1, int arg2);
* &#64;Shadow(prefix = "shadow$") abstract void shadow$someMethod(int arg1, int arg2);
* &#64;Shadow(prefix = "foo$") abstract void foo$someMethod(int arg1, int arg2);
* </pre></blockquote>
*
* <p>All of these declarations are semantically equivalent, however the third and fourth are the most expressive in terms of making their
* intentions clear, and thus specifying prefix is recommended, since it aids readability and maintainability.<p>
*
* <p>Note that specifying a <em>prefix</em> does not <b>enforce</b> use of the prefix, the behaviour of <em>prefix</em> is such that the prefix
* will be stripped from the start of the method name <em>as long as the method name actually starts with the prefix</em>! This has important
* repercussions since if the annotation value does not match the method prefix then <em>no renaming will take place</em> likey resulting in
* a failure state indicated by an {@link InvalidMixinException} at run time.</p>
*/
public String prefix() default "shadow$";
}
@@ -0,0 +1,170 @@
/**
* 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 java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about an interface being runtime-patched onto a mixin target class, see {@link Implements}
*/
public class InterfaceInfo {
/**
* Prefix for interface methods. Any methods using this prefix must exist in the target interface
*/
private final String prefix;
/**
* Interface being patched
*/
private final Type iface;
/**
* Method signatures in the interface, lazy loaded
*/
private Set<String> methods;
/**
* Make with the new thing already
*/
private InterfaceInfo(String prefix, Type iface) {
if (prefix == null || prefix.length() < 2 || !prefix.endsWith("$")) {
throw new InvalidMixinException(String.format("Prefix %s for iface %s is not valid", prefix, iface.toString()));
}
this.prefix = prefix;
this.iface = iface;
}
/**
* Lazy-loaded methods collection initialiser
*/
private void initMethods() {
this.methods = new HashSet<String>();
this.readInterface(this.iface.getClassName());
}
/**
* Reads an interface and its super-interfaces and gathers method names in to the local "methods" collection
*/
private void readInterface(String ifaceName) {
ClassNode ifaceNode = new ClassNode();
try {
ClassReader classReader = new ClassReader(this.loadInterface(ifaceName));
classReader.accept(ifaceNode, 0);
} catch (IOException ex) {
throw new InvalidMixinException("An error was encountered parsing the interface " + this.iface.toString());
}
for (MethodNode ifaceMethod : ifaceNode.methods) {
String signature = ifaceMethod.name + ifaceMethod.desc;
this.methods.add(signature);
}
for (String superIface : ifaceNode.interfaces) {
String sif = superIface.replace('/', '.');
this.readInterface(sif);
}
}
/**
* Fires ze missiles
*/
private byte[] loadInterface(String ifaceName) throws IOException {
byte[] ifaceBytes = MixinInfo.getClassBytes(ifaceName);
ifaceBytes = MixinInfo.applyTransformers(ifaceName, ifaceBytes);
return ifaceBytes;
}
/**
* Get the prefix string (non null)
*/
public String getPrefix() {
return this.prefix;
}
/**
* Get the interface type
*/
public Type getIface() {
return this.iface;
}
/**
* Get the internal name of the interface
*/
public String getInternalName() {
return this.iface.getInternalName();
}
/**
* Processes a method node in the mixin and renames it if necessary. If the prefix is found then we verify that the method exists in the target
* interface and throw our teddies out of the pram if that's not the case (replacement behaviour for {@link Override} essentially.
*/
public boolean renameMethod(MethodNode method) {
if (this.methods == null) {
this.initMethods();
}
if (!method.name.startsWith(this.prefix)) {
return false;
}
String realName = method.name.substring(this.prefix.length());
String signature = realName + method.desc;
if (!this.methods.contains(signature)) {
throw new InvalidMixinException(String.format("%s does not exist in target interface %s", realName, this.iface.toString()));
}
method.name = realName;
return true;
}
/**
* Convert an {@link Interface} annotation node into an {@link InterfaceInfo}
*/
static InterfaceInfo fromAnnotation(AnnotationNode node) {
String prefix = ASMHelper.<String>getAnnotationValue(node, "prefix");
Type iface = ASMHelper.<Type>getAnnotationValue(node, "iface");
if (prefix == null || iface == null) {
throw new InvalidMixinException(String.format("@Interface annotation on is missing a required parameter"));
}
return new InterfaceInfo(prefix, iface);
}
}
@@ -0,0 +1,171 @@
/**
* 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 java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
/**
* Mixin configuration bundle
*/
class MixinConfig {
/**
* Map of mixin target classes to mixin infos
*/
private final transient Map<String, List<MixinInfo>> mixinMapping = new HashMap<String, List<MixinInfo>>();
/**
* Package containing all mixins. This package will be monitored by the transformer so that we can explode if some dummy tries to reference a
* mixin class directly.
*/
@SerializedName("package")
private String mixinPackage;
/**
* Mixin classes to load, mixinPackage will be prepended
*/
@SerializedName("mixins")
private List<String> mixinClasses;
/**
* True to set the sourceFile property when applying mixins
*/
@SerializedName("setSourceFile")
private boolean setSourceFile = false;
/**
* Keep track of initialisation state
*/
private transient boolean initialised = false;
/**
* Spawn via GSON, no public ctor for you
*/
private MixinConfig() {}
/**
* <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
* have been spawned, because we will run the mixin bytecode through the transformer chain and naturally we want this to happen at a point when
* we can be reasonably sure that all transfomers have loaded.</p>
*
* <p>For this reason we will invoke the initialisation on the first call to either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em>
* methods.</p>
*/
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);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Get the package containing all mixin classes
*/
public String getMixinPackage() {
return this.mixinPackage;
}
/**
* Get the list of mixin classes we will be applying
*/
public List<String> getClasses() {
return this.mixinClasses;
}
/**
* Get whether to propogate the source file attribute from a mixin onto the target class
*/
public boolean shouldSetSourceFile() {
return this.setSourceFile;
}
/**
* Check whether this configuration bundle has a mixin for the specified class
*
* @param targetClass
* @return
*/
public boolean hasMixinsFor(String targetClass) {
if (!this.initialised) {
this.initialise();
}
return this.mixinMapping.containsKey(targetClass);
}
/**
* Get mixins for the specified target class
*
* @param targetClass
* @return
*/
public List<MixinInfo> getMixinsFor(String targetClass) {
if (!this.initialised) {
this.initialise();
}
List<MixinInfo> mixins = this.mixinMapping.get(targetClass);
if (mixins == null) {
mixins = new ArrayList<MixinInfo>();
this.mixinMapping.put(targetClass, mixins);
}
return mixins;
}
/**
* Factory method, creates a new mixin configuration bundle from the specified configFile, which must be accessible on the classpath
*
* @param configFile
* @return
*/
static MixinConfig create(String configFile) {
try {
return new Gson().fromJson(new InputStreamReader(MixinConfig.class.getResourceAsStream("/" + configFile)), MixinConfig.class);
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException(String.format("The specified configuration file '%s' was invalid or could not be read", configFile));
}
}
}
@@ -0,0 +1,202 @@
/**
* 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 java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.util.ASMHelper;
/**
* Data for applying a mixin. Keeps a copy of the mixin tree and also handles any pre-transformations required by the mixin class itself such as
* method renaming and any other pre-processing of the mixin bytecode.
*/
public class MixinData {
/**
* Mixin info
*/
private final MixinInfo info;
/**
* Tree
*/
private final ClassNode classNode;
/**
* Methods we need to rename
*/
private final Map<String, String> renamedMethods = new HashMap<String, String>();
/**
* Interfaces soft-implemented using {@link Implements}
*/
private final List<InterfaceInfo> softImplements = new ArrayList<InterfaceInfo>();
/**
* All interfaces implemented by this mixin, including soft implementations
*/
private final Set<String> interfaces = new HashSet<String>();
/**
* ctor
*
* @param info
*/
MixinData(MixinInfo info) {
this.info = info;
this.classNode = info.getClassNode(ClassReader.EXPAND_FRAMES);
this.prepare();
}
/**
* Get the mixin tree
*/
public ClassNode getClassNode() {
return this.classNode;
}
/**
* Get all interfaces for this mixin
*/
public Set<String> getInterfaces() {
return this.interfaces;
}
/**
* Get whether to propogate the source file attribute from a mixin onto the target class
*/
public boolean shouldSetSourceFile() {
return this.info.getParent().shouldSetSourceFile();
}
/**
* Prepare the mixin, applies any pre-processing transformations
*/
private void prepare() {
this.readImplementations();
this.findRenamedMethods();
this.transformMethods();
}
/**
* Read and process any {@link Implements} annotations on the mixin
*/
private void readImplementations() {
this.interfaces.addAll(this.classNode.interfaces);
AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(this.classNode, Implements.class);
if (implementsAnnotation == null) {
return;
}
List<AnnotationNode> interfaces = ASMHelper.getAnnotationValue(implementsAnnotation);
if (interfaces == null) {
return;
}
for (AnnotationNode interfaceNode : interfaces) {
InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(interfaceNode);
this.softImplements.add(interfaceInfo);
this.interfaces.add(interfaceInfo.getInternalName());
}
}
/**
* Let's do this
*/
private void findRenamedMethods() {
for (MethodNode mixinMethod : this.classNode.methods) {
String oldSignature = mixinMethod.name + mixinMethod.desc;
AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class);
if (shadowAnnotation != null) {
String prefix = MixinData.getAnnotationValue(shadowAnnotation, "prefix", Shadow.class);
if (mixinMethod.name.startsWith(prefix)) {
String newName = mixinMethod.name.substring(prefix.length());
this.renamedMethods.put(oldSignature, newName);
mixinMethod.name = newName;
}
}
for (InterfaceInfo iface : this.softImplements) {
if (iface.renameMethod(mixinMethod)) {
this.renamedMethods.put(oldSignature, mixinMethod.name);
}
}
}
}
/**
* Apply discovered method renames to method invokations in the mixin
*/
private void transformMethods() {
for (MethodNode mixinMethod : this.classNode.methods) {
for (Iterator<AbstractInsnNode> iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode)insn;
String newName = this.renamedMethods.get(methodNode.name + methodNode.desc);
if (newName != null) {
methodNode.name = newName;
}
}
}
}
}
/**
* Gets an annotation value or returns the default if the annotation value is not present
*
* @param annotation
* @param key
* @param annotationClass
* @return
*/
private static String getAnnotationValue(AnnotationNode annotation, String key, Class<?> annotationClass) {
String value = ASMHelper.getAnnotationValue(annotation, key);
if (value == null) {
try {
value = (String)Shadow.class.getDeclaredMethod(key).getDefaultValue();
} catch (NoSuchMethodException ex) {
// Don't care
}
}
return value;
}
}
@@ -0,0 +1,292 @@
/**
* 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 java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.util.ASMHelper;
/**
* Runtime information bundle about a mixin
*/
class MixinInfo implements Comparable<MixinInfo> {
/**
* Global order of mixin infos, used to determine ordering between mixins with equivalent priority
*/
static int mixinOrder = 0;
/**
* Logger
*/
private final transient Logger logger = LogManager.getLogger("sponge");
/**
* Parent configuration which declares this mixin
*/
private final transient MixinConfig parent;
/**
* Simple name
*/
private final String name;
/**
* Name of the mixin class itself, dotted notation
*/
private final String className;
/**
* Name of the mixin class, internal notation
*/
private final transient String classRef;
/**
* Mixin priority, read from the {@link Mixin} annotation on the mixin class
*/
private final int priority;
/**
* Mixin targets, read from the {@link Mixin} annotation on the mixin class
*/
private final List<String> targetClasses;
/**
* Intrinsic order (for sorting mixins with identical priority)
*/
private final transient int order = MixinInfo.mixinOrder++;
/**
* Mixin bytes (read once, generate tree on demand)
*/
private final transient byte[] mixinBytes;
/**
* Internal ctor, called by {@link MixinConfig}
*
* @param parent
* @param mixinName
* @param runTransformers
*/
MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers) {
this.parent = parent;
this.name = mixinName;
this.className = parent.getMixinPackage() + mixinName;
this.classRef = this.className.replace('.', '/');
// Read the class bytes and transform
this.mixinBytes = this.loadMixinClass(this.className, runTransformers);
ClassNode classNode = this.getClassNode(0);
this.targetClasses = this.readTargetClasses(classNode);
this.priority = this.readPriority(classNode);
}
/**
* Read the target class names from the {@link Mixin} annotation
*
* @param classNode
* @return
*/
private List<String> readTargetClasses(ClassNode classNode) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
throw new InvalidMixinException(String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
List<Type> targetClasses = ASMHelper.getAnnotationValue(mixin);
List<String> targetClassNames = new ArrayList<String>();
for (Type targetClass : targetClasses) {
targetClassNames.add(targetClass.getClassName());
}
return targetClassNames;
}
/**
* Read the priority from the {@link Mixin} annotation
*
* @param classNode
* @return
*/
private int readPriority(ClassNode classNode) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
throw new InvalidMixinException(String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
Integer priority = ASMHelper.getAnnotationValue(mixin, "priority");
return priority == null ? 1000 : priority.intValue();
}
/**
* Get the parent config which declares this mixin
*/
public MixinConfig getParent() {
return this.parent;
}
/**
* Get the simple name of the mixin
*/
public String getName() {
return this.name;
}
/**
* Get the name of the mixin class
*/
public String getClassName() {
return this.className;
}
/**
* Get the ref (internal name) of the mixin class
*/
public String getClassRef() {
return this.classRef;
}
/**
* Get the class bytecode
*/
public byte[] getClassBytes() {
return this.mixinBytes;
}
/**
* Get a new tree for the class bytecode
*/
public ClassNode getClassNode(int flags) {
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(this.mixinBytes);
classReader.accept(classNode, flags);
return classNode;
}
/**
* Get a new mixin data container for this info
*
* @return
*/
public MixinData getData() {
return new MixinData(this);
}
/**
* Get the target classes for this mixin
*/
public List<String> getTargetClasses() {
return Collections.unmodifiableList(this.targetClasses);
}
/**
* Get the mixin priority
*/
public int getPriority() {
return this.priority;
}
/**
* @param mixinClassName
* @param runTransformers
* @return
*/
private byte[] loadMixinClass(String mixinClassName, boolean runTransformers) {
byte[] mixinBytes = null;
try {
if ((mixinBytes = MixinInfo.getClassBytes(mixinClassName)) == null) {
throw new InvalidMixinException(String.format("The specified mixin '%s' was not found", mixinClassName));
}
if (runTransformers) {
mixinBytes = MixinInfo.applyTransformers(mixinClassName, mixinBytes);
}
} catch (IOException ex) {
this.logger.warn("Failed to load mixin %s, the specified mixin will not be applied", mixinClassName);
throw new InvalidMixinException("An error was encountered whilst loading the mixin class", ex);
}
return mixinBytes;
}
/**
* @param mixinClassName
* @return
* @throws IOException
*/
static byte[] getClassBytes(String mixinClassName) throws IOException {
return Launch.classLoader.getClassBytes(mixinClassName);
}
/**
* Since we obtain the mixin class bytes with getClassBytes(), we need to
* apply the transformers ourself
*
* @param name
* @param basicClass
* @return
*/
static byte[] applyTransformers(String name, byte[] basicClass) {
final List<IClassTransformer> transformers = Launch.classLoader.getTransformers();
for (final IClassTransformer transformer : transformers) {
if (!(transformer instanceof MixinTransformer)) {
basicClass = transformer.transform(name, name, basicClass);
}
}
return basicClass;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(MixinInfo other) {
if (other == null) {
return 0;
}
if (other.priority == this.priority) {
return this.order - other.order;
}
return (this.priority - other.priority);
}
}
@@ -0,0 +1,429 @@
/**
* 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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.ASMHelper;
/**
* Transformer which applies Mixin classes to their declared target classes
*/
public class MixinTransformer extends TreeTransformer {
private static final boolean DEBUG_EXPORT = Booleans.parseBoolean(System.getProperty("mixin.debug.export"), false);
/**
* Log all the things
*/
private final Logger logger = LogManager.getLogger("sponge");
/**
* Mixin configuration bundle
*/
private final List<MixinConfig> configs = new ArrayList<MixinConfig>();
/**
* ctor
*/
public MixinTransformer() {
// Go via blackboard to create FORWARD compatibility if Mixins get pulled into FML
Object globalMixinTransformer = MixinEnvironment.getCurrentEnvironment().getActiveTransformer();
if (globalMixinTransformer instanceof IClassTransformer) {
throw new RuntimeException("Terminating MixinTransformer instance " + this);
}
// I am a leaf on the wind
MixinEnvironment.getCurrentEnvironment().setActiveTransformer(this);
List<String> configs = MixinEnvironment.getCurrentEnvironment().getMixinConfigs();
if (configs != null) {
for (String configFile : configs) {
try {
this.configs.add(MixinConfig.create(configFile));
} catch (Exception ex) {
this.logger.warn(String.format("Failed to load mixin config: %s", configFile), ex);
}
}
}
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.IClassTransformer#transform(java.lang.String, java.lang.String, byte[])
*/
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
for (MixinConfig config : this.configs)
{
if (transformedName != null && transformedName.startsWith(config.getMixinPackage())) {
throw new RuntimeException(String.format("%s is a mixin class and cannot be referenced directly", transformedName));
}
if (config.hasMixinsFor(transformedName)) {
try {
basicClass = this.applyMixins(config, transformedName, basicClass);
} catch (InvalidMixinException th) {
this.logger.warn(String.format("Class mixin failed: %s %s", th.getClass().getName(), th.getMessage()), th);
th.printStackTrace();
}
}
}
return basicClass;
}
/**
* Apply mixins for specified target class to the class described by the supplied byte array
*
* @param config
* @param transformedName
* @param basicClass
* @return
*/
private byte[] applyMixins(MixinConfig config, String transformedName, byte[] basicClass) {
// Tree for target class
ClassNode targetClass = this.readClass(basicClass, true);
// Get and sort mixins for the class
List<MixinInfo> mixins = config.getMixinsFor(transformedName);
Collections.sort(mixins);
for (MixinInfo mixin : mixins) {
this.logger.info("Mixing {} into {}", mixin.getName(), transformedName);
this.applyMixin(targetClass, mixin.getData());
}
// Extension point
this.postTransform(transformedName, targetClass, mixins);
// Collapse tree to bytes
byte[] bytes = this.writeClass(targetClass);
// Export transformed class for debugging purposes
if (MixinTransformer.DEBUG_EXPORT) {
try {
FileUtils.writeByteArrayToFile(new File(".mixin.out/" + transformedName.replace('.', '/') + ".class"), bytes);
}
catch (IOException ex) {}
}
return bytes;
}
/**
* @param transformedName
* @param targetClass
* @param mixins
*/
protected void postTransform(String transformedName, ClassNode targetClass, List<MixinInfo> mixins) {
// Stub for subclasses
}
/**
* Apply the mixin described by mixin to the supplied classNode
*
* @param targetClass
* @param mixin
*/
protected void applyMixin(ClassNode targetClass, MixinData mixin) {
try {
this.verifyClasses(targetClass, mixin);
this.applyMixinInterfaces(targetClass, mixin);
this.applyMixinAttributes(targetClass, mixin);
this.applyMixinFields(targetClass, mixin);
this.applyMixinMethods(targetClass, mixin);
} catch (Exception ex) {
throw new InvalidMixinException("Unexpecteded error whilst applying the mixin class", ex);
}
}
/**
* Perform pre-flight checks on the mixin and target classes
*
* @param targetClass
* @param mixin
*/
protected void verifyClasses(ClassNode targetClass, MixinData mixin) {
String superName = mixin.getClassNode().superName;
if (targetClass.superName == null || superName == null || !targetClass.superName.equals(superName)) {
throw new InvalidMixinException("Mixin classes must have the same superclass as their target class");
}
}
/**
* Mixin interfaces implemented by the mixin class onto the target class
*
* @param targetClass
* @param mixin
*/
private void applyMixinInterfaces(ClassNode targetClass, MixinData mixin) {
for (String interfaceName : mixin.getInterfaces()) {
if (!targetClass.interfaces.contains(interfaceName)) {
targetClass.interfaces.add(interfaceName);
}
}
}
/**
* Mixin misc attributes from mixin class onto the target class
*
* @param targetClass
* @param mixin
*/
private void applyMixinAttributes(ClassNode targetClass, MixinData mixin) {
if (mixin.shouldSetSourceFile()) {
targetClass.sourceFile = mixin.getClassNode().sourceFile;
}
}
/**
* Mixin fields from mixin class into the target class. It is vital that this is done before mixinMethods because we need to compute renamed
* fields so that transformMethod can rename field references in the method body
*
* @param targetClass
* @param mixin
*/
private void applyMixinFields(ClassNode targetClass, MixinData mixin) {
for (FieldNode field : mixin.getClassNode().fields) {
// Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition
if (MixinTransformer.hasFlag(field, Opcodes.ACC_STATIC) && !MixinTransformer.hasFlag(field, Opcodes.ACC_PRIVATE)) {
throw new InvalidMixinException(String.format("Mixin classes cannot contain visible static methods or fields, found %s", field.name));
}
FieldNode target = this.findTargetField(targetClass, field);
if (target == null) {
// If this field is a shadow field but is NOT found in the target class, that's bad, mmkay
boolean isShadow = ASMHelper.getVisibleAnnotation(field, Shadow.class) != null;
if (isShadow) {
throw new InvalidMixinException(String.format("Shadow field %s was not located in the target class", field.name));
}
// This is just a local field, so add it
targetClass.fields.add(field);
} else {
// Check that the shadow field has a matching descriptor
if (!target.desc.equals(field.desc)) {
throw new InvalidMixinException(String.format("The field %s in the target class has a conflicting signature", field.name));
}
}
}
}
/**
* Mixin methods from the mixin class into the target class
*
* @param targetClass
* @param mixin
*/
private void applyMixinMethods(ClassNode targetClass, MixinData mixin) {
for (MethodNode mixinMethod : mixin.getClassNode().methods) {
// Reparent all mixin methods into the target class
this.transformMethod(mixinMethod, mixin.getClassNode().name, targetClass.name);
boolean isShadow = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class) != null;
boolean isOverwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class) != null;
boolean isAbstract = MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_ABSTRACT);
if (isShadow || isAbstract) {
// For shadow (and abstract, which can be used as a shorthand for Shadow) methods, we just check they're present
MethodNode target = this.findTargetMethod(targetClass, mixinMethod);
if (target == null) {
throw new InvalidMixinException(String.format("Shadow method %s was not located in the target class", mixinMethod.name));
}
} else if (!mixinMethod.name.startsWith("<")) {
if (MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
&& !MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE)
&& !MixinTransformer.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)
&& !isOverwrite) {
throw new InvalidMixinException(
String.format("Mixin classes cannot contain visible static methods or fields, found %s", mixinMethod.name));
}
MethodNode target = this.findTargetMethod(targetClass, mixinMethod);
if (target != null) {
targetClass.methods.remove(target);
} else if (isOverwrite) {
throw new InvalidMixinException(String.format("Overwrite target %s was not located in the target class", mixinMethod.name));
}
targetClass.methods.add(mixinMethod);
} else if ("<clinit>".equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(targetClass, mixinMethod.name, mixinMethod);
}
}
}
/**
* Handles "re-parenting" the method supplied, changes all references to the mixin class to refer to the target class (for field accesses and
* method invokations) and also renames fields accesses to their obfuscated versions
*
* @param method
* @param fromClass
* @param toClass
* @return
*/
private void transformMethod(MethodNode method, String fromClass, String toClass) {
Iterator<AbstractInsnNode> iter = method.instructions.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodInsn = (MethodInsnNode) insn;
if (methodInsn.owner.equals(fromClass)) {
methodInsn.owner = toClass;
}
}
if (insn instanceof FieldInsnNode) {
FieldInsnNode fieldInsn = (FieldInsnNode) insn;
if (fieldInsn.owner.equals(fromClass)) {
fieldInsn.owner = toClass;
}
}
}
}
/**
* Handles appending instructions from the source method to the target method
*
* @param targetClass
* @param targetMethodName
* @param sourceMethod
*/
private void appendInsns(ClassNode targetClass, String targetMethodName, MethodNode sourceMethod) {
if (Type.getReturnType(sourceMethod.desc) != Type.VOID_TYPE) {
throw new IllegalArgumentException("Attempted to merge insns into a method which does not return void");
}
if (targetMethodName == null || targetMethodName.length() == 0) {
targetMethodName = sourceMethod.name;
}
for (MethodNode method : targetClass.methods) {
if ((targetMethodName.equals(method.name)) && sourceMethod.desc.equals(method.desc)) {
AbstractInsnNode returnNode = null;
Iterator<AbstractInsnNode> findReturnIter = method.instructions.iterator();
while (findReturnIter.hasNext()) {
AbstractInsnNode insn = findReturnIter.next();
if (insn.getOpcode() == Opcodes.RETURN) {
returnNode = insn;
break;
}
}
Iterator<AbstractInsnNode> injectIter = sourceMethod.instructions.iterator();
while (injectIter.hasNext()) {
AbstractInsnNode insn = injectIter.next();
if (!(insn instanceof LineNumberNode) && insn.getOpcode() != Opcodes.RETURN) {
method.instructions.insertBefore(returnNode, insn);
}
}
}
}
}
/**
* Finds a method in the target class
*
* @param targetClass
* @param searchFor
* @return
*/
private MethodNode findTargetMethod(ClassNode targetClass, MethodNode searchFor) {
for (MethodNode target : targetClass.methods) {
if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc)) {
return target;
}
}
return null;
}
/**
* Finds a field in the target class
*
* @param targetClass
* @param searchFor
* @return
*/
private FieldNode findTargetField(ClassNode targetClass, FieldNode searchFor) {
for (FieldNode target : targetClass.fields) {
if (target.name.equals(searchFor.name)) {
return target;
}
}
return null;
}
/**
* Check whether the specified flag is set on the specified method
*
* @param method
* @param flag
* @return
*/
private static boolean hasFlag(MethodNode method, int flag) {
return (method.access & flag) == flag;
}
/**
* Check whether the specified flag is set on the specified field
*
* @param field
* @param flag
* @return
*/
private static boolean hasFlag(FieldNode field, int flag) {
return (field.access & flag) == flag;
}
}
@@ -0,0 +1,83 @@
/**
* 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.transformers;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
* Base class for transformers which work with ASM tree model
*/
public abstract class TreeTransformer implements IClassTransformer {
private ClassReader classReader;
private ClassNode classNode;
/**
* @param basicClass
* @return tree
*/
protected final ClassNode readClass(byte[] basicClass) {
return this.readClass(basicClass, true);
}
/**
* @param basicClass
* @return tree
*/
protected final ClassNode readClass(byte[] basicClass, boolean cacheReader) {
ClassReader classReader = new ClassReader(basicClass);
if (cacheReader) {
this.classReader = classReader;
}
ClassNode classNode = new ClassNode();
classReader.accept(classNode, ClassReader.EXPAND_FRAMES);
return classNode;
}
/**
* @param classNode
*/
protected final byte[] writeClass(ClassNode classNode) {
// 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);
this.classReader = null;
classNode.accept(writer);
return writer.toByteArray();
}
this.classNode = null;
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
classNode.accept(writer);
return writer.toByteArray();
}
}
@@ -0,0 +1,473 @@
/**
* 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.util;
import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES;
import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.util.CheckClassAdapter;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import java.util.List;
public class ASMHelper {
private static final int[] intConstants = new int[]
{Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5};
/**
* Generate a new method "boolean name()", which returns a constant value.
*
* @param clazz Class to add method to
* @param name Name of method
* @param retval Return value of method
*/
public static void generateBooleanMethodConst(ClassNode clazz, String name, boolean retval) {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()Z", null, null);
InsnList code = method.instructions;
code.add(pushIntConstant(retval ? 1 : 0));
code.add(new InsnNode(Opcodes.IRETURN));
clazz.methods.add(method);
}
/**
* Generate a new method "int name()", which returns a constant value.
*
* @param clazz Class to add method to
* @param name Name of method
* @param retval Return value of method
*/
public static void generateIntegerMethodConst(ClassNode clazz, String name, short retval) {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()I", null, null);
InsnList code = method.instructions;
code.add(pushIntConstant(retval));
code.add(new InsnNode(Opcodes.IRETURN));
clazz.methods.add(method);
}
/**
* Generate a forwarding method of the form
* "T name() { return this.forward(); }".
*
* @param clazz Class to generate new method on
* @param name Name of method to generate
* @param forwardname Name of method to call
* @param rettype Return type of method
*/
public static void generateSelfForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype) {
MethodNode method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
populateSelfForwardingMethod(method, forwardname, rettype, Type.getObjectType(clazz.name));
clazz.methods.add(method);
}
/**
* Generate a forwarding method of the form
* "static T name(S object) { return object.forward(); }".
*
* @param clazz Class to generate new method on
* @param name Name of method to generate
* @param forwardname Name of method to call
* @param rettype Return type of method
*/
public static void generateStaticForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype, Type argtype) {
MethodNode method = new MethodNode(Opcodes.ASM5,
Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
"()" + rettype.getDescriptor(), null, null);
populateSelfForwardingMethod(method, forwardname, rettype, argtype);
clazz.methods.add(method);
}
/**
* Generate a forwarding method of the form
* "T name() { return Class.forward(this); }".
*
* @param clazz Class to generate new method on
* @param name Name of method to generate
* @param forwardname Name of method to call
* @param rettype Return type of method
*/
public static void generateForwardingToStaticMethod(ClassNode clazz, String name, String forwardname, Type rettype, Type fowardtype) {
MethodNode method = new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name,
"()" + rettype.getDescriptor(), null, null);
populateForwardingToStaticMethod(method, forwardname, rettype, Type.getObjectType(clazz.name), fowardtype);
clazz.methods.add(method);
}
/**
* Generate a forwarding method of the form
* "T name() { return Class.forward(this); }".
*
* @param clazz Class to generate new method on
* @param name Name of method to generate
* @param forwardname Name of method to call
* @param rettype Return type of method
* @param thistype Type to treat 'this' as for overload searching purposes
*/
public static void generateForwardingToStaticMethod(ClassNode clazz, String name, String forwardname, Type rettype, Type fowardtype,
Type thistype) {
MethodNode
method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
populateForwardingToStaticMethod(method, forwardname, rettype, thistype, fowardtype);
clazz.methods.add(method);
}
/**
* Replace a method's code with a forward to another method on itself
* or the first argument of a static method, as the argument takes the
* place of this.
*
* @param method Method to replace code of
* @param forwardname Name of method to forward to
* @param thistype Type of object method is being replaced on
*/
public static void replaceSelfForwardingMethod(MethodNode method, String forwardname, Type thistype) {
Type methodType = Type.getMethodType(method.desc);
method.instructions.clear();
populateSelfForwardingMethod(method, forwardname, methodType.getReturnType(), thistype);
}
/**
* Generate a forwarding method of the form
* "T name(S object) { return object.forward(); }".
*
* @param clazz Class to generate new method on
* @param name Name of method to generate
* @param forwardname Name of method to call
* @param rettype Return type of method
* @param argtype Type of object to call method on
*/
public static void generateForwardingMethod(ClassNode clazz, String name, String forwardname, Type rettype, Type argtype) {
MethodNode
method =
new MethodNode(Opcodes.ASM5, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, name, "()" + rettype.getDescriptor(), null, null);
populateForwardingMethod(method, forwardname, rettype, argtype, Type.getObjectType(clazz.name));
clazz.methods.add(method);
}
/**
* Replace a method's code with a forward to an method on its first argument.
*
* @param method Method to replace code of
* @param forwardname Name of method to forward to
* @param thistype Type of object method is being replaced on
*/
public static void replaceForwardingMethod(MethodNode method, String forwardname, Type thistype) {
Type methodType = Type.getMethodType(method.desc);
method.instructions.clear();
populateForwardingMethod(method, forwardname, methodType.getReturnType(), methodType.getArgumentTypes()[0], thistype);
}
/**
* Populate a forwarding method of the form
* "T name() { return Class.forward(this); }".
*
* @param method Method to generate code for
* @param forwardname Name of method to call
* @param rettype Return type of method
* @param thistype Type of object method is being generated on
* @param forwardtype Type to forward method to
*/
public static void populateForwardingToStaticMethod(MethodNode method, String forwardname, Type rettype, Type thistype, Type forwardtype) {
InsnList code = method.instructions;
code.add(new VarInsnNode(thistype.getOpcode(Opcodes.ILOAD), 0));
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, forwardtype.getInternalName(), forwardname, Type.getMethodDescriptor(rettype, thistype),
false));
code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
}
/**
* Populate a forwarding method of the form
* "T name() { return this.forward(); }". This is also valid for methods of
* the form "static T name(S object) { return object.forward() }".
*
* @param method Method to generate code for
* @param forwardname Name of method to call
* @param rettype Return type of method
* @param thistype Type of object method is being generated on
*/
public static void populateSelfForwardingMethod(MethodNode method, String forwardname, Type rettype, Type thistype) {
InsnList code = method.instructions;
code.add(new VarInsnNode(thistype.getOpcode(Opcodes.ILOAD), 0));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, thistype.getInternalName(), forwardname, "()" + rettype.getDescriptor(), false));
code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
}
/**
* Populate a forwarding method of the form
* "T name(S object) { return object.forward(); }".
*
* @param method Method to generate code for
* @param forwardname Name of method to call
* @param rettype Return type of method
* @param argtype Type of object to call method on
* @param thistype Type of object method is being generated on
*/
public static void populateForwardingMethod(MethodNode method, String forwardname, Type rettype, Type argtype, Type thistype) {
InsnList code = method.instructions;
code.add(new VarInsnNode(argtype.getOpcode(Opcodes.ILOAD), 1));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, argtype.getInternalName(), forwardname, "()" + rettype.getDescriptor(), false));
code.add(new InsnNode(rettype.getOpcode(Opcodes.IRETURN)));
}
/**
* Gets an instruction that pushes a integer onto the stack. The instruction uses
* the smallest push possible (ICONST_*, BIPUSH, SIPUSH or Integer constant).
*
* @param c the integer to push onto the stack
*/
public static AbstractInsnNode pushIntConstant(int c) {
if (c == -1) {
return new InsnNode(Opcodes.ICONST_M1);
} else if (c >= 0 && c <= 5) {
return new InsnNode(intConstants[c]);
} else if (c >= Byte.MIN_VALUE && c <= Byte.MAX_VALUE) {
return new IntInsnNode(Opcodes.BIPUSH, c);
} else if (c >= Short.MIN_VALUE && c <= Short.MAX_VALUE) {
return new IntInsnNode(Opcodes.SIPUSH, c);
} else {
return new LdcInsnNode(c);
}
}
/**
* Finds a method given the method descriptor
*
* @param clazz the class to scan
* @param name the method name
* @param desc the method descriptor
*/
public static MethodNode findMethod(ClassNode clazz, String name, String desc) {
Iterator<MethodNode> i = clazz.methods.iterator();
while (i.hasNext()) {
MethodNode m = i.next();
if (m.name.equals(name) && m.desc.equals(desc)) {
return m;
}
}
return null;
}
/**
* Adds a method to a class, overwriting any matching method.
*
* @param clazz the class to scan
* @param method the method to add
*/
public static void addAndReplaceMethod(ClassNode clazz, MethodNode method) {
MethodNode m = findMethod(clazz, method.name, method.desc);
if (m != null) {
clazz.methods.remove(m);
}
clazz.methods.add(method);
}
/**
* Dumps the output of CheckClassAdapter.verify to System.out
*
* @param classNode the classNode to verify
*/
public static void dumpClass(ClassNode classNode) {
ClassWriter cw = new ClassWriter(COMPUTE_MAXS | COMPUTE_FRAMES);
classNode.accept(cw);
dumpClass(cw.toByteArray());
}
/**
* Dumps the output of CheckClassAdapter.verify to System.out
*
* @param bytes the bytecode of the class to check
*/
public static void dumpClass(byte[] bytes) {
ClassReader cr = new ClassReader(bytes);
CheckClassAdapter.verify(cr, true, new PrintWriter(System.out));
}
/**
* Get a runtime-visible annotation of the specified class from the supplied field node
*
* @param field Source field
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getVisibleAnnotation(FieldNode field, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(field.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an invisible annotation of the specified class from the supplied field node
*
* @param field Source field
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getInvisibleAnnotation(FieldNode field, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(field.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get a runtime-visible annotation of the specified class from the supplied method node
*
* @param method Source method
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getVisibleAnnotation(MethodNode method, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(method.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an invisible annotation of the specified class from the supplied method node
*
* @param method Source method
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getInvisibleAnnotation(MethodNode method, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(method.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get a runtime-visible annotation of the specified class from the supplied class node
*
* @param classNode Source classNode
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getVisibleAnnotation(ClassNode classNode, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(classNode.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an invisible annotation of the specified class from the supplied class node
*
* @param classNode Source classNode
* @param annotationClass Type of annotation to search for
* @return the annotation, or null if not present
*/
public static AnnotationNode getInvisibleAnnotation(ClassNode classNode, Class<? extends Annotation> annotationClass) {
return ASMHelper.getAnnotation(classNode.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Search for and return an annotation node matching the specified type within the supplied
* collection of annotation nodes
*
* @param annotations Haystack
* @param annotationType Needle
* @return matching annotation node or null if the annotation doesn't exist
*/
public static AnnotationNode getAnnotation(List<AnnotationNode> annotations, String annotationType) {
if (annotations == null) {
return null;
}
for (AnnotationNode annotation : annotations) {
if (annotationType.equals(annotation.desc)) {
return annotation;
}
}
return null;
}
/**
* Duck type the "value" entry (if any) of the specified annotation node
*
* @param annotation Annotation node to query
* @return duck-typed annotation value, null if missing, or inevitable ClassCastException if your duck is actually a rooster
*/
public static <T> T getAnnotationValue(AnnotationNode annotation) {
return ASMHelper.getAnnotationValue(annotation, "value");
}
/**
* Get the value of an annotation node and do pseudo-duck-typing via Java's crappy generics
*
* @param annotation Annotation node to query
* @param key Key to search for
* @return duck-typed annotation value, null if missing, or inevitable ClassCastException if your duck is actually a rooster
*/
@SuppressWarnings("unchecked")
public static <T> T getAnnotationValue(AnnotationNode annotation, String key) {
boolean getNextValue = false;
if (annotation.values == null) {
return null;
}
// Keys and value are stored in successive pairs, search for the key and if found return the following entry
for (Object value : annotation.values) {
if (getNextValue) {
return (T) value;
}
if (value.equals(key)) {
getNextValue = true;
}
}
return null;
}
}