Merge branch 'initphase'

Conflicts:
	src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
	src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java
This commit is contained in:
Mumfrey committed 2016-06-21 15:27:40 +01:00
commit a3b98d8a15
163 files changed
+15949 -3149

No files matched your search

+46 -16
View File
@@ -43,16 +43,6 @@ targetCompatibility = '1.6'
// Project repositories
repositories {
mavenCentral()
maven {
// for srg2source
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
// because Srg2Source needs an eclipse dependency.
name = "eclipse"
url = "https://repo.eclipse.org/content/groups/eclipse/"
}
maven {
name = 'minecraft'
url = 'https://libraries.minecraft.net/'
@@ -92,6 +82,12 @@ sourceSets {
fernflower {
compileClasspath += main.output
}
agent {
compileClasspath += main.output
}
bridge {
compileClasspath += main.output
}
}
// Dependencies for renamed ASM
@@ -127,15 +123,16 @@ task renamedASM {
}
}
}
eclipseClasspath.dependsOn(renamedASM)
// Project dependencies
dependencies {
compile 'org.slf4j:slf4j-api:1.7.7'
compile 'com.google.guava:guava:17.0'
compile 'net.minecraft:launchwrapper:1.11'
compile 'com.google.code.gson:gson:2.2.4'
compile 'commons-io:commons-io:2.4'
compile 'commons-codec:commons-codec:1.9'
apCompile 'com.google.guava:guava:17.0'
testCompile 'junit:junit:4.11'
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile 'org.mockito:mockito-core:1.9.0'
@@ -143,13 +140,10 @@ dependencies {
// maven
deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7'
// for annotation processor
compile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT'
apCompile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT'
// remapped ASM
compile tasks.renamedASM.outputs.files
apCompile tasks.renamedASM.outputs.files
agentCompile tasks.renamedASM.outputs.files
// fernflower bridge
fernflowerCompile 'commons-io:commons-io:2.4'
@@ -157,6 +151,14 @@ dependencies {
fernflowerCompile 'com.google.guava:guava:17.0'
fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT'
compile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT'
compile 'net.minecraft:launchwrapper:1.11'
agentCompile 'net.minecraft:launchwrapper:1.11'
// asm bridge
compile 'org.ow2.asm:asm-commons:5.0.3'
bridgeCompile 'org.ow2.asm:asm-commons:5.0.3'
bridgeCompile 'org.apache.logging.log4j:log4j-core:2.0-beta9'
}
// Filter, process, and include resources
@@ -212,6 +214,12 @@ jar {
// Include fernflower bridge
from sourceSets.fernflower.output
// Include hotswap agent
from sourceSets.agent.output
// Bridge
from sourceSets.bridge.output
// Renamed ASM
from zipTree(tasks.renamedASM.outputs.files[0])
@@ -226,7 +234,12 @@ jar {
"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)
"Implementation-Vendor": url,
// for hotswap agent
"Premain-Class": "org.spongepowered.tools.agent.MixinAgent",
"Agent-Class": "org.spongepowered.tools.agent.MixinAgent",
"Can-Redefine-Classes": true,
"Can-Retransform-Classes": true)
}
// generate shadow jar so we can use the AP standalone
@@ -259,6 +272,10 @@ task sourceJar(type: Jar) {
from sourceSets.ap.resources
from sourceSets.fernflower.java
from sourceSets.fernflower.resources
from sourceSets.agent.java
from sourceSets.agent.resources
from sourceSets.bridge.java
from sourceSets.bridge.resources
classifier = "sources"
}
@@ -315,7 +332,20 @@ uploadArchives {
}
}
}
whenConfigured {
dependencies = dependencies.findAll {
!it.artifactId.contains('fernflower')
}
}
}
}
}
}
install.repositories.mavenInstaller.pom {
whenConfigured {
dependencies = dependencies.findAll {
!it.artifactId.contains('fernflower')
}
}
}
+97 -165
View File
@@ -1,171 +1,103 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<?xml version="1.0" encoding="UTF-8"?>
<!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.
-->
This configuration file was written by the eclipse-cs plugin configuration editor
-->
<!--
Checkstyle-Configuration: Mixin Style
Description: none
-->
<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"/>
<property name="severity" value="warning"/>
<property name="charset" value="UTF-8"/>
<module name="TreeWalker">
<module name="FileContentsHolder"/>
<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>
<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="LineLength">
<property name="max" value="80"/>
<property name="ignorePattern" value="^[ ]*([a-zA-Z0-9\{\}\+\|\&amp;\&quot;@\(\)]|//)"/>
</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 name="FileContentsHolder" />
<module name="RequireThis" />
<module name="LineLength">
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
<property name="max" value="150"/>
</module>
<module name="SuppressionCommentFilter" />
<module name="LineLength">
<property name="ignorePattern" value="^[ ]*([a-zA-Z0-9\{\}\+\|\&amp;\&quot;@\(\)\?\.\:]|//)"/>
</module>
<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"/>
<message key="ws.notPreceded" value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
<message key="ws.notFollowed" value="WhitespaceAround: ''{0}'' is not followed by whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<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="format" value="^[a-z](([a-z0-9])|([a-z0-9][a-zA-Z0-9]*))?$"/>
<property name="tokens" value="VARIABLE_DEF"/>
<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.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
<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."/>
</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 name="RequireThis"/>
<module name="JavadocType">
<property name="scope" value="package"/>
</module>
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="SuppressionCommentFilter"/>
</module>
+295
View File
@@ -0,0 +1,295 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="12">
<profile kind="CodeFormatterProfile" name="Sponge" version="12">
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="48"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/>
<setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="4"/>
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="150"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/>
</profile>
</profiles>
+7
View File
@@ -0,0 +1,7 @@
#Organize Import Order
#Thu Jan 07 16:47:26 GMT 2016
4=com
3=org
2=javax
1=java
0=\#
+1 -1
View File
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
buildVersion=0.4.5
buildVersion=0.5.11
buildType=SNAPSHOT
+1 -1
View File
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-bin.zip
@@ -0,0 +1,223 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.agent;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import net.minecraft.launchwrapper.Launch;
/**
* An agent that re-transforms a mixin's target classes if the mixin has been
* redefined. Basically this agent enables hot-swapping of mixins.
*/
public class MixinAgent implements IHotSwap {
/**
* Class file transformer that re-transforms mixin's target classes if the
* mixin has been redefined.
*/
class Transformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain domain, byte[] classfileBuffer)
throws IllegalClassFormatException {
if (classBeingRedefined == null) {
return null;
}
byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined);
if (mixinBytecode != null) {
List<String> targets = this.reloadMixin(className, classfileBuffer);
if (targets == null || !this.reApplyMixins(targets)) {
return MixinAgent.ERROR_BYTECODE;
}
return mixinBytecode;
}
try {
MixinAgent.logger.info("Redefining class " + className);
return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer);
} catch (Throwable th) {
MixinAgent.logger.error("Error while re-transforming class " + className, th);
return MixinAgent.ERROR_BYTECODE;
}
}
private List<String> reloadMixin(String className, byte[] classfileBuffer) {
MixinAgent.logger.info("Redefining mixin {}", className);
try {
return MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer);
} catch (MixinReloadException e) {
MixinAgent.logger.error("Mixin {} cannot be reloaded, needs a restart to be applied: {} ", e.getMixinInfo(), e.getMessage());
} catch (Throwable th) {
// catch everything as otherwise it is ignored
MixinAgent.logger.error("Error while finding targets for mixin " + className, th);
}
return null;
}
/**
* Re-apply all mixins to the supplied list of target classes.
*
* @param targets Target classes to re-transform
* @return true if all targets were transformed, false if transformation
* failed
*/
private boolean reApplyMixins(List<String> targets) {
for (String target : targets) {
String targetName = target.replace('/', '.');
MixinAgent.logger.debug("Re-transforming target class {}", target);
try {
Class<?> targetClass = Launch.classLoader.findClass(targetName);
byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName);
if (targetBytecode == null) {
MixinAgent.logger.error("Target class {} bytecode is not registered", targetName);
return false;
}
targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode);
MixinAgent.instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode));
} catch (Throwable th) {
MixinAgent.logger.error("Error while re-transforming target class " + target, th);
return false;
}
}
return true;
}
}
/**
* Bytecode that signals an error. When returned from the class file
* transformer this causes a class file format exception and indicates in
* the ide that somethings went wrong.
*/
public static final byte[] ERROR_BYTECODE = new byte[]{1};
/**
* Class loader used to load mixin classes
*/
static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader();
static final Logger logger = LogManager.getLogger("mixin.agent");
/**
* Instance used to register the transformer
*/
static Instrumentation instrumentation = null;
/**
* Instances of all agents
*/
private static List<MixinAgent> agents = new ArrayList<MixinAgent>();
/**
* MixinTransformer instance to use to transform the mixin's target classes
*/
final MixinTransformer classTransformer;
/**
* Constructs an agent from a class transformer in which it will use to
* transform mixin's target class.
*
* @param classTransformer Class transformer that will transform a mixin's
* target class
*/
public MixinAgent(MixinTransformer classTransformer) {
this.classTransformer = classTransformer;
MixinAgent.agents.add(this);
if (MixinAgent.instrumentation != null) {
this.initTransformer();
}
}
private void initTransformer() {
MixinAgent.instrumentation.addTransformer(new Transformer(), true);
}
@Override
public void registerMixinClass(String name) {
MixinAgent.classLoader.addMixinClass(name);
}
@Override
public void registerTargetClass(String name, byte[] bytecode) {
MixinAgent.classLoader.addTargetClass(name, bytecode);
}
/**
* Sets the instrumentation instance so that the mixin agents can redefine
* mixins.
*
* @param instrumentation Instance to use to redefine the mixins
*/
public static void init(Instrumentation instrumentation) {
MixinAgent.instrumentation = instrumentation;
if (!MixinAgent.instrumentation.isRedefineClassesSupported()) {
MixinAgent.logger.error("The instrumentation doesn't support re-definition of classes");
}
for (MixinAgent agent : MixinAgent.agents) {
agent.initTransformer();
}
}
/**
* Initialize the java agent
*
* This will be called automatically if the jar is in a -javaagent java
* command line argument
*
* @param arg Ignored
* @param instrumentation Instance to use to transform the mixins
*/
public static void premain(String arg, Instrumentation instrumentation) {
System.setProperty("mixin.hotSwap", "true");
MixinAgent.init(instrumentation);
}
/**
* Initialize the java agent
*
* This will be called automatically if the java agent is loaded after jvm
* startup
*
* @param arg Ignored
* @param instrumentation Instance to use to re-define the mixins
*/
public static void agentmain(String arg, Instrumentation instrumentation) {
MixinAgent.init(instrumentation);
}
}
@@ -0,0 +1,130 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.agent;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.ClassWriter;
import org.spongepowered.asm.lib.MethodVisitor;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.util.Constants;
/**
* Class loader that is used to load fake mixin classes so that they can be
* re-defined.
*/
class MixinAgentClassLoader extends ClassLoader {
private static final Logger logger = LogManager.getLogger("mixin.agent");
/**
* Mapping of mixin mixin classes to their fake classes
*/
private Map<Class<?>, byte[]> mixins = new HashMap<Class<?>, byte[]>();
/**
* Mapping that keep track of bytecode for classes that are targeted by
* mixins
*/
private Map<String, byte[]> targets = new HashMap<String, byte[]>();
/**
* Add a fake mixin class
*
* @param name Name of the fake class
*/
void addMixinClass(String name) {
MixinAgentClassLoader.logger.debug("Mixin class {} added to class loader", name);
try {
byte[] bytes = this.materialise(name);
Class<?> clazz = this.defineClass(name, bytes, 0, bytes.length);
// apparently the class needs to be instantiated at least once
// to be including in list returned by allClasses() method in jdi api
clazz.newInstance();
this.mixins.put(clazz, bytes);
} catch (Throwable e) {
MixinAgentClassLoader.logger.catching(e);
}
}
/**
* Registers the bytecode for a class targeted by a mixin
*
* @param name Name of the target clas
* @param bytecode Bytecode of the target class
*/
void addTargetClass(String name, byte[] bytecode) {
this.targets.put(name, bytecode);
}
/**
* Gets the bytecode for a fake mixin class
*
* @param clazz Mixin class
* @return Bytecode of the fake mixin class
*/
byte[] getFakeMixinBytecode(Class<?> clazz) {
return this.mixins.get(clazz);
}
/**
* Gets the original bytecode for a target class
*
* @param name Name of the target class
* @return Original bytecode
*/
byte[] getOriginalTargetBytecode(String name) {
return this.targets.get(name);
}
/**
* Generates the simplest possible class that is instantiable
*
* @param name Name of the generated class
* @return Bytecode of the generated class
*/
private byte[] materialise(String name) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
cw.visit(MixinEnvironment.getCompatibilityLevel().classVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null,
Type.getInternalName(Object.class), null);
// create init method
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, Constants.CTOR, "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), Constants.CTOR, "()V", false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}
}
@@ -29,6 +29,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
@@ -40,13 +41,22 @@ import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
/**
* Convenience functions for mirror
*/
public abstract class MirrorUtils {
/**
* Number of times to recurse into TypeMirrors when trying to determine the
* upper bound of a TYPEVAR
*/
private static final int MAX_GENERIC_RECURSION_DEPTH = 5;
private static final String OBJECT_SIG = "java.lang.Object";
private static final String OBJECT_REF = "java/lang/Object";
// No instances for you
private MirrorUtils() {}
@@ -150,6 +160,61 @@ public abstract class MirrorUtils {
return parent.getClass().getSimpleName();
}
public static String getJavaSignature(Element element) {
if (element instanceof ExecutableElement) {
ExecutableElement method = (ExecutableElement)element;
StringBuilder desc = new StringBuilder().append("(");
boolean extra = false;
for (VariableElement arg : method.getParameters()) {
if (extra) {
desc.append(',');
}
desc.append(MirrorUtils.getTypeName(arg.asType()));
extra = true;
}
desc.append(')').append(method.getReturnType().toString());
return desc.toString();
}
return MirrorUtils.getTypeName(element.asType());
}
public static String stripGenerics(String type) {
StringBuilder sb = new StringBuilder();
for (int pos = 0, depth = 0; pos < type.length(); pos++) {
char c = type.charAt(pos);
if (c == '<') {
depth++;
}
if (depth == 0) {
sb.append(c);
} else if (c == '>') {
depth--;
}
}
return sb.toString();
}
public static String getTypeName(TypeMirror type) {
switch (type.getKind()) {
case ARRAY: return MirrorUtils.getTypeName(((ArrayType)type).getComponentType()) + "[]";
case DECLARED: return MirrorUtils.getTypeName((DeclaredType)type);
case TYPEVAR: return MirrorUtils.getTypeName(MirrorUtils.getUpperBound(type));
case ERROR: return MirrorUtils.OBJECT_SIG;
default: return type.toString();
}
}
public static String getTypeName(DeclaredType type) {
if (type == null) {
return MirrorUtils.OBJECT_SIG;
}
return MirrorUtils.getTypeName((TypeElement)type.asElement());
}
private static String getTypeName(TypeElement elem) {
return MirrorUtils.getInternalName(elem).replace('/', '.');
}
public static String generateSignature(ExecutableElement method) {
StringBuilder signature = new StringBuilder();
@@ -164,11 +229,12 @@ public abstract class MirrorUtils {
public static String getInternalName(VariableElement var) {
return MirrorUtils.getInternalName(var.asType());
}
public static String getInternalName(TypeMirror type) {
switch (type.getKind()) {
case ARRAY: return "[" + MirrorUtils.getInternalName(((ArrayType)type).getComponentType());
case DECLARED: return "L" + MirrorUtils.getInternalName((DeclaredType)type) + ";";
case TYPEVAR: return "L" + MirrorUtils.getInternalName(MirrorUtils.getUpperBound(type)) + ";";
case BOOLEAN: return "Z";
case BYTE: return "B";
case CHAR: return "C";
@@ -179,14 +245,50 @@ public abstract class MirrorUtils {
case SHORT: return "S";
case VOID: return "V";
// TODO figure out a better way to not crash when we get here
case ERROR: return "Ljava/lang/Object;";
case ERROR: return "L" + MirrorUtils.OBJECT_REF + ";";
default:
}
throw new IllegalArgumentException("Unable to parse type symbol " + type + " with " + type.getKind() + " to equivalent bytecode type");
}
private static DeclaredType getUpperBound(TypeMirror type) {
try {
return MirrorUtils.getUpperBound0(type, MirrorUtils.MAX_GENERIC_RECURSION_DEPTH);
} catch (IllegalStateException ex) {
throw new IllegalArgumentException("Type symbol \"" + type + "\" is too complex", ex);
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Unable to compute upper bound of type symbol " + type, ex);
}
}
private static DeclaredType getUpperBound0(TypeMirror type, int depth) {
if (depth == 0) {
throw new IllegalStateException("Generic symbol \"" + type + "\" is too complex, exceeded "
+ MirrorUtils.MAX_GENERIC_RECURSION_DEPTH + " iterations attempting to determine upper bound");
}
if (type instanceof DeclaredType) {
return (DeclaredType)type;
}
if (type instanceof TypeVariable) {
try {
TypeMirror upper = ((TypeVariable)type).getUpperBound();
return MirrorUtils.getUpperBound0(upper, --depth);
} catch (IllegalStateException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception ex) {
throw new IllegalArgumentException("Unable to compute upper bound of type symbol " + type);
}
}
return null;
}
public static String getInternalName(DeclaredType type) {
if (type == null) {
return MirrorUtils.OBJECT_REF;
}
return MirrorUtils.getInternalName((TypeElement)type.asElement());
}
@@ -204,4 +306,20 @@ public abstract class MirrorUtils {
}
return reference.toString();
}
public static boolean isAssignable(ProcessingEnvironment processingEnv, TypeMirror targetType, TypeMirror superClass) {
boolean assignable = processingEnv.getTypeUtils().isAssignable(targetType, superClass);
if (!assignable && targetType instanceof DeclaredType && superClass instanceof DeclaredType) {
TypeMirror rawTargetType = MirrorUtils.toRawType(processingEnv, (DeclaredType)targetType);
TypeMirror rawSuperType = MirrorUtils.toRawType(processingEnv, (DeclaredType)superClass);
return processingEnv.getTypeUtils().isAssignable(rawTargetType, rawSuperType);
}
return assignable;
}
private static TypeMirror toRawType(ProcessingEnvironment processingEnv, DeclaredType targetType) {
return processingEnv.getElementUtils().getTypeElement(((TypeElement)targetType.asElement()).getQualifiedName()).asType();
}
}
@@ -24,7 +24,6 @@
*/
package org.spongepowered.tools.obfuscation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -34,9 +33,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
@@ -44,186 +44,50 @@ import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.ConstraintViolationException;
import org.spongepowered.asm.util.InvalidConstraintException;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass;
import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager;
import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider;
import org.spongepowered.tools.obfuscation.struct.Message;
/**
* Information about a mixin stored during processing
*/
class AnnotatedMixin {
/**
* A name of an element which may have aliases
*/
static class AliasedElementName {
/**
* The original name including any original prefix (the "actual" name)
*/
protected final String originalName;
/**
* Aliases declared by the annotation (if any), never null
*/
private final List<String> aliases;
public AliasedElementName(Element element, AnnotationMirror annotation) {
this.originalName = element.getSimpleName().toString();
List<AnnotationValue> aliases = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(annotation, "aliases");
this.aliases = MirrorUtils.<String>unfold(aliases);
}
/**
* Get whether this member has any aliases defined
*/
public boolean hasAliases() {
return this.aliases.size() > 0;
}
/**
* Get this member's aliases
*/
public List<String> getAliases() {
return this.aliases;
}
/**
* Gets the original name of the member (including prefix)
*/
public String elementName() {
return this.originalName;
}
public String baseName() {
return this.originalName;
}
}
/**
* Convenience class to store information about an
* {@link org.spongepowered.asm.mixin.Shadow}ed member's names
*/
static class ShadowElementName extends AliasedElementName {
/**
* True if the real element is prefixed
*/
private final boolean hasPrefix;
/**
* Expected prefix read from the annotation, this is set even if
* {@link #hasPrefix} is false
*/
private final String prefix;
/**
* The base name without the prefix
*/
private final String baseName;
/**
* Obfuscated name (once determined)
*/
private String obfuscated;
ShadowElementName(Element element, AnnotationMirror shadow) {
super(element, shadow);
this.prefix = MirrorUtils.<String>getAnnotationValue(shadow, "prefix", "shadow$");
boolean hasPrefix = false;
String name = this.originalName;
if (name.startsWith(this.prefix)) {
hasPrefix = true;
name = name.substring(this.prefix.length());
}
this.hasPrefix = hasPrefix;
this.obfuscated = this.baseName = name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.baseName;
}
@Override
public String baseName() {
return this.baseName;
}
/**
* Sets the obfuscated name for this element
*
* @param name New name
* @return fluent interface
*/
public ShadowElementName setObfuscatedName(String name) {
this.obfuscated = name.substring(name.lastIndexOf('/') + 1);
return this;
}
/**
* Get the prefix (if set), does not return the expected prefix
*/
public String prefix() {
return this.hasPrefix ? this.prefix : "";
}
/**
* Get the base name
*/
public String name() {
return this.prefix(this.baseName);
}
/**
* Gets the obfuscated name (including prefix where appropriate
*/
public String obfuscated() {
return this.prefix(this.obfuscated);
}
/**
* Apply the prefix (if any) to the specified string
*
* @param name String to prefix
* @return Prefixed string or original string if no prefix
*/
public String prefix(String name) {
return this.hasPrefix ? this.prefix + name : name;
}
}
/**
* Mixin annotation
*/
private final AnnotationMirror annotation;
/**
/**
* Messager
*/
private final Messager messager;
/**
* Type handle provider
*/
private final ITypeHandleProvider typeProvider;
/**
* Manager
*/
private final AnnotatedMixins mixins;
private final IObfuscationManager obf;
/**
* Mixin class
*/
private final TypeElement mixin;
/**
* Mixin class
*/
private final TypeHandle handle;
/**
* Specified targets
*/
@@ -252,18 +116,35 @@ class AnnotatedMixin {
/**
* Stored (ordered) field mappings
*/
private final Set<String> fieldMappings = new LinkedHashSet<String>();
private final Map<ObfuscationType, Set<String>> fieldMappings = new HashMap<ObfuscationType, Set<String>>();
/**
* Stored (ordered) method mappings
*/
private final Set<String> methodMappings = new LinkedHashSet<String>();
private final Map<ObfuscationType, Set<String>> methodMappings = new HashMap<ObfuscationType, Set<String>>();
/**
* Overwrite handler
*/
private final AnnotatedMixinOverwriteHandler overwrites;
/**
* Shadow handler
*/
private final AnnotatedMixinShadowHandler shadows;
/**
* Injector handler
*/
private final AnnotatedMixinInjectorHandler injectors;
public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type) {
public AnnotatedMixin(IMixinAnnotationProcessor ap, TypeElement type) {
this.annotation = MirrorUtils.getAnnotation(type, Mixin.class);
this.mixins = mixins;
this.typeProvider = ap.getTypeProvider();
this.obf = ap.getObfuscationManager();
this.messager = ap;
this.mixin = type;
this.handle = new TypeHandle(type);
this.classRef = type.getQualifiedName().toString().replace('.', '/');
TypeHandle primaryTarget = this.initTargets();
@@ -276,6 +157,15 @@ class AnnotatedMixin {
}
this.remap = AnnotatedMixins.getRemapValue(this.annotation) && this.targets.size() > 0;
for (ObfuscationType obfType : ObfuscationType.values()) {
this.fieldMappings.put(obfType, new LinkedHashSet<String>());
this.methodMappings.put(obfType, new LinkedHashSet<String>());
}
this.overwrites = new AnnotatedMixinOverwriteHandler(ap, this);
this.shadows = new AnnotatedMixinShadowHandler(ap, this);
this.injectors = new AnnotatedMixinInjectorHandler(ap, this);
}
AnnotatedMixin runValidators(ValidationPass pass, Collection<IMixinValidator> validators) {
@@ -300,13 +190,13 @@ class AnnotatedMixin {
if (this.targets.contains(type)) {
continue;
}
this.targets.add(type);
this.addTarget(type);
if (primaryTarget == null) {
primaryTarget = type;
}
}
} catch (Exception ex) {
this.mixins.printMessage(Kind.WARNING, "Error processing public targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
this.printMessage(Kind.WARNING, "Error processing public targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
}
// Private targets, referenced by name
@@ -314,33 +204,53 @@ class AnnotatedMixin {
List<AnnotationValue> privateTargets = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(this.annotation, "targets",
Collections.<AnnotationValue>emptyList());
for (String privateTarget : MirrorUtils.<String>unfold(privateTargets)) {
TypeHandle type = this.mixins.getTypeHandle(privateTarget);
TypeHandle type = this.typeProvider.getTypeHandle(privateTarget);
if (this.targets.contains(type)) {
continue;
}
if (type == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this);
this.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this);
return null;
} else if (type.isPublic()) {
this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " is public and must be specified in value", this);
this.printMessage(Kind.WARNING, "Mixin target " + privateTarget + " is public and must be specified in value", this);
return null;
}
this.targets.add(type);
this.addSoftTarget(type, privateTarget);
if (primaryTarget == null) {
primaryTarget = type;
}
}
} catch (Exception ex) {
this.mixins.printMessage(Kind.WARNING, "Error processing private targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
this.printMessage(Kind.WARNING, "Error processing private targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
}
if (primaryTarget == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin has no targets", this);
this.printMessage(Kind.ERROR, "Mixin has no targets", this);
}
return primaryTarget;
}
/**
* Print a message to the AP messager
*/
private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) {
this.messager.printMessage(kind, msg, this.mixin, this.annotation);
}
private void addSoftTarget(TypeHandle type, String reference) {
ObfuscationData<String> obfClassData = this.obf.getObfClass(type);
if (!obfClassData.isEmpty()) {
this.obf.addClassMapping(this.classRef, reference, obfClassData);
}
this.addTarget(type);
}
private void addTarget(TypeHandle type) {
this.targets.add(type);
}
@Override
public String toString() {
return this.mixin.getSimpleName().toString();
@@ -357,6 +267,41 @@ class AnnotatedMixin {
return this.mixin;
}
/**
* Get the type handle for the mixin class
*/
public TypeHandle getHandle() {
return this.handle;
}
/**
* Get the mixin class reference
*/
public String getClassRef() {
return this.classRef;
}
/**
* Get whether this is an interface mixin
*/
public boolean isInterface() {
return this.mixin.getKind() == ElementKind.INTERFACE;
}
/**
* Get the <em>primary</em> target class reference
*/
public String getPrimaryTargetRef() {
return this.targetRef;
}
/**
* Get the <em>primary</em> target
*/
public TypeHandle getPrimaryTarget() {
return this.targetType;
}
/**
* Get the mixin's targets
*/
@@ -374,15 +319,15 @@ class AnnotatedMixin {
/**
* Get stored field mappings
*/
public Set<String> getFieldMappings() {
return this.fieldMappings;
public Set<String> getFieldMappings(ObfuscationType type) {
return this.fieldMappings.get(type);
}
/**
* Get stored method mappings
*/
public Set<String> getMethodMappings() {
return this.methodMappings;
public Set<String> getMethodMappings(ObfuscationType type) {
return this.methodMappings.get(type);
}
/**
@@ -393,347 +338,32 @@ class AnnotatedMixin {
this.methodMappings.clear();
}
/**
* Validate method for {@link org.spongepowered.asm.mixin.Shadow} and
* {@link org.spongepowered.asm.mixin.Overwrite} registrations to check that
* only a single target is registered. Mixins containing annotated methods
* with these annotations cannot be multi-targetted.
*/
private boolean validateSingleTarget(String annotation, Element element) {
if (this.targetRef == null || this.targets.size() > 1) {
this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", element);
this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", this.mixin);
return false;
}
return true;
}
/**
* Register an {@link org.spongepowered.asm.mixin.Overwrite} method
*/
public void registerOverwrite(ExecutableElement method, AnnotationMirror overwrite) {
AliasedElementName name = new AliasedElementName(method, overwrite);
this.validateTargetMethod(method, overwrite, name, "@Overwrite");
this.checkConstraints(method, overwrite);
if (!this.remap || !this.validateSingleTarget("@Overwrite", method)) {
return;
}
String mcpName = method.getSimpleName().toString();
String mcpSignature = MirrorUtils.generateSignature(method);
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + mcpName, mcpSignature));
if (obfMethod == null) {
Kind error = Kind.ERROR;
try {
// Try to access isStatic from com.sun.tools.javac.code.Symbol
Method md = method.getClass().getMethod("isStatic");
if (((Boolean)md.invoke(method)).booleanValue()) {
error = Kind.WARNING;
}
} catch (Exception ex) {
// well, we tried
}
this.mixins.printMessage(error, "No obfuscation mapping for @Overwrite method", method);
return;
}
String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
this.addMethodMapping(mcpName, obfName, mcpSignature, obfMethod.sig);
this.overwrites.registerOverwrite(method, overwrite);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} field
*/
public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean remap) {
ShadowElementName name = new ShadowElementName(field, shadow);
this.validateTargetField(field, shadow, name, "@Shadow");
if (!remap || !this.validateSingleTarget("@Shadow", field)) {
return;
}
String obfField = this.mixins.getObfField(this.targetRef + "/" + name);
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow);
return;
}
this.addFieldMapping(name.setObfuscatedName(obfField));
public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean shouldRemap) {
this.shadows.registerShadow(field, shadow, shouldRemap);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} method
*/
public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean remap) {
ShadowElementName name = new ShadowElementName(method, shadow);
this.validateTargetMethod(method, shadow, name, "@Shadow");
if (!remap || !this.validateSingleTarget("@Shadow", method)) {
return;
}
String mcpSignature = MirrorUtils.generateSignature(method);
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + name, mcpSignature));
if (obfMethod == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow);
return;
}
this.addMethodMapping(name.setObfuscatedName(obfMethod.name), mcpSignature, obfMethod.sig);
public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean shouldRemap) {
this.shadows.registerShadow(method, shadow, shouldRemap);
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.Inject} method
*/
public void registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) {
String originalReference = MirrorUtils.<String>getAnnotationValue(inject, "method");
MemberInfo targetMember = MemberInfo.parse(originalReference);
if (targetMember.name == null) {
return;
}
if (targetMember.desc != null) {
this.validateReferencedTarget(method, inject, targetMember, "@Inject");
}
if (!remap || !this.validateSingleTarget("@Inject", method)) {
return;
}
String desc = this.targetType.findDescriptor(targetMember);
if (desc == null) {
if (this.targetType.isImaginary()) {
this.mixins.printMessage(Kind.WARNING, "@Inject target requires method signature because enclosing type information is unavailable",
method, inject);
} else if (!Constants.INIT.equals(targetMember.name)) {
this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for @Inject target method", method, inject);
}
return;
}
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
if (obfMethod == null) {
Kind error = Constants.INIT.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR;
this.mixins.printMessage(error, "No obfuscation mapping for @Inject target " + targetMember.name, method, inject);
return;
}
String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
MemberInfo remappedReference = new MemberInfo(obfName, this.targetRef, obfMethod.sig, false);
this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString());
public Message registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) {
return this.injectors.registerInjector(method, inject, remap);
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.At} annotation
* and process the references
*/
public void registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) {
if (!AnnotatedMixins.getRemapValue(at)) {
return;
}
String type = MirrorUtils.<String>getAnnotationValue(at, "value");
String target = MirrorUtils.<String>getAnnotationValue(at, "target");
this.remapReference(type + ".<target>", target, element, inject, at);
// Pattern for replacing references in args, not used yet
// if ("SOMETYPE".equals(type)) {
// Map<String, String> args = AnnotatedMixin.getAtArgs(at);
// this.remapReference(type + ".args[target]", args.get("target"));
// }
public int registerInjectionPoint(ExecutableElement element, AnnotationMirror inject, AnnotationMirror at) {
return this.injectors.registerInjectionPoint(element, inject, at);
}
private void remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) {
if (target == null) {
return;
}
MemberInfo targetMember = MemberInfo.parse(target);
if (!targetMember.isFullyQualified()) {
String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature");
this.mixins.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject);
return;
}
MemberInfo remappedReference = null;
if (targetMember.isField()) {
String obfField = this.mixins.getObfField(targetMember.toSrg());
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject);
return;
}
remappedReference = MemberInfo.fromSrgField(obfField, targetMember.desc);
} else {
MethodData obfMethod = this.mixins.getObfMethod(targetMember);
if (obfMethod == null) {
if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) {
this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject);
}
return;
}
remappedReference = targetMember.remapUsing(obfMethod, false);
}
this.mixins.getReferenceMapper().addMapping(this.classRef, target, remappedReference.toString());
void addFieldMapping(ObfuscationType type, String mapping) {
this.fieldMappings.get(type).add(mapping);
}
/**
* Add a field mapping to the local table
*/
private void addFieldMapping(ShadowElementName name) {
String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated());
this.fieldMappings.add(mapping);
void addMethodMapping(ObfuscationType type, String mapping) {
this.methodMappings.get(type).add(mapping);
}
/**
* Add a method mapping to the local table
*/
private void addMethodMapping(ShadowElementName name, String mcpSignature, String obfSignature) {
this.addMethodMapping(name.name(), name.obfuscated(), mcpSignature, obfSignature);
}
/**
* Add a method mapping to the local table
*/
private void addMethodMapping(String mcpName, String obfName, String mcpSignature, String obfSignature) {
String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature);
this.methodMappings.add(mapping);
}
/**
* Check constraints for the specified annotation based on token values in
* the current environment
*
* @param method Annotated method
* @param annotation Annotation to check constraints
*/
private void checkConstraints(ExecutableElement method, AnnotationMirror annotation) {
try {
Constraint constraint = ConstraintParser.parse(MirrorUtils.<String>getAnnotationValue(annotation, "constraints"));
try {
constraint.check(this.mixins);
} catch (ConstraintViolationException ex) {
this.mixins.printMessage(Kind.ERROR, ex.getMessage(), method, annotation);
}
} catch (InvalidConstraintException ex) {
this.mixins.printMessage(Kind.WARNING, ex.getMessage(), method, annotation);
}
}
/**
* Checks whether the specified method exists in all targets and raises
* warnings where appropriate
*/
private void validateTargetMethod(ExecutableElement method, AnnotationMirror annotation, AliasedElementName name, String type) {
String signature = TypeHandle.getElementSignature(method);
for (TypeHandle target : this.targets) {
if (target.isImaginary()) {
continue;
}
// Find method as-is
MethodHandle targetMethod = target.findMethod(method);
if (targetMethod != null) {
continue;
}
if (!name.baseName().equals(name.elementName())) {
// Find method without prefix
targetMethod = target.findMethod(name.baseName(), signature);
if (targetMethod != null) {
continue;
}
}
// Check aliases
for (String alias : name.getAliases()) {
if ((targetMethod = target.findMethod(alias, signature)) != null) {
break;
}
}
if (targetMethod == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation);
}
}
}
/**
* Checks whether the specified field exists in all targets and raises
* warnings where appropriate
*/
private void validateTargetField(VariableElement field, AnnotationMirror shadow, AliasedElementName name, String type) {
String fieldType = field.asType().toString();
for (TypeHandle target : this.targets) {
if (target.isImaginary()) {
continue;
}
// Search for field
FieldHandle targetField = target.findField(field);
if (targetField != null) {
continue;
}
// Try search by alias
List<String> aliases = name.getAliases();
for (String alias : aliases) {
if ((targetField = target.findField(alias, fieldType)) != null) {
break;
}
}
if (targetField == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, shadow);
}
}
}
/**
* Checks whether the referenced method exists in all targets and raises
* warnings where appropriate
*/
private void validateReferencedTarget(ExecutableElement method, AnnotationMirror inject, MemberInfo reference, String type) {
String signature = reference.toDescriptor();
for (TypeHandle target : this.targets) {
if (target.isImaginary()) {
continue;
}
MethodHandle targetMethod = target.findMethod(reference.name, signature);
if (targetMethod == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject);
}
}
}
static Map<String, String> getAtArgs(AnnotationMirror at) {
Map<String, String> args = new HashMap<String, String>();
List<AnnotationValue> argv = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(at, "args");
if (argv != null) {
for (AnnotationValue av : argv) {
String arg = (String)av.getValue();
if (arg == null) {
continue;
}
int eqPos = arg.indexOf('=');
if (eqPos > -1) {
args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1));
} else {
args.put(arg, "");
}
}
}
return args;
}
}
@@ -0,0 +1,410 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.throwables.ConstraintViolationException;
import org.spongepowered.asm.util.throwables.InvalidConstraintException;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager;
/**
* Base class for module for {@link AnnotatedMixin} which handle different
* aspects of mixin target classes
*/
abstract class AnnotatedMixinElementHandler {
/**
* A name of an element which may have aliases
*/
static class AliasedElementName {
/**
* The original name including any original prefix (the "actual" name)
*/
protected final String originalName;
/**
* Aliases declared by the annotation (if any), never null
*/
private final List<String> aliases;
public AliasedElementName(Element element, AnnotationMirror annotation) {
this.originalName = element.getSimpleName().toString();
List<AnnotationValue> aliases = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(annotation, "aliases");
this.aliases = MirrorUtils.<String>unfold(aliases);
}
/**
* Get whether this member has any aliases defined
*/
public boolean hasAliases() {
return this.aliases.size() > 0;
}
/**
* Get this member's aliases
*/
public List<String> getAliases() {
return this.aliases;
}
/**
* Gets the original name of the member (including prefix)
*/
public String elementName() {
return this.originalName;
}
public String baseName() {
return this.originalName;
}
}
/**
* Convenience class to store information about an
* {@link org.spongepowered.asm.mixin.Shadow}ed member's names
*/
static class ShadowElementName extends AliasedElementName {
/**
* True if the real element is prefixed
*/
private final boolean hasPrefix;
/**
* Expected prefix read from the annotation, this is set even if
* {@link #hasPrefix} is false
*/
private final String prefix;
/**
* The base name without the prefix
*/
private final String baseName;
/**
* Obfuscated name (once determined)
*/
private String obfuscated;
ShadowElementName(Element element, AnnotationMirror shadow) {
super(element, shadow);
this.prefix = MirrorUtils.<String>getAnnotationValue(shadow, "prefix", "shadow$");
boolean hasPrefix = false;
String name = this.originalName;
if (name.startsWith(this.prefix)) {
hasPrefix = true;
name = name.substring(this.prefix.length());
}
this.hasPrefix = hasPrefix;
this.obfuscated = this.baseName = name;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.baseName;
}
@Override
public String baseName() {
return this.baseName;
}
/**
* Sets the obfuscated name for this element
*
* @param name New name
* @return fluent interface
*/
public ShadowElementName setObfuscatedName(String name) {
this.obfuscated = name.substring(name.lastIndexOf('/') + 1);
return this;
}
/**
* Get the prefix (if set), does not return the expected prefix
*/
public String prefix() {
return this.hasPrefix ? this.prefix : "";
}
/**
* Get the base name
*/
public String name() {
return this.prefix(this.baseName);
}
/**
* Gets the obfuscated name (including prefix where appropriate
*/
public String obfuscated() {
return this.prefix(this.obfuscated);
}
/**
* Apply the prefix (if any) to the specified string
*
* @param name String to prefix
* @return Prefixed string or original string if no prefix
*/
public String prefix(String name) {
return this.hasPrefix ? this.prefix + name : name;
}
}
/**
* Mixin
*/
protected final AnnotatedMixin mixin;
protected final String classRef;
/**
* Annotation processor
*/
protected final IMixinAnnotationProcessor ap;
/**
* Manager
*/
protected final IObfuscationManager obf;
AnnotatedMixinElementHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
this.ap = ap;
this.mixin = mixin;
this.classRef = mixin.getClassRef();
this.obf = ap.getObfuscationManager();
}
protected final boolean remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) {
if (target == null) {
return false;
}
MemberInfo targetMember = MemberInfo.parse(target);
if (!targetMember.isFullyQualified()) {
String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature");
this.ap.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject);
return false;
}
try {
targetMember.validate();
} catch (InvalidMemberDescriptorException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), element, inject);
}
if (targetMember.isField()) {
ObfuscationData<String> obfFieldData = this.obf.getObfFieldRecursive(targetMember);
if (obfFieldData.isEmpty()) {
this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject);
return false;
}
this.obf.addFieldMapping(this.classRef, target, targetMember, obfFieldData);
} else {
ObfuscationData<SrgMethod> obfMethodData = this.obf.getObfMethodRecursive(targetMember);
if (obfMethodData.isEmpty()) {
if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) {
this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject);
}
}
this.obf.addMethodMapping(this.classRef, target, targetMember, obfMethodData);
}
return true;
}
/**
* Add a field mapping to the local table
*/
protected final void addFieldMapping(ObfuscationType type, ShadowElementName name) {
String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated());
this.mixin.addFieldMapping(type, mapping);
}
/**
* Add a method mapping to the local table
*/
protected final void addMethodMapping(ObfuscationType type, ShadowElementName name, String mcpSignature, String obfSignature) {
this.addMethodMapping(type, name.name(), name.obfuscated(), mcpSignature, obfSignature);
}
/**
* Add a method mapping to the local table
*/
protected final void addMethodMapping(ObfuscationType type, String mcpName, String obfName, String mcpSignature, String obfSignature) {
String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature);
this.mixin.addMethodMapping(type, mapping);
}
/**
* Validate method for {@link org.spongepowered.asm.mixin.Shadow} and
* {@link org.spongepowered.asm.mixin.Overwrite} registrations to check that
* only a single target is registered. Mixins containing annotated methods
* with these annotations cannot be multi-targetted.
*/
protected final boolean validateSingleTarget(String annotation, Element element) {
if (this.mixin.getPrimaryTargetRef() == null || this.mixin.getTargets().size() > 1) {
this.ap.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", element);
this.ap.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", this.mixin.getMixin());
return false;
}
return true;
}
/**
* Check constraints for the specified annotation based on token values in
* the current environment
*
* @param method Annotated method
* @param annotation Annotation to check constraints
*/
protected final void checkConstraints(ExecutableElement method, AnnotationMirror annotation) {
try {
Constraint constraint = ConstraintParser.parse(MirrorUtils.<String>getAnnotationValue(annotation, "constraints"));
try {
constraint.check(this.ap.getTokenProvider());
} catch (ConstraintViolationException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, annotation);
}
} catch (InvalidConstraintException ex) {
this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation);
}
}
/**
* Checks whether the specified method exists in all targets and raises
* warnings where appropriate
*/
protected final void validateTargetMethod(ExecutableElement method, AnnotationMirror annotation, AliasedElementName name, String type) {
String signature = MirrorUtils.getJavaSignature(method);
for (TypeHandle target : this.mixin.getTargets()) {
if (target.isImaginary()) {
continue;
}
// Find method as-is
MethodHandle targetMethod = target.findMethod(method);
if (targetMethod != null) {
continue;
}
if (!name.baseName().equals(name.elementName())) {
// Find method without prefix
targetMethod = target.findMethod(name.baseName(), signature);
if (targetMethod != null) {
continue;
}
}
// Check aliases
for (String alias : name.getAliases()) {
if ((targetMethod = target.findMethod(alias, signature)) != null) {
break;
}
}
if (targetMethod == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation);
}
}
}
/**
* Checks whether the specified field exists in all targets and raises
* warnings where appropriate
*/
protected final void validateTargetField(VariableElement field, AnnotationMirror shadow, AliasedElementName name, String type) {
String fieldType = field.asType().toString();
for (TypeHandle target : this.mixin.getTargets()) {
if (target.isImaginary()) {
continue;
}
// Search for field
FieldHandle targetField = target.findField(field);
if (targetField != null) {
continue;
}
// Try search by alias
List<String> aliases = name.getAliases();
for (String alias : aliases) {
if ((targetField = target.findField(alias, fieldType)) != null) {
break;
}
}
if (targetField == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, shadow);
}
}
}
/**
* Checks whether the referenced method exists in all targets and raises
* warnings where appropriate
*/
protected final void validateReferencedTarget(ExecutableElement method, AnnotationMirror inject, MemberInfo reference, String type) {
String signature = reference.toDescriptor();
for (TypeHandle target : this.mixin.getTargets()) {
if (target.isImaginary()) {
continue;
}
MethodHandle targetMethod = target.findMethod(reference.name, signature);
if (targetMethod == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject);
}
}
}
}
@@ -0,0 +1,155 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.struct.Message;
/**
* A module for {@link AnnotatedMixin} whic handles injectors
*/
class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler {
AnnotatedMixinInjectorHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.Inject} method
*
* @param method Callback method
* @param inject Inject annotation
* @param remap
* @return pending error message or null if no error condition
*/
public Message registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) {
if (this.mixin.isInterface()) {
this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", method);
}
String originalReference = MirrorUtils.<String>getAnnotationValue(inject, "method");
MemberInfo targetMember = MemberInfo.parse(originalReference);
if (targetMember.name == null) {
return null;
}
try {
targetMember.validate();
} catch (InvalidMemberDescriptorException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, inject);
}
String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + "";
if (targetMember.desc != null) {
this.validateReferencedTarget(method, inject, targetMember, type);
}
if (!remap || !this.validateSingleTarget(type, method)) {
return null;
}
String desc = this.mixin.getPrimaryTarget().findDescriptor(targetMember);
if (desc == null) {
if (this.mixin.getPrimaryTarget().isImaginary()) {
this.ap.printMessage(Kind.WARNING, type + " target requires method signature because enclosing type information is unavailable",
method, inject);
} else if (!Constants.CTOR.equals(targetMember.name)) {
this.ap.printMessage(Kind.WARNING, "Unable to determine signature for " + type + " target method", method, inject);
}
return null;
}
ObfuscationData<SrgMethod> obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + targetMember.name, desc));
if (obfData.isEmpty()) {
Kind error = Constants.CTOR.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR;
return new Message(error, "No obfuscation mapping for " + type + " target " + targetMember.name, method, inject);
}
this.obf.addMethodMapping(this.classRef, originalReference, obfData);
return null;
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.At} annotation
* and process the references
*/
public int registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) {
if (this.mixin.isInterface()) {
this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", element);
}
if (!AnnotatedMixins.getRemapValue(at)) {
return 0;
}
String type = MirrorUtils.<String>getAnnotationValue(at, "value");
String target = MirrorUtils.<String>getAnnotationValue(at, "target");
int remapped = this.remapReference(type + ".<target>", target, element, inject, at) ? 1 : 0;
// Pattern for replacing references in args, not used yet
// if ("SOMETYPE".equals(type)) {
// Map<String, String> args = InjectorHandler.getAtArgs(at);
// this.remapReference(type + ".args[target]", args.get("target"));
// }
return remapped;
}
static Map<String, String> getAtArgs(AnnotationMirror at) {
Map<String, String> args = new HashMap<String, String>();
List<AnnotationValue> argv = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(at, "args");
if (argv != null) {
for (AnnotationValue av : argv) {
String arg = (String)av.getValue();
if (arg == null) {
continue;
}
int eqPos = arg.indexOf('=');
if (eqPos > -1) {
args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1));
} else {
args.put(arg, "");
}
}
}
return args;
}
}
@@ -0,0 +1,101 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.lang.reflect.Method;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
/**
* A module for {@link AnnotatedMixin} which handles method overwrites
*/
class AnnotatedMixinOverwriteHandler extends AnnotatedMixinElementHandler {
AnnotatedMixinOverwriteHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
}
void registerOverwrite(ExecutableElement method, AnnotationMirror overwrite) {
AliasedElementName name = new AliasedElementName(method, overwrite);
this.validateTargetMethod(method, overwrite, name, "@Overwrite");
this.checkConstraints(method, overwrite);
if (!this.mixin.remap() || !this.validateSingleTarget("@Overwrite", method)) {
return;
}
String mcpName = method.getSimpleName().toString();
String mcpSignature = MirrorUtils.generateSignature(method);
ObfuscationData<SrgMethod> obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + mcpName, mcpSignature));
if (obfData.isEmpty()) {
Kind error = Kind.ERROR;
try {
// Try to access isStatic from com.sun.tools.javac.code.Symbol
Method md = method.getClass().getMethod("isStatic");
if (((Boolean)md.invoke(method)).booleanValue()) {
error = Kind.WARNING;
}
} catch (Exception ex) {
// well, we tried
}
this.ap.printMessage(error, "No obfuscation mapping for @Overwrite method", method);
return;
}
for (ObfuscationType type : obfData) {
SrgMethod obfMethod = obfData.get(type);
this.addMethodMapping(type, mcpName, obfMethod.getSimpleName(), mcpSignature, obfMethod.getDesc());
}
if (!"true".equalsIgnoreCase(this.ap.getOption(SupportedOptions.DISABLE_OVERWRITE_CHECKER))) {
Kind overwriteErrorKind = "error".equalsIgnoreCase(this.ap.getOption(SupportedOptions.OVERWRITE_ERROR_LEVEL))
? Kind.ERROR : Kind.WARNING;
String javadoc = this.ap.getJavadocProvider().getJavadoc(method);
if (javadoc == null) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", method);
return;
}
if (!javadoc.toLowerCase().contains("@author")) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", method);
}
if (!javadoc.toLowerCase().contains("@reason")) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", method);
}
}
}
}
@@ -0,0 +1,94 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
/**
* A module for {@link AnnotatedMixin} which handles shadowed fields and methods
*/
class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler {
AnnotatedMixinShadowHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} field
*/
public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean remap) {
ShadowElementName name = new ShadowElementName(field, shadow);
this.validateTargetField(field, shadow, name, "@Shadow");
if (!remap || !this.validateSingleTarget("@Shadow", field)) {
return;
}
ObfuscationData<String> obfFieldData = this.obf.getObfField(this.mixin.getPrimaryTargetRef() + "/" + name);
if (obfFieldData.isEmpty()) {
this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow);
return;
}
for (ObfuscationType type : obfFieldData) {
String fieldName = obfFieldData.get(type);
this.addFieldMapping(type, name.setObfuscatedName(fieldName));
}
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} method
*/
public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean remap) {
ShadowElementName name = new ShadowElementName(method, shadow);
this.validateTargetMethod(method, shadow, name, "@Shadow");
if (!remap || !this.validateSingleTarget("@Shadow", method)) {
return;
}
String mcpSignature = MirrorUtils.generateSignature(method);
ObfuscationData<SrgMethod> obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + name, mcpSignature));
if (obfData.isEmpty()) {
this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow);
return;
}
for (ObfuscationType type : obfData) {
SrgMethod obfMethod = obfData.get(type);
this.addMethodMapping(type, name.setObfuscatedName(obfMethod.getName()), mcpSignature, obfMethod.getDesc());
}
}
}
@@ -27,20 +27,16 @@ package org.spongepowered.tools.obfuscation;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
@@ -50,7 +46,6 @@ import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
@@ -60,26 +55,32 @@ import javax.tools.StandardLocation;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass;
import org.spongepowered.tools.obfuscation.interfaces.IJavadocProvider;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass;
import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager;
import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider;
import org.spongepowered.tools.obfuscation.struct.Message;
import org.spongepowered.tools.obfuscation.validation.ParentValidator;
import org.spongepowered.tools.obfuscation.validation.TargetValidator;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import net.minecraftforge.srg2source.rangeapplier.SrgContainer;
/**
* Mixin info manager, stores all of the mixin info during processing and also
* manages access to the srgs
*/
class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITypeHandleProvider, IJavadocProvider {
private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid";
/**
* Detected compiler argument, specifies the behaviour of some operations
* for compatibility purposes.
*/
static enum CompilerEnvironment {
/**
* Default environment
@@ -115,24 +116,9 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
private final List<AnnotatedMixin> mixinsForPass = new ArrayList<AnnotatedMixin>();
/**
* Name of the resource to write generated srgs to
* Obfuscation manager
*/
private final String outSrgFileName;
/**
* Name of the resource to write remapped refs to
*/
private final String outRefMapFileName;
/**
* File containing the reobfd srgs
*/
private final String reobfSrgFileName;
/**
* Reference mapper for reference mapping
*/
private final ReferenceMapper refMapper = new ReferenceMapper();
private final ObfuscationManager obf;
/**
* Rule validators
@@ -145,15 +131,9 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
private final Map<String, Integer> tokenCache = new HashMap<String, Integer>();
/**
* SRG container for mcp->srg mappings
* Serialisable mixin target map
*/
private SrgContainer srgs;
/**
* True once we've tried to initialise the srgs, initially false so that we
* can do srg init lazily
*/
private boolean initDone;
private final TargetMap targets;
/**
* Properties file used to specify options when AP options cannot be
@@ -167,19 +147,31 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
private AnnotatedMixins(ProcessingEnvironment processingEnv) {
this.env = this.detectEnvironment(processingEnv);
this.processingEnv = processingEnv;
this.targets = this.initTargetMap();
this.obf = new ObfuscationManager(this);
this.printMessage(Kind.NOTE, "SpongePowered Mixin Annotation Processor v" + MixinBootstrap.VERSION);
this.reobfSrgFileName = this.getOption("reobfSrgFile");
this.outSrgFileName = this.getOption("outSrgFile");
this.outRefMapFileName = this.getOption("outRefMapFile");
this.validators = ImmutableList.<IMixinValidator>of(
new ParentValidator(processingEnv, this, this),
new TargetValidator(processingEnv, this, this)
new ParentValidator(this),
new TargetValidator(this)
);
this.initTokenCache(this.getOption("tokens"));
this.initTokenCache(this.getOption(SupportedOptions.TOKENS));
}
protected TargetMap initTargetMap() {
TargetMap targets = TargetMap.create(System.getProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY));
System.setProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY, targets.getSessionId());
String targetsFileName = this.getOption(SupportedOptions.DEPENDENCY_TARGETS_FILE);
if (targetsFileName != null) {
try {
targets.readImports(new File(targetsFileName));
} catch (IOException ex) {
this.printMessage(Kind.WARNING, "Could not read from specified imports file: " + targetsFileName);
}
}
return targets;
}
private void initTokenCache(String tokens) {
@@ -195,6 +187,31 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
}
}
}
@Override
public ITypeHandleProvider getTypeProvider() {
return this;
}
@Override
public ITokenProvider getTokenProvider() {
return this;
}
@Override
public IObfuscationManager getObfuscationManager() {
return this.obf;
}
@Override
public IJavadocProvider getJavadocProvider() {
return this;
}
@Override
public ProcessingEnvironment getProcessingEnvironment() {
return this.processingEnv;
}
@Override
public Integer getToken(String token) {
@@ -252,123 +269,20 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
return CompilerEnvironment.JAVAC;
}
/**
* Lazy initialisation for srgs, so that we only initialise the srgs if
* they're actually required.
*/
private boolean initSrgs() {
if (!this.initDone) {
this.initDone = true;
if (this.reobfSrgFileName == null) {
this.printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, obfuscation processing will not occur");
return false;
}
try {
File reobfSrgFile = new File(this.reobfSrgFileName);
this.printMessage(Kind.NOTE, "Loading SRGs from " + reobfSrgFile.getAbsolutePath());
this.srgs = new SrgContainer().readSrg(reobfSrgFile);
} catch (Exception ex) {
ex.printStackTrace();
this.printMessage(Kind.ERROR, "The specified SRG file could not be read, processing cannot continue");
this.srgs = null;
}
}
return this.srgs != null;
}
/**
* Write out generated srgs
*/
public void writeSrgs() {
if (this.outSrgFileName == null) {
return;
}
Set<String> fieldMappings = new LinkedHashSet<String>();
Set<String> methodMappings = new LinkedHashSet<String>();
for (AnnotatedMixin mixin : this.mixins.values()) {
fieldMappings.addAll(mixin.getFieldMappings());
methodMappings.addAll(mixin.getMethodMappings());
}
PrintWriter writer = null;
try {
writer = this.openFileWriter(this.outSrgFileName, "output SRGs");
for (String fieldMapping : fieldMappings) {
writer.println(fieldMapping);
}
for (String methodMapping : methodMappings) {
writer.println(methodMapping);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
}
/**
* Open a writer for an output file
*/
private PrintWriter openFileWriter(String fileName, String description) throws IOException {
if (fileName.matches("^.*[\\\\/:].*$")) {
File outSrgFile = new File(fileName);
outSrgFile.getParentFile().mkdirs();
this.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath());
return new PrintWriter(outSrgFile);
}
Filer filer = this.processingEnv.getFiler();
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
this.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath());
return new PrintWriter(outSrg.openWriter());
this.obf.writeSrgs(this.mixins);
}
/**
* Write out stored mappings
*/
public void writeRefs() {
if (this.outRefMapFileName == null) {
return;
}
PrintWriter writer = null;
try {
writer = this.openFileWriter(this.outRefMapFileName, "refmap");
this.refMapper.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
this.obf.writeRefs();
}
/**
* Get the reference mapper
*/
public ReferenceMapper getReferenceMapper() {
return this.refMapper;
}
/**
* Clear all registered mixins
*/
@@ -384,6 +298,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
if (!this.mixins.containsKey(name)) {
AnnotatedMixin mixin = new AnnotatedMixin(this, mixinType);
this.targets.registerTargets(mixin);
mixin.runValidators(ValidationPass.EARLY, this.validators);
this.mixins.put(name, mixin);
this.mixinsForPass.add(mixin);
@@ -411,12 +326,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
public Collection<TypeMirror> getMixinsTargeting(TypeElement targetType) {
List<TypeMirror> minions = new ArrayList<TypeMirror>();
for (AnnotatedMixin mixin : this.mixins.values()) {
for (TypeHandle mixinTarget : mixin.getTargets()) {
if (targetType.equals(mixinTarget.getElement())) {
minions.add(mixin.getMixin().asType());
break;
}
for (TypeReference mixin : this.targets.getMixinsTargeting(targetType)) {
TypeHandle handle = mixin.getHandle(this.processingEnv);
if (handle != null) {
minions.add(handle.getType());
}
}
@@ -443,7 +356,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
* Register a {@link org.spongepowered.asm.mixin.Shadow} field
*
* @param mixinType Mixin class
* @param method Shadow field
* @param field Shadow field
* @param shadow {@link org.spongepowered.asm.mixin.Shadow} annotation
*/
public void registerShadow(TypeElement mixinType, VariableElement field, AnnotationMirror shadow) {
@@ -484,12 +397,14 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
public void registerInjector(TypeElement mixinType, ExecutableElement method, AnnotationMirror inject) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
this.printMessage(Kind.ERROR, "Found @Inject annotation on a non-mixin method", method);
String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + "";
this.printMessage(Kind.ERROR, "Found " + type + " annotation on a non-mixin method", method);
return;
}
boolean remap = this.shouldRemap(mixinClass, inject);
mixinClass.registerInjector(method, inject, remap);
Message errorMessage = mixinClass.registerInjector(method, inject, remap);
int remappedAts = 0;
if (remap) {
Object ats = MirrorUtils.getAnnotationValue(inject, "at");
@@ -501,21 +416,28 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
at = ((AnnotationValue)at).getValue();
}
if (at instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at);
remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at);
} else {
this.printMessage(Kind.WARNING, "No annotation mirror on " + at.getClass().getName());
}
}
} else if (ats instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats);
remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats);
} else if (ats instanceof AnnotationValue) {
// Fix for JDT
Object mirror = ((AnnotationValue)ats).getValue();
if (mirror instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror);
remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror);
}
}
}
// The annotation was *not* marked as remap=false and failed so we
// checked for remappable @At annotations, if that failed as well then
// we raise the original error.
if (remappedAts == 0 && errorMessage != null) {
errorMessage.sendTo(this);
}
}
/**
@@ -530,6 +452,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
* Called from each AP when a pass is completed
*/
public void onPassCompleted() {
if (!"true".equalsIgnoreCase(this.getOption(SupportedOptions.DISABLE_TARGET_EXPORT))) {
this.targets.write(true);
}
for (AnnotatedMixin mixin : this.mixinsForPass) {
mixin.runValidators(ValidationPass.LATE, this.validators);
}
@@ -580,17 +506,11 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value);
}
/**
* Print a message to the AP messager
*/
public void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) {
this.processingEnv.getMessager().printMessage(kind, msg, mixin.getMixin(), mixin.getAnnotation());
}
/**
* Get a TypeHandle representing another type in the current processing
* environment
*/
@Override
public TypeHandle getTypeHandle(String name) {
name = name.replace('/', '.');
@@ -615,51 +535,15 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
return null;
}
/**
* Get an obfuscation mapping for a method
*/
public MethodData getObfMethod(MemberInfo method) {
MethodData obfd = this.getObfMethod(method.asMethodData());
if (obfd != null || !method.isFullyQualified()) {
return obfd;
}
// Get a type handle for the declared method owner
TypeHandle type = this.getTypeHandle(method.owner);
if (type.isImaginary()) {
return null;
}
// See if we can get the superclass from the reference
TypeMirror superClass = type.getElement().getSuperclass();
if (superClass.getKind() != TypeKind.DECLARED) {
return null;
}
// Well we found it, let's inflect the class name and recurse the search
String superClassName = ((TypeElement)((DeclaredType)superClass).asElement()).getQualifiedName().toString();
return this.getObfMethod(new MemberInfo(method.name, superClassName.replace('.', '/'), method.desc, method.matchAll));
}
/**
* Get an obfuscation mapping for a method
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IJavadocProvider
* #getJavadoc(javax.lang.model.element.Element)
*/
public MethodData getObfMethod(MethodData method) {
if (this.initSrgs()) {
return this.srgs.methodMap.get(method);
}
return null;
}
/**
* Get an obfuscation mapping for a field
*/
public String getObfField(String field) {
if (this.initSrgs()) {
return this.srgs.fieldMap.get(field);
}
return null;
@Override
public String getJavadoc(Element element) {
Elements elements = this.processingEnv.getElementUtils();
return elements.getDocComment(element);
}
/**
@@ -26,7 +26,6 @@ package org.spongepowered.tools.obfuscation;
import javax.lang.model.element.VariableElement;
/**
* Retrieved from a {@link TypeHandle} when searching for fields
*/
@@ -29,9 +29,6 @@ import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
@@ -39,8 +36,11 @@ import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.tools.MirrorUtils;
@@ -48,14 +48,12 @@ import org.spongepowered.tools.MirrorUtils;
* Annotation processor which finds {@link Inject} and {@link At} annotations in
* mixin classes and generates SRG mappings
*/
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({
"org.spongepowered.asm.mixin.injection.Inject",
"org.spongepowered.asm.mixin.injection.ModifyArg",
"org.spongepowered.asm.mixin.injection.Redirect",
"org.spongepowered.asm.mixin.injection.At"
})
@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile" })
public class InjectionObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -66,13 +64,15 @@ public class InjectionObfuscationProcessor extends MixinProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
return true;
}
this.processMixins(roundEnv);
this.processInjectors(roundEnv, Inject.class);
this.processInjectors(roundEnv, ModifyArg.class);
this.processInjectors(roundEnv, Redirect.class);
this.processInjectors(roundEnv, ModifyVariable.class);
this.processInjectors(roundEnv, ModifyConstant.class);
this.postProcess(roundEnv);
return true;
@@ -26,7 +26,6 @@ package org.spongepowered.tools.obfuscation;
import javax.lang.model.element.ExecutableElement;
/**
* Retrieved from a {@link TypeHandle} when searching for methods
*/
@@ -24,9 +24,12 @@
*/
package org.spongepowered.tools.obfuscation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
@@ -34,8 +37,11 @@ import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Mixin;
/**
* Base class for mixin annotation processor modules
*/
public abstract class MixinProcessor extends AbstractProcessor {
/**
* Mixin info manager
*/
@@ -58,10 +64,10 @@ public abstract class MixinProcessor extends AbstractProcessor {
this.mixins.onPassStarted();
for (Element elem : roundEnv.getElementsAnnotatedWith(Mixin.class)) {
if (elem.getKind() == ElementKind.CLASS) {
if (elem.getKind() == ElementKind.CLASS || elem.getKind() == ElementKind.INTERFACE) {
this.mixins.registerMixin((TypeElement)elem);
} else {
this.mixins.printMessage(Kind.ERROR, "Found an @Mixin annotation on an element which is not a class", elem);
this.mixins.printMessage(Kind.ERROR, "Found an @Mixin annotation on an element which is not a class or interface", elem);
}
}
}
@@ -70,4 +76,20 @@ public abstract class MixinProcessor extends AbstractProcessor {
this.mixins.onPassCompleted();
}
@Override
public SourceVersion getSupportedSourceVersion() {
try {
return SourceVersion.valueOf("RELEASE_8");
} catch (IllegalArgumentException ex) {
// Java 8 not supported
}
return super.getSupportedSourceVersion();
}
@Override
public Set<String> getSupportedOptions() {
return SupportedOptions.all;
}
}
@@ -34,6 +34,9 @@ import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator;
import org.spongepowered.tools.obfuscation.interfaces.IOptionProvider;
/**
* Base class for mixin validators
@@ -64,15 +67,13 @@ public abstract class MixinValidator implements IMixinValidator {
/**
* ctor
*
* @param processingEnv Processing environment
* @param messager Messager to use
* @param options Option provider
* @param ap Processing environment
* @param pass Validation pass being performed
*/
public MixinValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options, ValidationPass pass) {
this.processingEnv = processingEnv;
this.messager = messager;
this.options = options;
public MixinValidator(IMixinAnnotationProcessor ap, ValidationPass pass) {
this.processingEnv = ap.getProcessingEnvironment();
this.messager = ap;
this.options = ap;
this.pass = pass;
}
@@ -0,0 +1,93 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.spongepowered.asm.obfuscation.SrgMethod;
/**
* Return value struct for various obfuscation queries performed by the mixin
* annotation processor.
*
* <p>When obfuscation queries are performed by the AP, the returned data are
* encapsulated in an <tt>ObfuscationData</tt> object which contains a mapping
* of the different obfuscation types to the respective remapped value of the
* original entry for that environment.</p>
*
* <p>The returned data are iterable over the keys, consumers should call
* {@link #get} to retrieve the remapped entries for each key.</p>
*
* @param <T> Contained type of the data, usually {@link String} for field
* and type obfuscations, and {@link SrgMethod} for methods.
*/
public class ObfuscationData<T> implements Iterable<ObfuscationType> {
private final Map<ObfuscationType, T> data = new HashMap<ObfuscationType, T>();
private final T defaultValue;
public ObfuscationData() {
this(null);
}
public ObfuscationData(T defaultValue) {
this.defaultValue = defaultValue;
}
public void add(ObfuscationType type, T value) {
this.data.put(type, value);
}
public boolean isEmpty() {
return this.data.isEmpty();
}
public T get(ObfuscationType type) {
T value = this.data.get(type);
return value != null ? value : this.defaultValue;
}
@Override
public Iterator<ObfuscationType> iterator() {
return this.data.keySet().iterator();
}
@Override
public String toString() {
return String.format("ObfuscationData[%sDEFAULT=%s]", this.listValues(), this.defaultValue);
}
private String listValues() {
StringBuilder sb = new StringBuilder();
for (ObfuscationType type : this.data.keySet()) {
sb.append(type.name()).append('=').append(this.data.get(type)).append(',');
}
return sb.toString();
}
}
@@ -0,0 +1,389 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.obfuscation.SrgField;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager;
/**
* Obfuscation Manager for mixin Annotation Processor
*/
public class ObfuscationManager implements IObfuscationManager {
/**
* Annotation processor
*/
private final IMixinAnnotationProcessor ap;
/**
* Name of the resource to write remapped refs to
*/
private final String outRefMapFileName;
/**
* Target obfuscation environments
*/
private final List<TargetObfuscationEnvironment> targetEnvironments = new ArrayList<TargetObfuscationEnvironment>();
/**
* Reference mapper for reference mapping
*/
private final ReferenceMapper refMapper = new ReferenceMapper();
public ObfuscationManager(IMixinAnnotationProcessor ap) {
this.ap = ap;
this.outRefMapFileName = this.ap.getOption(SupportedOptions.OUT_REFMAP_FILE);
for (ObfuscationType obfType : ObfuscationType.values()) {
if (obfType.isSupported(this.ap)) {
this.targetEnvironments.add(new TargetObfuscationEnvironment(ap, obfType, this.refMapper));
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getReferenceMapper()
*/
@Override
public ReferenceMapper getReferenceMapper() {
return this.refMapper;
}
/**
* Write out generated srgs
*/
public void writeSrgs(Map<String, AnnotatedMixin> mixins) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
targetEnv.writeSrgs(this.ap.getProcessingEnvironment().getFiler(), mixins);
}
}
/**
* Write out stored mappings
*/
public void writeRefs() {
if (this.outRefMapFileName == null) {
return;
}
PrintWriter writer = null;
try {
writer = this.newWriter(this.outRefMapFileName, "refmap");
this.refMapper.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
}
/**
* Open a writer for an output file
*/
private PrintWriter newWriter(String fileName, String description) throws IOException {
if (fileName.matches("^.*[\\\\/:].*$")) {
File outSrgFile = new File(fileName);
outSrgFile.getParentFile().mkdirs();
this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath());
return new PrintWriter(outSrgFile);
}
FileObject outSrg = this.ap.getProcessingEnvironment().getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath());
return new PrintWriter(outSrg.openWriter());
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfEntryRecursive(
* org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
@SuppressWarnings("unchecked")
public <T> ObfuscationData<T> getObfEntryRecursive(final MemberInfo targetMember) {
MemberInfo currentTarget = targetMember;
ObfuscationData<String> obfTargetNames = this.getObfClass(currentTarget.owner);
ObfuscationData<T> obfData = this.getObfEntry(currentTarget);
try {
while (obfData.isEmpty()) {
TypeHandle targetType = this.ap.getTypeProvider().getTypeHandle(currentTarget.owner);
if (targetType == null) {
return obfData;
}
TypeHandle superClass = targetType.getSuperclass();
if (superClass == null) {
return obfData;
}
currentTarget = currentTarget.move(superClass.getName());
obfData = this.getObfEntry(currentTarget);
if (!obfData.isEmpty()) {
for (ObfuscationType type : obfData) {
String obfClass = obfTargetNames.get(type);
T obfMember = obfData.get(type);
if (currentTarget.isField()) {
obfData.add(type, (T)MemberInfo.fromSrgField(obfMember.toString(), "").move(obfClass).toSrg());
} else {
obfData.add(type, (T)MemberInfo.fromSrgMethod((SrgMethod)obfMember).move(obfClass).asSrgMethod());
}
}
}
}
} catch (Exception ex) {
return this.getObfEntry(targetMember);
}
return obfData;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfEntry(
* org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
@SuppressWarnings("unchecked")
public <T> ObfuscationData<T> getObfEntry(MemberInfo targetMember) {
if (targetMember.isField()) {
return (ObfuscationData<T>)this.getObfField(targetMember.toSrg());
}
return (ObfuscationData<T>)this.getObfMethod(targetMember.asSrgMethod());
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfMethodRecursive(
* org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
public ObfuscationData<SrgMethod> getObfMethodRecursive(MemberInfo targetMember) {
return this.<SrgMethod>getObfEntryRecursive(targetMember);
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfMethod(
* org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
public ObfuscationData<SrgMethod> getObfMethod(MemberInfo method) {
ObfuscationData<SrgMethod> data = new ObfuscationData<SrgMethod>();
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
SrgMethod obfMethod = targetEnv.getObfMethod(method);
if (obfMethod != null) {
data.add(targetEnv.getType(), obfMethod);
}
}
if (!data.isEmpty() || !Constants.CTOR.equals(method.name)) {
return data;
}
return this.remapDescriptor(data, method);
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager
* #getObfMethod(org.spongepowered.asm.obfuscation.SrgMethod)
*/
@Override
public ObfuscationData<SrgMethod> getObfMethod(SrgMethod method) {
ObfuscationData<SrgMethod> data = new ObfuscationData<SrgMethod>();
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
SrgMethod obfMethod = targetEnv.getObfMethod(method);
if (obfMethod != null) {
data.add(targetEnv.getType(), obfMethod);
}
}
if (!data.isEmpty() || !Constants.CTOR.equals(method.getSimpleName())) {
return data;
}
return this.remapDescriptor(data, new MemberInfo(method));
}
/**
* Remap a method owner and descriptor only, used for remapping ctors
*
* @param data Output method data collection
* @param method Method to remap
* @return data
*/
public ObfuscationData<SrgMethod> remapDescriptor(ObfuscationData<SrgMethod> data, MemberInfo method) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
MemberInfo obfMethod = targetEnv.remapDescriptor(method);
if (obfMethod != null) {
data.add(targetEnv.getType(), obfMethod.asSrgMethod());
}
}
return data;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfFieldRecursive(
* org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
public ObfuscationData<String> getObfFieldRecursive(MemberInfo targetMember) {
return this.<String>getObfEntryRecursive(targetMember);
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfField(java.lang.String)
*/
@Override
public ObfuscationData<String> getObfField(String field) {
ObfuscationData<String> data = new ObfuscationData<String>();
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
SrgField obfField = targetEnv.getObfField(field);
if (obfField != null) {
data.add(targetEnv.getType(), obfField.toString());
}
}
return data;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfClass(org.spongepowered.tools.obfuscation.TypeHandle)
*/
@Override
public ObfuscationData<String> getObfClass(TypeHandle type) {
return this.getObfClass(type.getName());
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.IObfuscationManager
* #getObfClass(java.lang.String)
*/
@Override
public ObfuscationData<String> getObfClass(String className) {
ObfuscationData<String> data = new ObfuscationData<String>(className);
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
String obfClass = targetEnv.getObfClass(className);
if (obfClass != null) {
data.add(targetEnv.getType(), obfClass);
}
}
return data;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager
* #addMethodMapping(java.lang.String, java.lang.String,
* org.spongepowered.tools.obfuscation.ObfuscationData)
*/
@Override
public void addMethodMapping(String className, String reference, ObfuscationData<SrgMethod> obfMethodData) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
SrgMethod obfMethod = obfMethodData.get(targetEnv.getType());
if (obfMethod != null) {
MemberInfo remappedReference = new MemberInfo(obfMethod);
targetEnv.addMapping(className, reference, remappedReference.toString());
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager
* #addMethodMapping(java.lang.String, java.lang.String,
* org.spongepowered.asm.mixin.injection.struct.MemberInfo,
* org.spongepowered.tools.obfuscation.ObfuscationData)
*/
@Override
public void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData<SrgMethod> obfMethodData) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
SrgMethod obfMethod = obfMethodData.get(targetEnv.getType());
if (obfMethod != null) {
MemberInfo remappedReference = context.remapUsing(obfMethod, true);
targetEnv.addMapping(className, reference, remappedReference.toString());
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager
* #addFieldMapping(java.lang.String, java.lang.String,
* org.spongepowered.asm.mixin.injection.struct.MemberInfo,
* org.spongepowered.tools.obfuscation.ObfuscationData)
*/
@Override
public void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData<String> obfFieldData) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
String obfField = obfFieldData.get(targetEnv.getType());
if (obfField != null) {
MemberInfo remappedReference = MemberInfo.fromSrgField(obfField, targetEnv.remapDescriptor(context.desc));
targetEnv.addMapping(className, reference, remappedReference.toString());
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager
* #addClassMapping(java.lang.String, java.lang.String,
* org.spongepowered.tools.obfuscation.ObfuscationData)
*/
@Override
public void addClassMapping(String className, String reference, ObfuscationData<String> obfClassData) {
for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
String remapped = obfClassData.get(targetEnv.getType());
if (remapped != null) {
targetEnv.addMapping(className, reference, remapped);
}
}
}
}
@@ -0,0 +1,132 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.List;
import org.spongepowered.tools.obfuscation.interfaces.IOptionProvider;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
/**
* Obfuscation types supported by the annotation processor
*/
enum ObfuscationType {
/**
* "SEARGE" mappings, these are unique mappings used by MCP and derived
* projects
*/
SRG("searge", SupportedOptions.REOBF_SRG_FILE, SupportedOptions.REOBF_EXTRA_SRG_FILES, SupportedOptions.OUT_SRG_SRG_FILE),
/**
* "NOTCH" mappings, internal to minecraft only
*/
NOTCH("notch", SupportedOptions.REOBF_NOTCH_FILE, SupportedOptions.REOBF_EXTRA_NOTCH_FILES, SupportedOptions.OUT_NOTCH_SRG_FILE);
/**
* Refmap key for this mapping type
*/
private final String key;
/**
* The name of the Annotation Processor argument which contains the file
* name to read the SRGs for this obfuscation type from
*/
private final String srgFileArgName;
/**
* The name of the Annotation Processor argument which contains the file
* name to read the extra SRGs for this obfuscation type from
*/
private final String extraSrgFilesArgName;
/**
* The name of the Annotation Processor argument which contains the file
* name to write generated SRG mappings to
*/
private final String outSrgFileArgName;
private ObfuscationType(String displayName, String srgFileArgName, String extraSrgFilesArgName, String outSrgFileArgName) {
this.key = displayName;
this.srgFileArgName = srgFileArgName;
this.extraSrgFilesArgName = extraSrgFilesArgName;
this.outSrgFileArgName = outSrgFileArgName;
}
@Override
public String toString() {
return this.key;
}
public String getKey() {
return this.key;
}
public String getSrgFileOption() {
return this.srgFileArgName;
}
public String getExtraSrgFilesOption() {
return this.extraSrgFilesArgName;
}
public String getOutputSrgFileOption() {
return this.outSrgFileArgName;
}
public boolean isDefault(IOptionProvider options) {
String defaultEnv = options.getOption(SupportedOptions.DEFAULT_OBFUSCATION_ENV);
return (defaultEnv == null && this == ObfuscationType.SRG) || (defaultEnv != null && this.key.equals(defaultEnv.toLowerCase()));
}
public boolean isSupported(IOptionProvider options) {
return this.getSrgFileNames(options).size() > 0;
}
public List<String> getSrgFileNames(IOptionProvider options) {
Builder<String> builder = ImmutableList.<String>builder();
String srgFile = options.getOption(this.srgFileArgName);
if (srgFile != null) {
builder.add(srgFile);
}
String extraSrgFiles = options.getOption(this.extraSrgFilesArgName);
if (extraSrgFiles != null) {
for (String extraSrgFile : extraSrgFiles.split(";")) {
builder.add(extraSrgFile.trim());
}
}
return builder.build();
}
public String getOutputSrgFileName(IOptionProvider options) {
return options.getOption(this.outSrgFileArgName);
}
}
@@ -0,0 +1,71 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
/**
* Supported options for the annotation processor. Not an enum mainly so that
* the string tokens can be inlined.
*/
public final class SupportedOptions {
public static final String TOKENS = "tokens";
public static final String REOBF_SRG_FILE = "reobfSrgFile";
public static final String REOBF_EXTRA_SRG_FILES = "reobfSrgFiles";
public static final String REOBF_NOTCH_FILE = "reobfNotchSrgFile";
public static final String REOBF_EXTRA_NOTCH_FILES = "reobfNotchSrgFiles";
public static final String OUT_SRG_SRG_FILE = "outSrgFile";
public static final String OUT_NOTCH_SRG_FILE = "outNotchSrgFile";
public static final String OUT_REFMAP_FILE = "outRefMapFile";
public static final String DISABLE_TARGET_VALIDATOR = "disableTargetValidator";
public static final String DISABLE_TARGET_EXPORT = "disableTargetExport";
public static final String DISABLE_OVERWRITE_CHECKER = "disableOverwriteChecker";
public static final String OVERWRITE_ERROR_LEVEL = "overwriteErrorLevel";
public static final String DEFAULT_OBFUSCATION_ENV = "defaultObfuscationEnv";
public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile";
public static final Set<String> all = ImmutableSet.<String>of(
SupportedOptions.TOKENS,
SupportedOptions.REOBF_SRG_FILE,
SupportedOptions.REOBF_EXTRA_SRG_FILES,
SupportedOptions.REOBF_NOTCH_FILE,
SupportedOptions.REOBF_EXTRA_NOTCH_FILES,
SupportedOptions.OUT_SRG_SRG_FILE,
SupportedOptions.OUT_NOTCH_SRG_FILE,
SupportedOptions.OUT_REFMAP_FILE,
SupportedOptions.DISABLE_TARGET_VALIDATOR,
SupportedOptions.DISABLE_TARGET_EXPORT,
SupportedOptions.DISABLE_OVERWRITE_CHECKER,
SupportedOptions.OVERWRITE_ERROR_LEVEL,
SupportedOptions.DEFAULT_OBFUSCATION_ENV,
SupportedOptions.DEPENDENCY_TARGETS_FILE
);
private SupportedOptions() {}
}
@@ -0,0 +1,282 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.TypeElement;
import com.google.common.io.Files;
/**
* Serialisable map of classes to their associated mixins, used so that we can
* pass target information for supermixins from one compiler session to another
*/
public class TargetMap extends HashMap<TypeReference, Set<TypeReference>> {
private static final long serialVersionUID = 1L;
/**
* Session ID, used to identify the temp file
*/
private final String sessionId;
/**
* Create a new TargetMap with a session ID based on the current system time
*/
private TargetMap() {
this(String.valueOf(System.currentTimeMillis()));
}
/**
* Create a TargetMap with the specified session ID
*
* @param sessionId
*/
private TargetMap(String sessionId) {
this.sessionId = sessionId;
}
/**
* Get the session ID
*/
public String getSessionId() {
return this.sessionId;
}
/**
* Register target classes for the specified mixin
*
* @param mixin mixin to add targets for
*/
public void registerTargets(AnnotatedMixin mixin) {
this.registerTargets(mixin.getTargets(), mixin.getHandle());
}
/**
* Register target classes for the supplied mixin
*
* @param targets List of targets
* @param mixin Mixin class
*/
public void registerTargets(List<TypeHandle> targets, TypeHandle mixin) {
for (TypeHandle target : targets) {
this.addMixin(target, mixin);
}
}
/**
* Register the specified mixin against the specified target
*
* @param target Target class
* @param mixin Mixin class
*/
public void addMixin(TypeHandle target, TypeHandle mixin) {
this.addMixin(target.getReference(), mixin.getReference());
}
/**
* Register the specified mixin against the specified target
*
* @param target Target class
* @param mixin Mixin class
*/
public void addMixin(String target, String mixin) {
this.addMixin(new TypeReference(target), new TypeReference(mixin));
}
/**
* Register the specified mixin against the specified target
*
* @param target Target class
* @param mixin Mixin class
*/
public void addMixin(TypeReference target, TypeReference mixin) {
Set<TypeReference> mixins = this.getMixinsFor(target);
mixins.add(mixin);
}
/**
* Get mixin classes which target the specified class
*
* @param target Target class
* @return Collection of mixins registered as targetting the specified class
*/
public Collection<TypeReference> getMixinsTargeting(TypeElement target) {
return this.getMixinsTargeting(new TypeHandle(target));
}
/**
* Get mixin classes which target the specified class
*
* @param target Target class
* @return Collection of mixins registered as targetting the specified class
*/
public Collection<TypeReference> getMixinsTargeting(TypeHandle target) {
return this.getMixinsTargeting(target.getReference());
}
/**
* Get mixin classes which target the specified class
*
* @param target Target class
* @return Collection of mixins registered as targetting the specified class
*/
public Collection<TypeReference> getMixinsTargeting(TypeReference target) {
return Collections.unmodifiableCollection(this.getMixinsFor(target));
}
/**
* Get mixin set for specified class
*
* @param target Target class
* @return Set of mixins registered as targetting the specified class
*/
private Set<TypeReference> getMixinsFor(TypeReference target) {
Set<TypeReference> mixins = this.get(target);
if (mixins == null) {
mixins = new HashSet<TypeReference>();
this.put(target, mixins);
}
return mixins;
}
/**
* Read upstream library mixins from a file
*
* @param file File to read from
* @throws IOException if an error occurs whilst reading the file
*/
public void readImports(File file) throws IOException {
if (!file.isFile()) {
return;
}
for (String line : Files.readLines(file, Charset.defaultCharset())) {
String[] parts = line.split("\t");
if (parts.length == 2) {
this.addMixin(parts[1], parts[0]);
}
}
}
/**
* Write this target map to temporary session file
*
* @param temp Set "delete on exit" for the file
*/
public void write(boolean temp) {
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try {
File sessionFile = TargetMap.getSessionFile(this.sessionId);
if (temp) {
sessionFile.deleteOnExit();
}
fout = new FileOutputStream(sessionFile, true);
oos = new ObjectOutputStream(fout);
oos.writeObject(this);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
/**
* Attemp to deserialise a TargetMap from the specified file
*
* @param sessionFile File to read
* @return deserialised map or null if deserialisation failed
*/
private static TargetMap read(File sessionFile) {
ObjectInputStream objectinputstream = null;
FileInputStream streamIn = null;
try {
streamIn = new FileInputStream(sessionFile);
objectinputstream = new ObjectInputStream(streamIn);
TargetMap map = (TargetMap)objectinputstream.readObject();
return map;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectinputstream != null) {
try {
objectinputstream .close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return null;
}
/**
* Create a TargetMap for the specified session id. Generate new map if
* the session id is invalid or the file cannot be read. Session ID can be
* null
*
* @param sessionId session to deserialise, can be null to create new
* session
* @return new TargetMap
*/
public static TargetMap create(String sessionId) {
if (sessionId != null) {
File sessionFile = TargetMap.getSessionFile(sessionId);
if (sessionFile.exists()) {
TargetMap map = TargetMap.read(sessionFile);
if (map != null) {
return map;
}
}
}
return new TargetMap();
}
private static File getSessionFile(String sessionId) {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
return new File(tempDir, String.format("mixin-targetdb-%s.tmp", sessionId));
}
}
@@ -0,0 +1,378 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Filer;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.asm.obfuscation.SrgContainer;
import org.spongepowered.asm.obfuscation.SrgField;
import org.spongepowered.asm.util.ObfuscationUtil;
import org.spongepowered.asm.util.ObfuscationUtil.IClassRemapper;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
/**
* Stores information relevant to a particular target obfuscation environment.
*
* <p>We classify different types of possible obfuscation (eg. "searge", "notch"
* ) as <em>obfuscation environments</em> and store related information such as
* the input SRG mappings, generated refmap, generated SRGs, here.</p>
*/
class TargetObfuscationEnvironment {
/**
* Remapping proxy for remapping descriptors
*/
final class RemapperProxy implements IClassRemapper {
@Override
public String map(String typeName) {
if (TargetObfuscationEnvironment.this.srgs == null) {
return null;
}
return TargetObfuscationEnvironment.this.srgs.getClassMapping(typeName);
}
@Override
public String unmap(String typeName) {
if (TargetObfuscationEnvironment.this.srgs == null) {
return null;
}
return TargetObfuscationEnvironment.this.srgs.getClassMapping(typeName);
}
}
/**
* SRG container for mcp->? mappings
*/
protected SrgContainer srgs;
private final RemapperProxy remapper = new RemapperProxy();
/**
* Type
*/
private final ObfuscationType type;
/**
* Annotation processor
*/
private final IMixinAnnotationProcessor ap;
/**
* Name of the resource to write generated srgs to
*/
private final String outSrgFileName;
/**
* File containing the reobfd srgs
*/
private final List<String> reobfSrgFileNames;
/**
* Reference mapper for reference mapping
*/
private final ReferenceMapper refMapper;
/**
* True once we've tried to initialise the srgs, initially false so that we
* can do srg init lazily
*/
private boolean initDone;
public TargetObfuscationEnvironment(IMixinAnnotationProcessor ap, ObfuscationType type, ReferenceMapper refMapper) {
this.ap = ap;
this.type = type;
this.refMapper = refMapper;
this.reobfSrgFileNames = type.getSrgFileNames(ap);
this.outSrgFileName = type.getOutputSrgFileName(ap);
}
private boolean initSrgs() {
if (!this.initDone) {
this.initDone = true;
if (this.reobfSrgFileNames == null) {
this.ap.printMessage(Kind.ERROR, "The " + this.type.getSrgFileOption()
+ " argument was not supplied, obfuscation processing will not occur");
return false;
}
int successCount = 0;
this.srgs = new SrgContainer();
for (String srgFileName : this.reobfSrgFileNames) {
File reobfSrgFile = new File(srgFileName);
try {
if (reobfSrgFile.isFile()) {
this.ap.printMessage(Kind.NOTE, "Loading " + this.type + " mappings from " + reobfSrgFile.getAbsolutePath());
this.srgs.readSrg(reobfSrgFile);
successCount++;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (successCount < 1) {
this.ap.printMessage(Kind.ERROR, "No valid SRG files for " + this.type + " could be read, processing may not be sucessful.");
this.srgs = null;
}
}
return this.srgs != null;
}
/**
* Get the type
*/
public ObfuscationType getType() {
return this.type;
}
public void addMapping(String className, String reference, String newReference) {
this.refMapper.addMapping(this.type.getKey(), className, reference, newReference);
if (this.type.isDefault(this.ap)) {
this.refMapper.addMapping(null, className, reference, newReference);
}
}
/**
* Get an obfuscation mapping for a method
*/
public SrgMethod getObfMethod(MemberInfo method) {
SrgMethod obfd = this.getObfMethod(method.asSrgMethod());
if (obfd != null || !method.isFullyQualified()) {
return obfd;
}
// Get a type handle for the declared method owner
TypeHandle type = this.ap.getTypeProvider().getTypeHandle(method.owner);
if (type == null || type.isImaginary()) {
return null;
}
// See if we can get the superclass from the reference
TypeMirror superClass = type.getElement().getSuperclass();
if (superClass.getKind() != TypeKind.DECLARED) {
return null;
}
// Well we found it, let's inflect the class name and recurse the search
String superClassName = ((TypeElement)((DeclaredType)superClass).asElement()).getQualifiedName().toString();
return this.getObfMethod(new MemberInfo(method.name, superClassName.replace('.', '/'), method.desc, method.matchAll));
}
/**
* Get an obfuscation mapping for a method
*/
public SrgMethod getObfMethod(SrgMethod method) {
return this.getObfMethod(method, true);
}
/**
* Get an obfuscation mapping for a method
*/
public SrgMethod getObfMethod(SrgMethod method, boolean srgOnly) {
if (this.initSrgs()) {
boolean remapped = true;
SrgMethod originalMethod = method.copy();
SrgMethod methodMapping = this.srgs.getMethodMapping(method);
// If no obf mapping, we can attempt to remap the owner class
if (methodMapping == null) {
if (srgOnly) {
return null;
}
methodMapping = originalMethod;
remapped = false;
}
String remappedOwner = this.getObfClass(methodMapping.getOwner());
if (remappedOwner == null || remappedOwner.equals(method.getOwner()) || remappedOwner.equals(methodMapping.getOwner())) {
return remapped ? methodMapping : null;
}
if (remapped) {
return methodMapping.move(remappedOwner);
}
return new SrgMethod(remappedOwner, methodMapping.getSimpleName(), ObfuscationUtil.mapDescriptor(methodMapping.getDesc(), this.remapper));
}
return null;
}
/**
* Remap only the owner and descriptor of the specified method
*
* @param method method to remap
* @return remapped method or null if no remapping occurred
*/
public MemberInfo remapDescriptor(MemberInfo method) {
boolean transformed = false;
String owner = method.owner;
if (owner != null) {
String newOwner = this.remapper.map(owner);
if (newOwner != null) {
owner = newOwner;
transformed = true;
}
}
String desc = method.desc;
if (desc != null) {
String newDesc = ObfuscationUtil.mapDescriptor(method.desc, this.remapper);
if (!newDesc.equals(method.desc)) {
desc = newDesc;
transformed = true;
}
}
return transformed ? new MemberInfo(method.name, owner, desc, method.matchAll) : null;
}
/**
* Remap a single descriptor in the context of this environment
*
* @param desc descriptor to remap
* @return remapped descriptor, may return the original descriptor if no
* remapping occurred
*/
public String remapDescriptor(String desc) {
return ObfuscationUtil.mapDescriptor(desc, this.remapper);
}
/**
* Get an obfuscation mapping for a field
*/
public SrgField getObfField(String field) {
return this.getObfField(field, true);
}
/**
* Get an obfuscation mapping for a field
*/
public SrgField getObfField(String field, boolean srgOnly) {
if (this.initSrgs()) {
SrgField originalField = new SrgField(field);
SrgField fieldMapping = this.srgs.getFieldMapping(originalField);
// If no obf mapping, we can attempt to remap the owner class
if (fieldMapping == null) {
if (srgOnly) {
return null;
}
fieldMapping = originalField;
}
String remappedOwner = this.getObfClass(fieldMapping.getOwner());
if (remappedOwner == null || remappedOwner.equals(originalField.getOwner()) || remappedOwner.equals(fieldMapping.getOwner())) {
return fieldMapping != originalField ? fieldMapping : null;
}
return fieldMapping.move(remappedOwner);
}
return null;
}
/**
* Get an obfuscation mapping for a class
*/
public String getObfClass(String className) {
if (this.initSrgs()) {
return this.srgs.getClassMapping(className);
}
return null;
}
/**
* Write out generated srgs
*/
public void writeSrgs(Filer filer, Map<String, AnnotatedMixin> mixins) {
if (this.outSrgFileName == null) {
return;
}
Set<String> fieldMappings = new LinkedHashSet<String>();
Set<String> methodMappings = new LinkedHashSet<String>();
for (AnnotatedMixin mixin : mixins.values()) {
fieldMappings.addAll(mixin.getFieldMappings(this.type));
methodMappings.addAll(mixin.getMethodMappings(this.type));
}
PrintWriter writer = null;
try {
writer = this.openFileWriter(filer, this.outSrgFileName, this.type + " output SRGs");
for (String fieldMapping : fieldMappings) {
writer.println(fieldMapping);
}
for (String methodMapping : methodMappings) {
writer.println(methodMapping);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
}
/**
* Open a writer for an output file
*/
private PrintWriter openFileWriter(Filer filer, String fileName, String description) throws IOException {
if (fileName.matches("^.*[\\\\/:].*$")) {
File outSrgFile = new File(fileName);
outSrgFile.getParentFile().mkdirs();
this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath());
return new PrintWriter(outSrgFile);
}
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath());
return new PrintWriter(outSrg.openWriter());
}
}
@@ -28,9 +28,6 @@ import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
@@ -47,9 +44,7 @@ import org.spongepowered.tools.MirrorUtils;
* Annotation processor which finds {@link Shadow} and {@link Overwrite}
* annotations in mixin classes and generates SRG mappings
*/
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile", "disableTargetValidator" })
public class TargetObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -60,7 +55,7 @@ public class TargetObfuscationProcessor extends MixinProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
return true;
}
this.processMixins(roundEnv);
@@ -35,12 +35,12 @@ import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.tools.MirrorUtils;
/**
* A wrapper for TypeElement which gives us a soft-failover mechanism when
* dealing with classes that are inaccessible via mirror (such as anonymous
@@ -63,6 +63,11 @@ public class TypeHandle {
* Actual type element, this is null for inaccessible classes
*/
private final TypeElement element;
/**
* Reference to this handle, for serialisation
*/
private TypeReference reference;
/**
* Ctor for imaginary elements, require the enclosing package and the FQ
@@ -140,6 +145,23 @@ public class TypeHandle {
public TypeMirror getType() {
return this.element != null ? this.element.asType() : null;
}
/**
* Returns the enclosed element's superclass if available, or null if this
* class does not have a superclass
*/
public TypeHandle getSuperclass() {
if (this.element == null) {
return null;
}
TypeMirror superClass = this.element.getSuperclass();
if (superClass == null || superClass.getKind() == TypeKind.NONE) {
return null;
}
return new TypeHandle((DeclaredType)superClass);
}
/**
* Get whether the element is probably public
@@ -154,6 +176,13 @@ public class TypeHandle {
public boolean isImaginary() {
return this.element == null;
}
public TypeReference getReference() {
if (this.reference == null) {
this.reference = new TypeReference(this);
}
return this.reference;
}
public String findDescriptor(MemberInfo memberInfo) {
String desc = memberInfo.desc;
@@ -180,7 +209,7 @@ public class TypeHandle {
* @return handle to the discovered field if matched or null if no match
*/
public FieldHandle findField(VariableElement element) {
return this.findField(element.getSimpleName().toString(), element.asType().toString());
return this.findField(element.getSimpleName().toString(), MirrorUtils.getTypeName(element.asType()));
}
/**
@@ -192,7 +221,7 @@ public class TypeHandle {
* @return handle to the discovered field if matched or null if no match
*/
public FieldHandle findField(String name, String type) {
String rawType = type.replaceAll("<[^>]+>", "");
String rawType = MirrorUtils.stripGenerics(type);
for (Element element : this.getEnclosedElements()) {
if (element.getKind() != ElementKind.FIELD) {
@@ -218,7 +247,7 @@ public class TypeHandle {
* @return handle to the discovered method if matched or null if no match
*/
public MethodHandle findMethod(ExecutableElement element) {
return this.findMethod(element.getSimpleName().toString(), TypeHandle.getElementSignature(element));
return this.findMethod(element.getSimpleName().toString(), MirrorUtils.getJavaSignature(element));
}
/**
@@ -230,7 +259,7 @@ public class TypeHandle {
* @return handle to the discovered method if matched or null if no match
*/
public MethodHandle findMethod(String name, String signature) {
String rawSignature = signature.replaceAll("<[^>]+>", "");
String rawSignature = MirrorUtils.stripGenerics(signature);
for (Element element : this.getEnclosedElements()) {
switch (element.getKind()) {
@@ -256,30 +285,12 @@ public class TypeHandle {
private boolean compareElement(Element elem, String name, String type) {
try {
String elementName = elem.getSimpleName().toString();
String elementType = TypeHandle.getElementSignature(elem);
return name.equals(elementName) && (type.length() == 0 || type.equals(elementType));
String elementType = MirrorUtils.getJavaSignature(elem);
String rawElementType = MirrorUtils.stripGenerics(elementType);
return name.equals(elementName) && (type.length() == 0 || type.equals(elementType) || type.equals(rawElementType));
} catch (NullPointerException ex) {
return false;
}
}
static String getElementSignature(Element element) {
if (element instanceof ExecutableElement) {
ExecutableElement method = (ExecutableElement)element;
StringBuilder desc = new StringBuilder().append("(");
boolean extra = false;
for (VariableElement arg : method.getParameters()) {
if (extra) {
desc.append(',');
}
desc.append(arg.asType().toString());
extra = true;
}
desc.append(')').append(method.getReturnType().toString());
return desc.toString();
}
return element.asType().toString();
}
}
@@ -0,0 +1,123 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.io.Serializable;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
/**
* Soft wrapper for a {@link TypeHandle} so that we can serialise it
*/
public class TypeReference implements Serializable, Comparable<TypeReference> {
private static final long serialVersionUID = 1L;
/**
* Class name, used to recreate the handle on the other side
*/
private final String name;
/**
* Transient handle, not serialised, regenerated when required
*/
private transient TypeHandle handle;
/**
* Create a new soft wrapper for the specified type handle
*
* @param handle handle to wrap
*/
public TypeReference(TypeHandle handle) {
this.name = handle.getName();
this.handle = handle;
}
/**
* Create a type reference with no handle
*
* @param name Name of the type
*/
TypeReference(String name) {
this.name = name;
}
/**
* Get the class name (internal format)
*/
public String getName() {
return this.name;
}
/**
* Get the FQ class name (dotted format)
*/
public String getClassName() {
return this.name.replace('/', '.');
}
/**
* Fetch or attempt to generate the type handle
*
* @param processingEnv environment to create handle if it needs to be
* regenerated
* @return type handle
*/
public TypeHandle getHandle(ProcessingEnvironment processingEnv) {
if (this.handle == null) {
TypeElement element = processingEnv.getElementUtils().getTypeElement(this.getClassName());
try {
this.handle = new TypeHandle(element);
} catch (Exception ex) {
// Class probably doesn't exist in scope :/
ex.printStackTrace();
}
}
return this.handle;
}
@Override
public String toString() {
return String.format("TypeReference[%s]", this.name);
}
@Override
public int compareTo(TypeReference other) {
return other == null ? -1 : this.name.compareTo(other.name);
}
@Override
public boolean equals(Object other) {
return other instanceof TypeReference && this.compareTo((TypeReference)other) == 0;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
@@ -0,0 +1,42 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.interfaces;
import javax.lang.model.element.Element;
/**
* Provides javadoc. What else did you expect?
*/
public interface IJavadocProvider {
/**
* Get javadoc on element
*
* @param element Element to fetch javadoc for
* @return javadoc
*/
public abstract String getJavadoc(Element element);
}
@@ -0,0 +1,62 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.interfaces;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import org.spongepowered.asm.util.ITokenProvider;
/**
* Interface for annotation processor core
*/
public interface IMixinAnnotationProcessor extends Messager, IOptionProvider {
/**
* Get the underlying processing environment
*/
public abstract ProcessingEnvironment getProcessingEnvironment();
/**
* Get the obfuscation manager
*/
public abstract IObfuscationManager getObfuscationManager();
/**
* Get the token provider
*/
public abstract ITokenProvider getTokenProvider();
/**
* Get the type handle provider
*/
public abstract ITypeHandleProvider getTypeProvider();
/**
* Get the javadoc provider
*/
public abstract IJavadocProvider getJavadocProvider();
}
@@ -22,13 +22,14 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
package org.spongepowered.tools.obfuscation.interfaces;
import java.util.Collection;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import org.spongepowered.tools.obfuscation.TypeHandle;
/**
* A mixin validator module, basically just a way of making the various sanity
@@ -36,6 +37,9 @@ import javax.lang.model.element.TypeElement;
*/
public interface IMixinValidator {
/**
* Validation pass
*/
public enum ValidationPass {
EARLY,
LATE
@@ -0,0 +1,154 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.interfaces;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.tools.obfuscation.ObfuscationData;
import org.spongepowered.tools.obfuscation.TypeHandle;
/**
* Manages obfuscation things
*/
public interface IObfuscationManager {
/**
* Get the underlying reference mapper
*/
public abstract ReferenceMapper getReferenceMapper();
/**
* Attempts to resolve an obfuscation entry by recursively enumerating
* superclasses of the target member until a match is found. If a match is
* found in a superclass then the reference is remapped to the original
* owner class.
*
* @param targetMember Member to search for
* @return ObfuscationData with remapped owner class corresponding to the
* original owner class
*/
public abstract <T> ObfuscationData<T> getObfEntryRecursive(MemberInfo targetMember);
/**
* Resolves a field or method reference to an ObfuscationData set
*
* @param targetMember member to search for
* @return obfuscation data (by type) for the supplied member
*/
public abstract <T> ObfuscationData<T> getObfEntry(MemberInfo targetMember);
/**
* Attempts to resolve an obfuscated method by recursively enumerating
* superclasses of the target method until a match is found. If a match is
* found in a superclass then the method owner is remapped to the obfuscated
* name of the original owner class.
*
* @param method Method to search for
* @return ObfuscationData with remapped owner class corresponding to the
* original owner class
*/
public abstract ObfuscationData<SrgMethod> getObfMethodRecursive(MemberInfo method);
/**
* Get an obfuscation mapping for a method
*/
public abstract ObfuscationData<SrgMethod> getObfMethod(MemberInfo method);
/**
* Get an obfuscation mapping for a method
*/
public abstract ObfuscationData<SrgMethod> getObfMethod(SrgMethod method);
/**
* Attempts to resolve an obfuscated field by recursively enumerating
* superclasses of the target field until a match is found. If a match is
* found in a superclass then the field owner is remapped to the obfuscated
* name of the original owner class.
*
* @param field Field to search for
* @return ObfuscationData with remapped owner class corresponding to the
* original owner class
*/
public abstract ObfuscationData<String> getObfFieldRecursive(MemberInfo field);
/**
* Get an obfuscation mapping for a field
*/
public abstract ObfuscationData<String> getObfField(String field);
/**
* Get an obfuscation mapping for a class
*/
public abstract ObfuscationData<String> getObfClass(TypeHandle type);
/**
* Get an obfuscation mapping for a class
*/
public abstract ObfuscationData<String> getObfClass(String className);
/**
* Adds a method mapping to the internal refmap
*
* @param className Mixin class name which owns the refmap entry
* @param reference Original reference, as it appears in the annotation
* @param obfMethodData Method data to add for this mapping
*/
public abstract void addMethodMapping(String className, String reference, ObfuscationData<SrgMethod> obfMethodData);
/**
* Adds a method mapping to the internal refmap, generates refmap entries
* using the supplied parsed memberinfo as context
*
* @param className Mixin class name which owns the refmap entry
* @param reference Original reference, as it appears in the annotation
* @param context The context for this mapping entry, remapped using the
* supplied obfuscation data
* @param obfMethodData Method data to add for this mapping
*/
public abstract void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData<SrgMethod> obfMethodData);
/**
* Adds a field mapping to the internal refmap, generates refmap entries
* using the supplied parsed memberinfo as context
*
* @param className Mixin class name which owns the refmap entry
* @param reference Original reference, as it appears in the annotation
* @param context The context for this mapping entry, remapped using the
* supplied obfuscation data
* @param obfFieldData Field data to add for this mapping
*/
public abstract void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData<String> obfFieldData);
/**
* Adds a class mapping to the internal refmap
*
* @param className Mixin class name which owns the refmap entry
* @param reference Original reference, as it appears in the annotation
* @param obfClassData Class obf names
*/
public abstract void addClassMapping(String className, String reference, ObfuscationData<String> obfClassData);
}
@@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
package org.spongepowered.tools.obfuscation.interfaces;
/**
* An object which can provide option values to consumers
@@ -0,0 +1,42 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.interfaces;
import org.spongepowered.tools.obfuscation.TypeHandle;
/**
* Manager object which cann supply {@link TypeHandle} instances
*/
public interface ITypeHandleProvider {
/**
* Generate a type handle for the specified type
*
* @param name Type name (class name)
* @return A new type handle
*/
public abstract TypeHandle getTypeHandle(String name);
}
@@ -0,0 +1,114 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.struct;
import javax.annotation.processing.Messager;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic;
/**
* Wrapper for Annotation Processor messages, used to enable messages to be
* easily queued and manipulated
*/
public class Message {
private Diagnostic.Kind kind;
private CharSequence msg;
private final Element element;
private final AnnotationMirror annotation;
private final AnnotationValue value;
public Message(Diagnostic.Kind kind, CharSequence msg) {
this(kind, msg, null, null, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element) {
this(kind, msg, element, null, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) {
this(kind, msg, element, annotation, null);
}
public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) {
this.kind = kind;
this.msg = msg;
this.element = element;
this.annotation = annotation;
this.value = value;
}
public Message sendTo(Messager messager) {
if (this.value != null) {
messager.printMessage(this.kind, this.msg, this.element, this.annotation, this.value);
} else if (this.annotation != null) {
messager.printMessage(this.kind, this.msg, this.element, this.annotation);
} else if (this.element != null) {
messager.printMessage(this.kind, this.msg, this.element);
} else {
messager.printMessage(this.kind, this.msg);
}
return this;
}
public Diagnostic.Kind getKind() {
return this.kind;
}
public Message setKind(Diagnostic.Kind kind) {
this.kind = kind;
return this;
}
public CharSequence getMsg() {
return this.msg;
}
public Message setMsg(CharSequence msg) {
this.msg = msg;
return this;
}
public Element getElement() {
return this.element;
}
public AnnotationMirror getAnnotation() {
return this.annotation;
}
public AnnotationValue getValue() {
return this.value;
}
}
@@ -26,17 +26,14 @@ package org.spongepowered.tools.obfuscation.validation;
import java.util.Collection;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import org.spongepowered.tools.obfuscation.IOptionProvider;
import org.spongepowered.tools.obfuscation.MixinValidator;
import org.spongepowered.tools.obfuscation.TypeHandle;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
/**
* Validator which checks that the mixin parent is sane
@@ -46,12 +43,10 @@ public class ParentValidator extends MixinValidator {
/**
* ctor
*
* @param processingEnv Processing environment
* @param messager Messager
* @param options Option provider
* @param ap Processing environment
*/
public ParentValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options) {
super(processingEnv, messager, options, ValidationPass.EARLY);
public ParentValidator(IMixinAnnotationProcessor ap) {
super(ap, ValidationPass.EARLY);
}
/* (non-Javadoc)
@@ -26,18 +26,18 @@ package org.spongepowered.tools.obfuscation.validation;
import java.util.Collection;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.spongepowered.tools.obfuscation.IOptionProvider;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.MixinValidator;
import org.spongepowered.tools.obfuscation.SupportedOptions;
import org.spongepowered.tools.obfuscation.TypeHandle;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
/**
* Validator which checks that the mixin targets are sane
@@ -47,12 +47,10 @@ public class TargetValidator extends MixinValidator {
/**
* ctor
*
* @param processingEnv Processing environment
* @param messager Messager
* @param options Option provider
* @param ap Processing environment
*/
public TargetValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options) {
super(processingEnv, messager, options, ValidationPass.LATE);
public TargetValidator(IMixinAnnotationProcessor ap) {
super(ap, ValidationPass.LATE);
}
/* (non-Javadoc)
@@ -62,10 +60,29 @@ public class TargetValidator extends MixinValidator {
*/
@Override
public boolean validate(TypeElement mixin, AnnotationMirror annotation, Collection<TypeHandle> targets) {
if ("true".equalsIgnoreCase(this.options.getOption("disableTargetValidator"))) {
if ("true".equalsIgnoreCase(this.options.getOption(SupportedOptions.DISABLE_TARGET_VALIDATOR))) {
return true;
}
if (mixin.getKind() == ElementKind.INTERFACE) {
this.validateInterfaceMixin(mixin, targets);
} else {
this.validateClassMixin(mixin, targets);
}
return true;
}
private void validateInterfaceMixin(TypeElement mixin, Collection<TypeHandle> targets) {
for (TypeHandle target : targets) {
TypeElement targetType = target.getElement();
if (targetType != null && !(targetType.getKind() == ElementKind.INTERFACE)) {
this.error("Targetted type '" + target + " of " + mixin + " is not an interface", mixin);
}
}
}
private void validateClassMixin(TypeElement mixin, Collection<TypeHandle> targets) {
TypeMirror superClass = mixin.getSuperclass();
for (TypeHandle target : targets) {
@@ -74,12 +91,10 @@ public class TargetValidator extends MixinValidator {
this.error("Superclass " + superClass + " of " + mixin + " was not found in the hierarchy of target class " + targetType, mixin);
}
}
return true;
}
private boolean validateSuperClass(TypeMirror targetType, TypeMirror superClass) {
if (this.isAssignable(targetType, superClass)) {
if (MirrorUtils.isAssignable(this.processingEnv, targetType, superClass)) {
return true;
}
@@ -91,6 +106,10 @@ public class TargetValidator extends MixinValidator {
return false;
}
if (MirrorUtils.isAssignable(this.processingEnv, targetType, superClass)) {
return true;
}
TypeElement targetElement = (TypeElement)((DeclaredType)targetType).asElement();
TypeMirror targetSuper = targetElement.getSuperclass();
if (targetSuper.getKind() == TypeKind.NONE) {
@@ -106,15 +125,11 @@ public class TargetValidator extends MixinValidator {
private boolean checkMixinsFor(TypeMirror targetType, TypeMirror superClass) {
for (TypeMirror mixinType : this.getMixinsTargeting(targetType)) {
if (this.isAssignable(mixinType, superClass)) {
if (MirrorUtils.isAssignable(this.processingEnv, mixinType, superClass)) {
return true;
}
}
return false;
}
protected final boolean isAssignable(TypeMirror targetType, TypeMirror superClass) {
return this.processingEnv.getTypeUtils().isAssignable(targetType, superClass);
}
}
@@ -0,0 +1,98 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.bridge;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.commons.Remapper;
import org.spongepowered.asm.mixin.extensibility.IRemapper;
import org.spongepowered.asm.util.ObfuscationUtil;
import org.spongepowered.asm.util.ObfuscationUtil.IClassRemapper;
/**
* Base impl of remapper
*/
public abstract class RemapperAdapter implements IRemapper, IClassRemapper {
protected final Logger logger = LogManager.getLogger("mixin");
protected final Remapper remapper;
public RemapperAdapter(Remapper remapper) {
this.remapper = remapper;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
@Override
public String mapMethodName(String owner, String name, String desc) {
this.logger.debug("{} is remapping method {}{} for {}", this, name, desc, owner);
String newName = this.remapper.mapMethodName(owner, name, desc);
if (!newName.equals(name)) {
return newName;
}
String obfOwner = this.unmap(owner);
String obfDesc = this.unmapDesc(desc);
this.logger.debug("{} is remapping obfuscated method {}{} for {}", this, name, obfDesc, obfOwner);
return this.remapper.mapMethodName(obfOwner, name, obfDesc);
}
@Override
public String mapFieldName(String owner, String name, String desc) {
this.logger.debug("{} is remapping field {}{} for {}", this, name, desc, owner);
String newName = this.remapper.mapFieldName(owner, name, desc);
if (!newName.equals(name)) {
return newName;
}
String obfOwner = this.unmap(owner);
String obfDesc = this.unmapDesc(desc);
this.logger.debug("{} is remapping obfuscated field {}{} for {}", this, name, obfDesc, obfOwner);
return this.remapper.mapFieldName(obfOwner, name, obfDesc);
}
@Override
public String map(String typeName) {
this.logger.debug("{} is remapping class {}", this, typeName);
return this.remapper.map(typeName);
}
@Override
public String unmap(String typeName) {
return typeName;
}
@Override
public String mapDesc(String desc) {
return this.remapper.mapDesc(desc);
}
@Override
public String unmapDesc(String desc) {
return ObfuscationUtil.unmapDescriptor(desc, this);
}
}
@@ -0,0 +1,80 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.bridge;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.objectweb.asm.commons.Remapper;
import org.spongepowered.asm.mixin.extensibility.IRemapper;
/**
* Remapper adapter which remaps using FML's deobfuscating remapper
*/
public class RemapperAdapterFML extends RemapperAdapter {
private final Method mdUnmap;
private RemapperAdapterFML(Remapper remapper, Method mdUnmap) {
super(remapper);
this.logger.info("Initialised Mixin FML Remapper Adapter with {}", remapper);
this.mdUnmap = mdUnmap;
}
@Override
public String unmap(String typeName) {
try {
return this.mdUnmap.invoke(this.remapper, typeName).toString();
} catch (Exception ex) {
return typeName;
}
}
public static IRemapper create() {
try {
Class<?> clDeobfRemapper = RemapperAdapterFML.getFMLDeobfuscatingRemapper();
Field singletonField = clDeobfRemapper.getDeclaredField("INSTANCE");
Method mdUnmap = clDeobfRemapper.getDeclaredMethod("unmap", String.class);
Remapper remapper = (Remapper)singletonField.get(null);
return new RemapperAdapterFML(remapper, mdUnmap);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* Attempt to get the FML Deobfuscating Remapper, tries the post-1.8
* namespace first and falls back to 1.7.10 if class lookup fails
*/
private static Class<?> getFMLDeobfuscatingRemapper() throws ClassNotFoundException {
try {
return Class.forName("net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper");
} catch (ClassNotFoundException ex) {
return Class.forName("cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper");
}
}
}
@@ -0,0 +1,78 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
import net.minecraft.launchwrapper.Launch;
/**
* Abstractions for working with {@link Launch#blackboard}
*/
public final class Blackboard {
/**
* Blackboard keys
*/
public static final class Keys {
public static final String TWEAKCLASSES = "TweakClasses";
public static final String TWEAKS = "Tweaks";
public static final String INIT = "mixin.initialised";
public static final String AGENTS = "mixin.agents";
public static final String CONFIGS = "mixin.configs";
public static final String TRANSFORMER = "mixin.transformer";
public static final String FML_LOAD_CORE_MOD = "mixin.launch.fml.loadcoremodmethod";
public static final String FML_GET_REPARSEABLE_COREMODS = "mixin.launch.fml.reparseablecoremodsmethod";
public static final String FML_CORE_MOD_MANAGER = "mixin.launch.fml.coremodmanagerclass";
public static final String FML_GET_IGNORED_MODS = "mixin.launch.fml.ignoredmodsmethod";
private Keys() {}
}
private Blackboard() {}
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T)Launch.blackboard.get(key);
}
public static void put(String key, Object value) {
Launch.blackboard.put(key, value);
}
@SuppressWarnings("unchecked")
public static <T> T get(String key, T defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? (T)value : defaultValue;
}
public static String getString(String key, String defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? value.toString() : defaultValue;
}
}
@@ -26,13 +26,15 @@ package org.spongepowered.asm.launch;
import java.util.List;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.platform.MixinPlatformManager;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Bootstaps the mixin subsystem. This class acts as a bridge between the mixin
* subsystem and the tweaker or coremod which is boostrapping it. Without this
@@ -60,13 +62,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.4.5";
/**
* Blackboard key where the subsystem version will be stored to indicate
* successful bootstrap
*/
public static final String INIT_KEY = "mixin.initialised";
public static final String VERSION = "0.5.11";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
@@ -82,7 +78,7 @@ public abstract class MixinBootstrap {
// These are Klass local, with luck this shouldn't be a problem
private static boolean initialised = false;
private static boolean injectStateTweaker = true;
private static boolean initState = true;
// Static initialiser, add classloader exclusions as early as possible
static {
@@ -94,6 +90,8 @@ public abstract class MixinBootstrap {
// Only needed in dev, in production this would be handled by the tweaker
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.LAUNCH_PACKAGE);
}
private static MixinPlatformManager platformManager = new MixinPlatformManager();
private MixinBootstrap() {}
@@ -104,22 +102,29 @@ public abstract class MixinBootstrap {
Launch.classLoader.registerTransformer(MixinBootstrap.TRANSFORMER_PROXY_CLASS);
}
/**
* Get the platform manager
*/
public static MixinPlatformManager getPlatform() {
return MixinBootstrap.platformManager;
}
/**
* Initialise the mixin subsystem
*/
public static void init() {
if (!MixinBootstrap.preInit()) {
if (!MixinBootstrap.start()) {
return;
}
MixinBootstrap.register();
MixinBootstrap.doInit(null);
}
/**
* Phase 1 of mixin initialisation
*/
static boolean preInit() {
Object registeredVersion = Launch.blackboard.get(MixinBootstrap.INIT_KEY);
static boolean start() {
Object registeredVersion = Blackboard.get(Blackboard.Keys.INIT);
if (registeredVersion != null) {
if (!registeredVersion.equals(MixinBootstrap.VERSION)) {
throw new MixinInitialisationError("Mixin subsystem version " + registeredVersion
@@ -129,15 +134,21 @@ public abstract class MixinBootstrap {
return false;
}
Launch.blackboard.put(MixinBootstrap.INIT_KEY, MixinBootstrap.VERSION);
Blackboard.put(Blackboard.Keys.INIT, MixinBootstrap.VERSION);
if (!MixinBootstrap.initialised) {
MixinBootstrap.initialised = true;
String command = System.getProperty("sun.java.command");
if (command != null && command.contains("GradleStart")) {
System.setProperty("mixin.env.disableRefMap", "true");
}
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") > 132) {
MixinBootstrap.logger.error("Initialising mixin subsystem after game pre-init phase! Some mixins may be skipped.");
MixinEnvironment.init(Phase.DEFAULT);
MixinBootstrap.injectStateTweaker = false;
MixinBootstrap.getPlatform().prepare(null);
MixinBootstrap.initState = false;
} else {
MixinEnvironment.init(Phase.PREINIT);
}
@@ -149,26 +160,37 @@ public abstract class MixinBootstrap {
}
/**
* Phase 2 of mixin initialisation, register the state tweaker
* Phase 2 of mixin initialisation, initialise the phases
*/
static void register() {
static void doInit(List<String> args) {
if (!MixinBootstrap.initialised) {
throw new IllegalStateException("MixinBootstrap.register() called before MixinBootstrap.preInit()");
throw new IllegalStateException("MixinBootstrap.doInit() called before MixinBootstrap.preInit()");
}
if (MixinBootstrap.injectStateTweaker) {
MixinBootstrap.getPlatform().getPhaseProviderClasses();
// for (String platformProviderClass : MixinBootstrap.getPlatform().getPhaseProviderClasses()) {
// System.err.printf("Registering %s\n", platformProviderClass);
// MixinEnvironment.registerPhaseProvider(platformProviderClass);
// }
if (MixinBootstrap.initState) {
MixinBootstrap.getPlatform().prepare(args);
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") < 4) {
MixinBootstrap.logger.warn("MixinBootstrap.register() called during a tweak constructor. Expect CoModificationException in 5.. 4..");
MixinBootstrap.logger.warn("MixinBootstrap.doInit() called during a tweak constructor. Expect CoModificationException in 5.. 4..");
}
@SuppressWarnings("unchecked")
List<String> tweakClasses = (List<String>)Launch.blackboard.get("TweakClasses");
List<String> tweakClasses = Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES);
if (tweakClasses != null) {
tweakClasses.add(MixinEnvironment.class.getName() + "$EnvironmentStateTweaker");
}
}
}
static void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
}
private static int findInStackTrace(String className, String methodName) {
Thread currentThread = Thread.currentThread();
@@ -185,4 +207,5 @@ public abstract class MixinBootstrap {
return 0;
}
}
@@ -24,7 +24,9 @@
*/
package org.spongepowered.asm.launch;
/**
* Error raised when mixin subsystem initialisation fails
*/
public class MixinInitialisationError extends Error {
private static final long serialVersionUID = 1L;
@@ -25,23 +25,11 @@
package org.spongepowered.asm.launch;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
/**
* 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
@@ -49,84 +37,20 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
*/
public class MixinTweaker implements ITweaker {
private static final String MFATT_TWEAKER = "TweakClass";
private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main";
/**
* Make with the logging already
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Tweak containers
*/
private final Map<URI, MixinTweakContainer> containers = new LinkedHashMap<URI, MixinTweakContainer>();
/**
* Tracks whether {@link #acceptOptions} was called yet, if true, causes new
* launch agents to be <tt>prepare</tt>d immediately
*/
private boolean prepared = false;
/**
* Hello world
*/
public MixinTweaker() {
MixinBootstrap.preInit();
// Add agents for the tweak container
URI uri = null;
try {
uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
if (uri != null) {
this.addContainer(uri);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
MixinBootstrap.start();
}
public final void addContainer(URI uri) {
if (this.containers.containsKey(uri)) {
return;
}
MixinTweaker.logger.debug("Adding mixin launch agents for container {}", uri);
MixinTweakContainer container = new MixinTweakContainer(uri);
this.containers.put(uri, container);
if (this.prepared) {
container.prepare();
}
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#acceptOptions(java.util.List,
* java.io.File, java.io.File, java.lang.String)
*/
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
MixinBootstrap.register();
this.prepared = true;
for (MixinTweakContainer container : this.containers.values()) {
container.prepare();
}
this.parseArgs(args);
}
/**
* Read and parse command-line arguments
*
* @param args command-line arguments
*/
private void parseArgs(List<String> args) {
boolean captureNext = false;
for (String arg : args) {
if (captureNext) {
MixinTweaker.addConfig(arg);
}
captureNext = "--mixin".equals(arg);
}
MixinBootstrap.doInit(args);
}
/* (non-Javadoc)
@@ -135,42 +59,7 @@ public class MixinTweaker implements ITweaker {
*/
@Override
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
this.scanClasspath();
MixinTweaker.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size());
for (MixinTweakContainer container : this.containers.values()) {
try {
container.injectIntoClassLoader(classLoader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Scan the classpath for mixin containers (containers which declare the
* mixin tweaker in their manifest) and add agents for them
*/
private void scanClasspath() {
for (URL url : Launch.classLoader.getSources()) {
try {
URI uri = url.toURI();
if (this.containers.containsKey(uri)) {
continue;
}
MixinTweaker.logger.debug("Scanning {} for mixin tweaker", uri);
if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) {
continue;
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(MixinTweaker.MFATT_TWEAKER);
if (MixinTweaker.class.getName().equals(tweaker)) {
MixinTweaker.logger.debug("{} contains a mixin tweaker, adding agents", uri);
this.addContainer(uri);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
MixinBootstrap.injectIntoClassLoader(classLoader);
}
/* (non-Javadoc)
@@ -178,14 +67,7 @@ public class MixinTweaker implements ITweaker {
*/
@Override
public String getLaunchTarget() {
for (MixinTweakContainer container : this.containers.values()) {
String mainClass = container.getLaunchTarget();
if (mainClass != null) {
return mainClass;
}
}
return MixinTweaker.DEFAULT_MAIN_CLASS;
return MixinBootstrap.getPlatform().getLaunchTarget();
}
/* (non-Javadoc)
@@ -195,52 +77,5 @@ public class MixinTweaker implements ITweaker {
public String[] getLaunchArguments() {
return new String[]{};
}
/**
* Add a config from a jar manifest source or the command line. Supports
* config declarations in the form <tt>filename.json</tt> or alternatively
* <tt>filename.json&#064;PHASE</tt> where <tt>PHASE</tt> is a
* case-sensitive string token representing an environment phase.
*
* @param config config resource name, does not require a leading /
*/
static void addConfig(String config) {
if (config.endsWith(".json")) {
MixinTweaker.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getDefaultEnvironment().addConfiguration(config);
} else if (config.contains(".json@")) {
int pos = config.indexOf(".json@");
String phaseName = config.substring(pos + 6);
config = config.substring(0, pos + 5);
Phase phase = Phase.forName(phaseName);
if (phase != null) {
MixinTweaker.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getEnvironment(phase).addConfiguration(config);
}
}
}
/**
* Add a token provider class from a jar manifest source. Supports either
* bare class names in the form <tt>blah.package.ClassName</tt> or
* alternatively <tt>blah.package.ClassName&#064;PHASE</tt> where
* <tt>PHASE</tt> is a case-sensitive string token representing an
* environment phase name.
*
* @param provider provider class name, optionally suffixed with &#064;PHASE
*/
static void addTokenProvider(String provider) {
if (provider.contains("@")) {
String[] parts = provider.split("@", 2);
Phase phase = Phase.forName(parts[1]);
if (phase != null) {
MixinTweaker.logger.debug("Registering token provider class: {}", parts[0]);
MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]);
}
return;
}
MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider);
}
}
@@ -22,21 +22,26 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Base interface for launch agents. Launch agents are environment-specific
* launch handlers which are used by the {@link MixinTweaker mixin tweaker} to
* perform launch tasks required by that environment without having to fill the
* tweaker itself with a bunch of environment-specific cruft.
* Base interface for platform agents. Platform agents are environment-specific
* handlers which are used by the Mixin subsystem to perform platform-specific
* tasks required by different environments without having to litter the Mixin
* codebase with a bunch of environment-specific cruft.
*
* <p>Agents handle mixin environment launch tasks on a per-container basis,
* <p>Platform Agents handle mixin environment tasks on a per-container basis,
* with each container in the environment being assigned one of each available
* type of agent to handle those tasks on behalf of the container.</p>
*/
interface IMixinLaunchAgent {
public interface IMixinPlatformAgent {
/**
* Get the phase provider for this agent
*/
public abstract String getPhaseProvider();
/**
* Called during pre-initialisation, after all tweakers and tweak containers
@@ -44,6 +49,13 @@ interface IMixinLaunchAgent {
*/
public abstract void prepare();
/**
* Called from <tt>injectIntoClassLoader</tt> in the parent tweaker but <b>
* only called on the primary tweak container</b>. This is useful if the
* agent needs to perform some environment-specific setup just once.
*/
public abstract void initPrimaryContainer();
/**
* Called from <tt>injectIntoClassLoader</tt> in the parent tweaker
*
@@ -56,4 +68,5 @@ interface IMixinLaunchAgent {
* custom target is available.
*/
public abstract String getLaunchTarget();
}
@@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.io.IOException;
@@ -22,46 +22,51 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* A collection of {@link IMixinLaunchAgent launch agents)
* A collection of {@link IMixinPlatformAgent} platform agents)
*/
public class MixinTweakContainer {
public class MixinContainer {
public static final List<String> agentClasses = new ArrayList<String>();
static {
Launch.blackboard.put("mixin.agents", MixinTweakContainer.agentClasses);
MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentFML");
MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentDefault");
Blackboard.put(Blackboard.Keys.AGENTS, MixinContainer.agentClasses);
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentFML");
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault");
}
private final Logger logger = LogManager.getLogger("mixin");
private final URI uri;
private final List<IMixinLaunchAgent> agents = new ArrayList<IMixinLaunchAgent>();
private final List<IMixinPlatformAgent> agents = new ArrayList<IMixinPlatformAgent>();
public MixinTweakContainer(URI uri) {
public MixinContainer(MixinPlatformManager manager, URI uri) {
this.uri = uri;
for (String agentClass : MixinTweakContainer.agentClasses) {
for (String agentClass : MixinContainer.agentClasses) {
try {
@SuppressWarnings("unchecked")
Class<IMixinLaunchAgent> clazz = (Class<IMixinLaunchAgent>)Class.forName(agentClass);
Constructor<IMixinLaunchAgent> ctor = clazz.getDeclaredConstructor(URI.class);
IMixinLaunchAgent agent = ctor.newInstance(uri);
Class<IMixinPlatformAgent> clazz = (Class<IMixinPlatformAgent>)Class.forName(agentClass);
Constructor<IMixinPlatformAgent> ctor = clazz.getDeclaredConstructor(MixinPlatformManager.class, URI.class);
IMixinPlatformAgent agent = ctor.newInstance(manager, uri);
this.agents.add(agent);
} catch (Exception ex) {
ex.printStackTrace();
this.logger.catching(ex);
}
}
}
@@ -73,26 +78,44 @@ public class MixinTweakContainer {
return this.uri;
}
public Collection<String> getPhaseProviders() {
List<String> phaseProviders = new ArrayList<String>();
for (IMixinPlatformAgent agent : this.agents) {
String phaseProvider = agent.getPhaseProvider();
if (phaseProvider != null) {
phaseProviders.add(phaseProvider);
}
}
return phaseProviders;
}
/**
*
*/
public void prepare() {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
agent.prepare();
}
}
public void initPrimaryContainer() {
for (IMixinPlatformAgent agent : this.agents) {
this.logger.debug("Processing launch tasks for {}", agent);
agent.initPrimaryContainer();
}
}
/**
* @param classLoader
*/
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
agent.injectIntoClassLoader(classLoader);
}
}
public String getLaunchTarget() {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
String launchTarget = agent.getLaunchTarget();
if (launchTarget != null) {
return launchTarget;
@@ -22,17 +22,26 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.net.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Launch agent base class
* Platform agent base class
*/
public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent {
/**
* Logger
*/
protected static final Logger logger = LogManager.getLogger("mixin");
protected final MixinPlatformManager manager;
/**
* URI to the container
*/
@@ -49,11 +58,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
protected final MainAttributes attributes;
/**
* Create a new launch agent for the specified URI
* Create a new platform agent for the specified URI
*
* @param uri
*/
public MixinLaunchAgentAbstract(URI uri) {
public MixinPlatformAgentAbstract(MixinPlatformManager manager, URI uri) {
this.manager = manager;
this.uri = uri;
this.container = this.uri != null ? new File(this.uri) : null;
this.attributes = MainAttributes.of(uri);
@@ -61,7 +71,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
@Override
public String toString() {
return String.format("LaunchAgent[%s:%s]", this.getClass().getSimpleName(), this.uri);
return String.format("PlatformAgent[%s:%s]", this.getClass().getSimpleName(), this.uri);
}
@Override
public String getPhaseProvider() {
return null;
}
}
@@ -22,42 +22,50 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.net.URI;
import org.spongepowered.asm.util.Constants.ManifestAttributes;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Default launch agent, handles the <tt>MixinConfigs</tt> manifest key
* Default platform agent, handles the mixin manifest keys such as
* <tt>MixinConfigs</tt> and <tt>MixinTokenProviders</tt>.
*/
public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract {
protected static final String MFATT_MIXINCONFIGS = "MixinConfigs";
protected static final String MFATT_TOKENPROVIDERS = "MixinTokenProviders";
protected static final String MFATT_MAINCLASS = "Main-Class";
public MixinLaunchAgentDefault(URI uri) {
super(uri);
public MixinPlatformAgentDefault(MixinPlatformManager manager, URI uri) {
super(manager, uri);
}
@Override
public void prepare() {
String mixinConfigs = this.attributes.get(MixinLaunchAgentDefault.MFATT_MIXINCONFIGS);
@SuppressWarnings("deprecation")
String compatibilityLevel = this.attributes.get(ManifestAttributes.COMPATIBILITY);
if (compatibilityLevel != null) {
this.manager.setCompatibilityLevel(compatibilityLevel);
}
String mixinConfigs = this.attributes.get(ManifestAttributes.MIXINCONFIGS);
if (mixinConfigs != null) {
for (String config : mixinConfigs.split(",")) {
MixinTweaker.addConfig(config.trim());
this.manager.addConfig(config.trim());
}
}
String tokenProviders = this.attributes.get(MixinLaunchAgentDefault.MFATT_TOKENPROVIDERS);
String tokenProviders = this.attributes.get(ManifestAttributes.TOKENPROVIDERS);
if (tokenProviders != null) {
for (String provider : tokenProviders.split(",")) {
MixinTweaker.addTokenProvider(provider.trim());
this.manager.addTokenProvider(provider.trim());
}
}
}
@Override
public void initPrimaryContainer() {
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
@@ -65,7 +73,7 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
@Override
public String getLaunchTarget() {
return this.attributes.get(MixinLaunchAgentDefault.MFATT_MAINCLASS);
return this.attributes.get(ManifestAttributes.MAINCLASS);
}
}
@@ -22,28 +22,46 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
//import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.Level;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.mixin.MixinEnvironment;
//import org.spongepowered.asm.mixin.environment.IPhaseProvider;
//import org.spongepowered.asm.mixin.environment.PhaseDefinition;
//import org.spongepowered.asm.mixin.environment.phase.OnLogMessage;
import org.spongepowered.asm.mixin.extensibility.IRemapper;
//import com.google.common.collect.ImmutableList;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Launch agent for use under FML.
* Platform agent for use under FML.
*
* <p>When FML is present we scan containers for the manifest entries which are
* inhibited by the tweaker, in particular the <tt>FMLCorePlugin</tt> and
* <tt>FMLCorePluginContainsFMLMod</tt> entries. This is required because FML
* performs no further processing of containers if they contain a tweaker!</p>
*/
public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract {
private static final String LOAD_CORE_MOD_METHOD = "loadCoreMod";
private static final String GET_REPARSEABLE_COREMODS_METHOD = "getReparseableCoremods";
private static final String CORE_MOD_MANAGER_CLASS = "net.minecraftforge.fml.relauncher.CoreModManager";
private static final String GET_IGNORED_MODS_METHOD = "getIgnoredMods";
private static final String FML_REMAPPER_ADAPTER_CLASS = "org.spongepowered.asm.bridge.RemapperAdapterFML";
private static final String MFATT_FORCELOADASMOD = "ForceLoadAsMod";
private static final String MFATT_FMLCOREPLUGIN = "FMLCorePlugin";
@@ -72,8 +90,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
/**
* @param uri
*/
public MixinLaunchAgentFML(URI uri) {
super(uri);
public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) {
super(manager, uri);
this.fileName = this.container.getName();
this.coreModWrapper = this.initFMLCoreMod();
}
@@ -83,17 +101,16 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private ITweaker initFMLCoreMod() {
try {
this.clCoreModManager = MixinLaunchAgentFML.getCoreModManagerClass();
this.clCoreModManager = MixinPlatformAgentFML.getCoreModManagerClass();
if ("true".equalsIgnoreCase(this.attributes.get(MixinLaunchAgentFML.MFATT_FORCELOADASMOD))) {
if ("true".equalsIgnoreCase(this.attributes.get(MixinPlatformAgentFML.MFATT_FORCELOADASMOD))) {
this.loadAsMod();
}
return this.injectCorePlugin();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
return null;
}
/**
@@ -109,15 +126,12 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private void loadAsMod() {
try {
Method mdGetLoadedCoremods = this.clCoreModManager.getDeclaredMethod("getLoadedCoremods");
@SuppressWarnings("unchecked")
List<String> loadedCoremods = (List<String>)mdGetLoadedCoremods.invoke(null);
loadedCoremods.remove(this.fileName);
MixinPlatformAgentFML.getIgnoredMods(this.clCoreModManager).remove(this.fileName);
} catch (Exception ex) {
ex.printStackTrace();
MixinPlatformAgentAbstract.logger.catching(ex);
}
if (this.attributes.get(MixinLaunchAgentFML.MFATT_COREMODCONTAINSMOD) != null) {
if (this.attributes.get(MixinPlatformAgentFML.MFATT_COREMODCONTAINSMOD) != null) {
this.addReparseableJar();
}
}
@@ -128,7 +142,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private void addReparseableJar() {
try {
Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod("getReparseableCoremods");
Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_GET_REPARSEABLE_COREMODS, MixinPlatformAgentFML.GET_REPARSEABLE_COREMODS_METHOD));
@SuppressWarnings("unchecked")
List<String> reparsedCoremods = (List<String>)mdGetReparsedCoremods.invoke(null);
if (!reparsedCoremods.contains(this.fileName)) {
@@ -140,12 +155,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
}
private ITweaker injectCorePlugin() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String coreModName = this.attributes.get(MixinLaunchAgentFML.MFATT_FMLCOREPLUGIN);
String coreModName = this.attributes.get(MixinPlatformAgentFML.MFATT_FMLCOREPLUGIN);
if (coreModName == null) {
return null;
}
Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod("loadCoreMod", LaunchClassLoader.class, String.class, File.class);
Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_LOAD_CORE_MOD, MixinPlatformAgentFML.LOAD_CORE_MOD_METHOD), LaunchClassLoader.class, String.class, File.class);
mdLoadCoreMod.setAccessible(true);
ITweaker wrapper = (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.container);
if (wrapper == null) {
@@ -154,16 +170,44 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
return wrapper;
}
@Override
public String getPhaseProvider() {
return MixinPlatformAgentFML.class.getName() + "$PhaseProvider";
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent#prepare()
* @see org.spongepowered.asm.launch.IMixinPlatformAgent#prepare()
*/
@Override
public void prepare() {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinPlatformAgent
* #initPrimaryContainer()
*/
@Override
public void initPrimaryContainer() {
if (this.clCoreModManager != null) {
// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFML.class.getName() + "$PhaseProvider");
this.injectRemapper();
}
}
private void injectRemapper() {
try {
Class<?> clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader);
Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create");
IRemapper remapper = (IRemapper)mdCreate.invoke(null);
MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper);
} catch (Exception ex) {
MixinPlatformAgentAbstract.logger.debug("Failed instancing FML remapper adapter, things will probably go horribly for notch-obf'd mods!");
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent
* @see org.spongepowered.asm.launch.IMixinPlatformAgent
* #injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader)
*/
@Override
@@ -174,13 +218,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent#getLaunchTarget()
* @see org.spongepowered.asm.launch.IMixinPlatformAgent#getLaunchTarget()
*/
@Override
public String getLaunchTarget() {
return null;
}
/**
* Performs a naive check which attempts to discover whether we are pre or
* post FML's main injection. If we are <i>pre</i>, then we must <b>not</b>
@@ -193,9 +237,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*
* @return true if FML was already injected
*/
@SuppressWarnings("unchecked")
protected final boolean isFMLInjected() {
for (String tweaker : (List<String>)Launch.blackboard.get("TweakClasses")) {
for (String tweaker : Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES)) {
if (tweaker.endsWith("FMLDeobfTweaker")) {
return true;
}
@@ -209,10 +252,31 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private static Class<?> getCoreModManagerClass() throws ClassNotFoundException {
try {
return Class.forName("net.minecraftforge.fml.relauncher.CoreModManager");
return Class.forName(Blackboard.getString(
Blackboard.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS));
} catch (ClassNotFoundException ex) {
return Class.forName("cpw.mods.fml.relauncher.CoreModManager");
}
}
@SuppressWarnings("unchecked")
private static List<String> getIgnoredMods(Class<?> clCoreModManager) throws IllegalAccessException, InvocationTargetException {
Method mdGetIgnoredMods = null;
try {
mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_GET_IGNORED_MODS, MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD));
} catch (NoSuchMethodException ex1) {
try {
// Legacy name
mdGetIgnoredMods = clCoreModManager.getDeclaredMethod("getLoadedCoremods");
} catch (NoSuchMethodException ex2) {
MixinPlatformAgentAbstract.logger.catching(Level.DEBUG, ex2);
return Collections.<String>emptyList();
}
}
return (List<String>)mdGetIgnoredMods.invoke(null);
}
}
@@ -0,0 +1,287 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//import org.spongepowered.asm.launch.MixinBootstrap.Delegate;
import org.spongepowered.asm.launch.MixinTweaker;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.Mixins;
//import com.google.common.collect.ImmutableList;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Handler for platform-specific behaviour required in different mixin
* environments.
*/
public class MixinPlatformManager {
private static final String MFATT_TWEAKER = "TweakClass";
private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main";
/**
* Make with the logging already
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Bootstrap delegate
*/
// private final Delegate delegate;
/**
* Tweak containers
*/
private final Map<URI, MixinContainer> containers = new LinkedHashMap<URI, MixinContainer>();
/**
* Container for this tweaker
*/
private MixinContainer primaryContainer;
/**
* Tracks whether {@link #acceptOptions} was called yet, if true, causes new
* agents to be <tt>prepare</tt>d immediately
*/
private boolean prepared = false;
/**
* Tracks whether {@link #injectIntoClassLoader} was called yet
*/
private boolean injected;
public MixinPlatformManager() { //Delegate delegate) {
// this.delegate = delegate;
// Add agents for the tweak container
URI uri = null;
try {
uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
if (uri != null) {
this.primaryContainer = this.addContainer(uri);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
public Collection<String> getPhaseProviderClasses() {
Collection<String> phaseProviders = this.primaryContainer.getPhaseProviders();
if (phaseProviders != null) {
return Collections.<String>unmodifiableCollection(phaseProviders);
}
return Collections.<String>emptyList();
}
public final MixinContainer addContainer(URI uri) {
MixinContainer existingContainer = this.containers.get(uri);
if (existingContainer != null) {
return existingContainer;
}
MixinPlatformManager.logger.debug("Adding mixin platform agents for container {}", uri);
MixinContainer container = new MixinContainer(this, uri);
this.containers.put(uri, container);
if (this.prepared) {
container.prepare();
}
return container;
}
public final void prepare(List<String> args) {
this.prepared = true;
for (MixinContainer container : this.containers.values()) {
container.prepare();
}
if (args != null) {
this.parseArgs(args);
} else {
String argv = System.getProperty("sun.java.command");
if (argv != null) {
this.parseArgs(Arrays.asList(argv.split(" ")));
}
}
}
/**
* Read and parse command-line arguments
*
* @param args command-line arguments
*/
private void parseArgs(List<String> args) {
boolean captureNext = false;
for (String arg : args) {
if (captureNext) {
this.addConfig(arg);
}
captureNext = "--mixin".equals(arg);
}
}
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
if (this.injected) {
return;
}
this.injected = true;
if (this.primaryContainer != null) {
this.primaryContainer.initPrimaryContainer();
}
this.scanClasspath();
MixinPlatformManager.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size());
for (MixinContainer container : this.containers.values()) {
try {
container.injectIntoClassLoader(classLoader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Scan the classpath for mixin containers (containers which declare the
* mixin tweaker in their manifest) and add agents for them
*/
private void scanClasspath() {
for (URL url : Launch.classLoader.getSources()) {
try {
URI uri = url.toURI();
if (this.containers.containsKey(uri)) {
continue;
}
MixinPlatformManager.logger.debug("Scanning {} for mixin tweaker", uri);
if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) {
continue;
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(MixinPlatformManager.MFATT_TWEAKER);
if (MixinTweaker.class.getName().equals(tweaker)) {
MixinPlatformManager.logger.debug("{} contains a mixin tweaker, adding agents", uri);
this.addContainer(uri);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public String getLaunchTarget() {
for (MixinContainer container : this.containers.values()) {
String mainClass = container.getLaunchTarget();
if (mainClass != null) {
return mainClass;
}
}
return MixinPlatformManager.DEFAULT_MAIN_CLASS;
}
/**
* Set the desired compatibility level as a string, used by agents to set
* compatibility level from jar manifest
*
* @param level compatibility level as a string
*/
@SuppressWarnings("deprecation")
final void setCompatibilityLevel(String level) {
try {
CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase());
MixinPlatformManager.logger.debug("Setting mixin compatibility level: {}", value);
MixinEnvironment.setCompatibilityLevel(value);
} catch (IllegalArgumentException ex) {
MixinPlatformManager.logger.warn("Invalid compatibility level specified: {}", level);
}
}
/**
* Add a config from a jar manifest source or the command line. Supports
* config declarations in the form <tt>filename.json</tt> or alternatively
* <tt>filename.json&#064;PHASE</tt> where <tt>PHASE</tt> is a
* case-sensitive string token representing an environment phase.
*
* @param config config resource name, does not require a leading /
*/
@SuppressWarnings("deprecation")
final void addConfig(String config) {
if (config.endsWith(".json")) {
MixinPlatformManager.logger.debug("Registering mixin config: {}", config);
Mixins.addConfiguration(config);
} else if (config.contains(".json@")) {
int pos = config.indexOf(".json@");
String phaseName = config.substring(pos + 6);
config = config.substring(0, pos + 5);
Phase phase = Phase.forName(phaseName);
if (phase != null) {
MixinPlatformManager.logger.warn("Setting config phase via manifest is deprecated: {}. Specify target in config instead", config);
MixinPlatformManager.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getEnvironment(phase).addConfiguration(config);
}
}
}
/**
* Add a token provider class from a jar manifest source. Supports either
* bare class names in the form <tt>blah.package.ClassName</tt> or
* alternatively <tt>blah.package.ClassName&#064;PHASE</tt> where
* <tt>PHASE</tt> is a case-sensitive string token representing an
* environment phase name.
*
* @param provider provider class name, optionally suffixed with &#064;PHASE
*/
final void addTokenProvider(String provider) {
if (provider.contains("@")) {
String[] parts = provider.split("@", 2);
Phase phase = Phase.forName(parts[1]);
if (phase != null) {
MixinPlatformManager.logger.debug("Registering token provider class: {}", parts[0]);
MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]);
}
return;
}
MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider);
}
}
@@ -0,0 +1,64 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Anotation used to decorate items you might wish to examine after mixin
* application.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Debug {
/**
* Only applicable for classes, use this to decorate mixins that you wish
* to export even if <tt>mixin.debug.export</tt> is not enabled. This is
* useful if you wish to export only the target of the mixin you are working
* on without enabling export globally.
*
* <p>Note that if <tt>mixin.debug.export</tt> is <b>not</b> <tt>true</tt>
* then the decompiler is <em>not</em> initialised (even if present on the
* classpath) and thus you must set <tt>mixin.debug.export.decompile</tt> to
* <tt>true</tt> in order to have force-exported classes decompiled.</p>
*
* @return whether to export the decorated target class
*/
public boolean export() default false;
/**
* Print the method bytecode to the console after mixin application. This
* setting is only used if the <tt>mixin.debug.verbose</tt> option is
* enabled.
*
* @return whether to print the class or method to the console.
*/
public boolean print() default false;
}
@@ -0,0 +1,62 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* This annotation has two uses:
*
* <ul>
* <li>
* On an {@link Shadow} field, it can be used to raise an error-level log
* message if any write occurrences appear in the mixin bytecode. This can
* be used in place of declaring the field as actually <tt>final</tt>. This
* is required since it is normally desirable to remove the <tt>final</tt>
* modifier from shadow fields to avoid unwanted field initialisers. If
* {@link Option#DEBUG_VERIFY} is <tt>true</tt>, then an
* {@link InvalidMixinException} is thrown.
* </li>
* <li>
* On an {@link Inject injector} or {@link Overwrite overwritten} method,
* it is equivalent to setting the priority of the containing mixin to
* {@link Integer#MAX_VALUE} but applies only to the annotated method. This
* allows methods to mark themselves as effectively final, preventing their
* replacement by later mixins with higher priority.
* </li>
* </ul>
*/
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Final {
}
@@ -53,4 +53,12 @@ public @interface Interface {
*/
public String prefix();
/**
* If set to <tt>true</tt>, all methods implementing this interface are
* treated as if they were individually decorated with {@link Unique}
*
* @return true to mark all implementing methods as unique
*/
public boolean unique() default false;
}
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation allows fine-tuning of the overwrite policy for a
* soft-implemented interface member method.
@@ -25,23 +25,36 @@
package org.spongepowered.asm.mixin;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.obfuscation.RemapperChain;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.PrettyPrinter;
import com.google.common.collect.ImmutableList;
@@ -53,12 +66,11 @@ import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* The mixin environment manages global state information for the mixin
* subsystem.
*/
public class MixinEnvironment implements ITokenProvider {
public final class MixinEnvironment implements ITokenProvider {
/**
* Environment phase, deliberately not implemented as an enum
@@ -76,16 +88,22 @@ public class MixinEnvironment implements ITokenProvider {
*/
public static final Phase PREINIT = new Phase(0, "PREINIT");
/**
* "Initialisation" phase, after FML's deobf transformer has loaded
*/
public static final Phase INIT = new Phase(1, "INIT");
/**
* "Default" phase, during runtime
*/
public static final Phase DEFAULT = new Phase(1, "DEFAULT");
public static final Phase DEFAULT = new Phase(2, "DEFAULT");
/**
* All phases
*/
static final List<Phase> phases = ImmutableList.of(
Phase.PREINIT,
Phase.INIT,
Phase.DEFAULT
);
@@ -175,11 +193,10 @@ public class MixinEnvironment implements ITokenProvider {
protected abstract boolean detect();
@SuppressWarnings("unchecked")
protected final String getSideName() {
// Using this method first prevents us from accidentally loading FML classes
// too early when using the tweaker in dev
for (ITweaker tweaker : (List<ITweaker>)Launch.blackboard.get("Tweaks")) {
for (ITweaker tweaker : Blackboard.<List<ITweaker>>get(Blackboard.Keys.TWEAKS)) {
if (tweaker.getClass().getName().endsWith(".common.launcher.FMLServerTweaker")) {
return "SERVER";
} else if (tweaker.getClass().getName().endsWith(".common.launcher.FMLTweaker")) {
@@ -197,7 +214,7 @@ public class MixinEnvironment implements ITokenProvider {
return name;
}
name = this.getSideName("com.mumfrey.liteloader.core.LiteLoader", "getEnvironmentType");
name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType");
if (name != null) {
return name;
}
@@ -246,10 +263,22 @@ public class MixinEnvironment implements ITokenProvider {
* <dt>?</dt><dd>Matches exactly one character</dd>
* </dl>
*/
DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter"),
DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter", false),
/**
* Run the CheckClassAdapter on all classes after mixins are applied
* Allow fernflower to be disabled even if it is found on the classpath
*/
DEBUG_EXPORT_DECOMPILE(Option.DEBUG_EXPORT, "decompile") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue());
}
},
/**
* Run the CheckClassAdapter on all classes after mixins are applied,
* also enables stricter checks on mixins for use at dev-time, promotes
* some warning-level messages to exceptions
*/
DEBUG_VERIFY(Option.DEBUG_ALL, "verify"),
@@ -259,6 +288,44 @@ public class MixinEnvironment implements ITokenProvider {
*/
DEBUG_VERBOSE(Option.DEBUG_ALL, "verbose"),
/**
* Elevates failed injections to an error condition, see
* {@link Inject#expect} for details
*/
DEBUG_INJECTORS(Option.DEBUG_ALL, "countInjections"),
/**
* Enable strict checks
*/
DEBUG_STRICT(Option.DEBUG_ALL, "strict") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), false);
}
},
/**
* If false (default), {@link Unique} public methods merely raise a
* warning when encountered and are not merged into the target. If true,
* an exception is thrown instead
*/
DEBUG_UNIQUE(Option.DEBUG_STRICT, "unique"),
/**
* Enable strict checking for mixin targets
*/
DEBUG_TARGETS(Option.DEBUG_STRICT, "targets"),
/**
* Disable the injector handler remapper
*/
DEBUG_DISABLE_HANDLER_REMAP(Option.DEBUG_ALL, "disableHandlerRename") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue());
}
},
/**
* Dumps the bytecode for the target class to disk when mixin
* application fails
@@ -279,8 +346,38 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Ignore all constraints on mixin annotations, output warnings instead
*/
IGNORE_CONSTRAINTS("ignoreConstraints");
IGNORE_CONSTRAINTS("ignoreConstraints"),
/**
* Enables the hot-swap agent
*/
HOT_SWAP("hotSwap"),
/**
* Parent for environment settings
*/
ENVIRONMENT("env") {
@Override
boolean getBooleanValue() {
return false;
}
},
/**
* Force refmap obf type when required
*/
OBFUSCATION_TYPE(Option.ENVIRONMENT, "obf"),
/**
* Disable refmap when required
*/
DISABLE_REFMAP(Option.ENVIRONMENT, "disableRefMap"),
/**
* Default compatibility level to operate at
*/
DEFAULT_COMPATIBILITY_LEVEL(Option.ENVIRONMENT, "compatLevel");
/**
* Prefix for mixin options
*/
@@ -296,14 +393,38 @@ public class MixinEnvironment implements ITokenProvider {
* Java property name
*/
final String property;
/**
* Whether this property is boolean or not
*/
final boolean flag;
/**
* Number of parents
*/
final int depth;
private Option(String property) {
this(null, property);
this(null, property, true);
}
private Option(String property, boolean flag) {
this(null, property, flag);
}
private Option(Option parent, String property) {
this(parent, property, true);
}
private Option(Option parent, String property, boolean flag) {
this.parent = parent;
this.property = (parent != null ? parent.property : Option.PREFIX) + "." + property;
this.flag = flag;
int depth = 0;
for (; parent != null; depth++) {
parent = parent.parent;
}
this.depth = depth;
}
Option getParent() {
@@ -314,6 +435,11 @@ public class MixinEnvironment implements ITokenProvider {
return this.property;
}
@Override
public String toString() {
return this.flag ? String.valueOf(this.getBooleanValue()) : this.getStringValue();
}
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), false)
|| (this.parent != null && this.parent.getBooleanValue());
@@ -322,6 +448,93 @@ public class MixinEnvironment implements ITokenProvider {
String getStringValue() {
return (this.parent == null || this.parent.getBooleanValue()) ? System.getProperty(this.property) : null;
}
@SuppressWarnings("unchecked")
<E extends Enum<E>> E getEnumValue(E defaultValue) {
String value = System.getProperty(this.property, defaultValue.name());
try {
return (E) Enum.valueOf(defaultValue.getClass(), value);
} catch (IllegalArgumentException ex) {
return defaultValue;
}
}
}
/**
* Operational compatibility level for the mixin subsystem
*/
public static enum CompatibilityLevel {
JAVA_6(6, Opcodes.V1_6, false),
JAVA_7(7, Opcodes.V1_7, false) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.7;
}
},
JAVA_8(8, Opcodes.V1_8, true) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.8;
}
};
private final int ver;
private final int classVersion;
private final boolean supportsMethodsInInterfaces;
private CompatibilityLevel maxCompatibleLevel;
private CompatibilityLevel(int ver, int classVersion, boolean resolveMethodsInInterfaces) {
this.ver = ver;
this.classVersion = classVersion;
this.supportsMethodsInInterfaces = resolveMethodsInInterfaces;
}
@SuppressWarnings("unused")
private void setMaxCompatibleLevel(CompatibilityLevel maxCompatibleLevel) {
this.maxCompatibleLevel = maxCompatibleLevel;
}
boolean isSupported() {
return true;
}
public int classVersion() {
return this.classVersion;
}
public boolean supportsMethodsInInterfaces() {
return this.supportsMethodsInInterfaces;
}
public boolean isAtLeast(CompatibilityLevel level) {
return this.ver >= level.ver;
}
public boolean canElevateTo(CompatibilityLevel level) {
if (level == null || this.maxCompatibleLevel == null) {
return true;
}
return level.ver <= this.maxCompatibleLevel.ver;
}
public boolean canSupport(CompatibilityLevel level) {
if (level == null) {
return true;
}
return level.canElevateTo(this);
}
}
/**
@@ -336,6 +549,7 @@ public class MixinEnvironment implements ITokenProvider {
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
}
@Override
@@ -392,6 +606,39 @@ public class MixinEnvironment implements ITokenProvider {
}
/**
* Temporary
*/
static class MixinLogger {
static MixinAppender appender = new MixinAppender("MixinLogger", null, null);
public MixinLogger() {
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
appender.start();
log.addAppender(appender);
}
/**
* Temporary
*/
static class MixinAppender extends AbstractAppender {
protected MixinAppender(String name, Filter filter, Layout<? extends Serializable> layout) {
super(name, filter, layout);
}
@Override
public void append(LogEvent event) {
if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) {
// transition to INIT
MixinEnvironment.gotoPhase(Phase.INIT);
}
}
}
}
/**
* Known re-entrant transformers, other re-entrant transformers will
* detected automatically
@@ -403,10 +650,6 @@ public class MixinEnvironment implements ITokenProvider {
"cpw.mods.fml.common.asm.transformers.TerminalTransformer"
);
// Blackboard keys
private static final String CONFIGS_KEY = "mixin.configs";
private static final String TRANSFORMER_KEY = "mixin.transformer";
/**
* Currently active environment
*/
@@ -418,6 +661,11 @@ public class MixinEnvironment implements ITokenProvider {
*/
private static Phase currentPhase = Phase.NOT_INITIALISED;
/**
* Current compatibility level
*/
private static CompatibilityLevel compatibility = Option.DEFAULT_COMPATIBILITY_LEVEL.<CompatibilityLevel>getEnumValue(CompatibilityLevel.JAVA_6);
/**
* Show debug header info on first environment construction
*/
@@ -426,7 +674,7 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Logger
*/
private final Logger logger = LogManager.getLogger("mixin");
private static final Logger logger = LogManager.getLogger("mixin");
/**
* The phase for this environment
@@ -443,10 +691,7 @@ public class MixinEnvironment implements ITokenProvider {
*/
private final boolean[] options;
/**
* Error handlers for environment
*/
private final Set<String> errorHandlers = new LinkedHashSet<String>();
// private final Map<String, MixinConfig> configs;
/**
* List of token provider classes
@@ -462,6 +707,11 @@ public class MixinEnvironment implements ITokenProvider {
* Internal tokens defined by this environment
*/
private final Map<String, Integer> internalTokens = new HashMap<String, Integer>();
/**
* Remappers for this environment
*/
private final RemapperChain remappers = new RemapperChain();
/**
* Detected side
@@ -481,19 +731,24 @@ public class MixinEnvironment implements ITokenProvider {
*/
private IClassNameTransformer nameTransformer;
/**
* Obfuscation context (refmap key to use in this environment)
*/
private String obfuscationContext = null;
MixinEnvironment(Phase phase) {
this.phase = phase;
this.configsKey = MixinEnvironment.CONFIGS_KEY + "." + this.phase.name.toLowerCase();
this.configsKey = Blackboard.Keys.CONFIGS + "." + this.phase.name.toLowerCase();
// Sanity check
Object version = Launch.blackboard.get(MixinBootstrap.INIT_KEY);
Object version = this.getVersion();
if (version == null || !MixinBootstrap.VERSION.equals(version)) {
throw new RuntimeException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()");
throw new MixinException("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");
throw new MixinException("Attempted to init the mixin environment in the wrong classloader");
}
this.options = new boolean[Option.values().length];
@@ -510,17 +765,22 @@ public class MixinEnvironment implements ITokenProvider {
private void printHeader(Object version) {
Side side = this.getSide();
String codeSource = this.getCodeSource();
this.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
if (this.getOption(Option.DEBUG_VERBOSE)) {
PrettyPrinter printer = new PrettyPrinter(32);
printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr();
printer.add("%25s : %s", "Code source", codeSource);
printer.add("%25s : %s", "Internal Version", version).hr();
printer.kv("Code source", codeSource);
printer.kv("Internal Version", version);
printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr();
for (Option option : Option.values()) {
printer.add("%25s : %s%s", option.property, option.parent == null ? "" : " - ", this.getOption(option));
StringBuilder indent = new StringBuilder();
for (int i = 0; i < option.depth; i++) {
indent.append("- ");
}
printer.kv(option.property, "%s<%s>", indent, option);
}
printer.hr().add("%25s : %s", "Detected Side", side);
printer.hr().kv("Detected Side", side);
printer.print(System.err);
}
}
@@ -546,10 +806,11 @@ public class MixinEnvironment implements ITokenProvider {
* Get mixin configurations from the blackboard
*
* @return list of registered mixin configs
* @deprecated no replacement
*/
@Deprecated
public List<String> getMixinConfigs() {
@SuppressWarnings("unchecked")
List<String> mixinConfigs = (List<String>) Launch.blackboard.get(this.configsKey);
List<String> mixinConfigs = Blackboard.<List<String>>get(this.configsKey);
if (mixinConfigs == null) {
mixinConfigs = new ArrayList<String>();
Launch.blackboard.put(this.configsKey, mixinConfigs);
@@ -562,23 +823,32 @@ public class MixinEnvironment implements ITokenProvider {
*
* @param config Name of configuration resource to add
* @return fluent interface
* @deprecated use Mixins::addConfiguration instead
*/
@Deprecated
public MixinEnvironment addConfiguration(String config) {
MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!");
Mixins.addConfiguration(config, this);
return this;
}
void registerConfig(String config) {
List<String> configs = this.getMixinConfigs();
if (!configs.contains(config)) {
configs.add(config);
}
return this;
}
/**
* Add a new error handler class to this environment
*
* @param handlerName Handler class to add
* @return fluent interface
* @deprecated use Mixins::registerErrorHandlerClass
*/
@Deprecated
public MixinEnvironment registerErrorHandlerClass(String handlerName) {
this.errorHandlers.add(handlerName);
Mixins.registerErrorHandlerClass(handlerName);
return this;
}
@@ -597,7 +867,7 @@ public class MixinEnvironment implements ITokenProvider {
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
this.logger.error("Error instantiating " + providerName, th);
MixinEnvironment.logger.error("Error instantiating " + providerName, th);
}
}
return this;
@@ -613,7 +883,7 @@ public class MixinEnvironment implements ITokenProvider {
if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) {
String providerName = provider.getClass().getName();
TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this);
this.logger.info("Adding new token provider {} to {}", providerName, this);
MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this);
this.tokenProviders.add(wrapper);
this.tokenProviderClasses.add(providerName);
Collections.sort(this.tokenProviders);
@@ -647,9 +917,11 @@ public class MixinEnvironment implements ITokenProvider {
* Get all registered error handlers for this environment
*
* @return set of error handler class names
* @deprecated use Mixins::getErrorHandlerClasses
*/
@Deprecated
public Set<String> getErrorHandlerClasses() {
return Collections.<String>unmodifiableSet(this.errorHandlers);
return Mixins.getErrorHandlerClasses();
}
/**
@@ -658,7 +930,7 @@ public class MixinEnvironment implements ITokenProvider {
* @return active mixin transformer instance
*/
public Object getActiveTransformer() {
return Launch.blackboard.get(MixinEnvironment.TRANSFORMER_KEY);
return Blackboard.get(Blackboard.Keys.TRANSFORMER);
}
/**
@@ -668,7 +940,7 @@ public class MixinEnvironment implements ITokenProvider {
*/
public void setActiveTransformer(IClassTransformer transformer) {
if (transformer != null) {
Launch.blackboard.put(MixinEnvironment.TRANSFORMER_KEY, transformer);
Blackboard.put(Blackboard.Keys.TRANSFORMER, transformer);
}
}
@@ -709,7 +981,7 @@ public class MixinEnvironment implements ITokenProvider {
* @return current version
*/
public String getVersion() {
return (String)Launch.blackboard.get(MixinBootstrap.INIT_KEY);
return Blackboard.<String>get(Blackboard.Keys.INIT);
}
/**
@@ -742,6 +1014,40 @@ public class MixinEnvironment implements ITokenProvider {
return option.getStringValue();
}
/**
* Set the obfuscation context
*
* @param context
*/
public void setObfuscationContext(String context) {
this.obfuscationContext = context;
}
/**
* Get the current obfuscation context
*/
public String getObfuscationContext() {
return this.obfuscationContext;
}
/**
* Get the current obfuscation context
*/
public String getRefmapObfuscationContext() {
String overrideObfuscationType = Option.OBFUSCATION_TYPE.getStringValue();
if (overrideObfuscationType != null) {
return overrideObfuscationType;
}
return this.obfuscationContext;
}
/**
* Get the remapper chain for this environment
*/
public RemapperChain getRemappers() {
return this.remappers;
}
/**
* Invoke a mixin environment audit process
*/
@@ -804,7 +1110,7 @@ public class MixinEnvironment implements ITokenProvider {
* list just once per environment and cache the result.
*/
private void buildTransformerDelegationList() {
this.logger.debug("Rebuilding transformer delegation list:");
MixinEnvironment.logger.debug("Rebuilding transformer delegation list:");
this.transformers = new ArrayList<IClassTransformer>();
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
String transformerName = transformer.getClass().getName();
@@ -815,19 +1121,20 @@ public class MixinEnvironment implements ITokenProvider {
break;
}
}
if (include && !transformerName.contains(MixinTransformer.class.getName())) {
this.logger.debug(" Adding: {}", transformerName);
boolean ignoreTransformer = transformer.getClass().getAnnotation(Resource.class) != null;
if (include && !ignoreTransformer && !transformerName.contains(MixinTransformer.class.getName())) {
MixinEnvironment.logger.debug(" Adding: {}", transformerName);
this.transformers.add(transformer);
} else {
this.logger.debug(" Excluding: {}", transformerName);
MixinEnvironment.logger.debug(" Excluding: {}", transformerName);
}
}
this.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
this.logger.debug("Found name transformer: {}", transformer.getClass().getName());
MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName());
this.nameTransformer = (IClassNameTransformer) transformer;
}
}
@@ -861,6 +1168,9 @@ public class MixinEnvironment implements ITokenProvider {
if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) {
MixinEnvironment.currentPhase = phase;
MixinEnvironment.getEnvironment(phase);
@SuppressWarnings("unused")
MixinLogger logSpy = new MixinLogger();
}
}
@@ -899,6 +1209,37 @@ public class MixinEnvironment implements ITokenProvider {
return MixinEnvironment.currentEnvironment;
}
/**
* Get the current compatibility level
*/
public static CompatibilityLevel getCompatibilityLevel() {
return MixinEnvironment.compatibility;
}
/**
* Set desired compatibility level for the entire environment
*
* @param level Level to set, ignored if less than the current level
* @throws IllegalArgumentException if the specified level is not supported
* @deprecated set compatibility level in configuration
*/
@Deprecated
public static void setCompatibilityLevel(CompatibilityLevel level) throws IllegalArgumentException {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
if (!"org.spongepowered.asm.mixin.transformer.MixinConfig".equals(stackTrace[2].getClassName())) {
MixinEnvironment.logger.warn("MixinEnvironment::setCompatibilityLevel is deprecated and will be removed. Set level via config instead!");
}
if (level != MixinEnvironment.compatibility && level.isAtLeast(MixinEnvironment.compatibility)) {
if (!level.isSupported()) {
throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported");
}
MixinEnvironment.compatibility = level;
MixinEnvironment.logger.info("Compatibility level set to {}", level);
}
}
/**
* Internal callback
*
@@ -913,6 +1254,12 @@ public class MixinEnvironment implements ITokenProvider {
MixinBootstrap.addProxy();
}
if (phase == Phase.DEFAULT) {
// remove appender
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
log.removeAppender(MixinLogger.appender);
}
MixinEnvironment.currentPhase = phase;
MixinEnvironment.currentEnvironment = MixinEnvironment.getEnvironment(MixinEnvironment.getCurrentPhase());
}
@@ -0,0 +1,139 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.mixin.transformer.Config;
import net.minecraft.launchwrapper.Launch;
/**
* Entry point for registering global mixin resources. Compatibility with
* pre-0.6 versions is maintained via the methods on {@link MixinEnvironment}
* delegating to the methods here.
*/
public final class Mixins {
/**
* Logger
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Blackboard key storing mixin configs which are pending
*/
private static final String CONFIGS_KEY = Blackboard.Keys.CONFIGS + ".queue";
/**
* Error handlers for environment
*/
private static final Set<String> errorHandlers = new LinkedHashSet<String>();
private Mixins() {}
public static void addConfigurations(String... configFiles) {
MixinEnvironment fallback = MixinEnvironment.getDefaultEnvironment();
for (String configFile : configFiles) {
Mixins.createConfiguration(configFile, fallback);
}
}
/**
* Add a mixin configuration resource
*
* @param configFile path to configuration resource
*/
public static void addConfiguration(String configFile) {
Mixins.createConfiguration(configFile, MixinEnvironment.getDefaultEnvironment());
}
@Deprecated
static void addConfiguration(String configFile, MixinEnvironment fallback) {
Mixins.createConfiguration(configFile, fallback);
}
@SuppressWarnings("deprecation")
private static void createConfiguration(String configFile, MixinEnvironment fallback) {
Config config = null;
try {
config = Config.create(configFile, fallback);
} catch (Exception ex) {
Mixins.logger.error("Error encountered reading mixin config " + configFile + ": " + ex.getClass().getName() + " " + ex.getMessage(), ex);
}
Mixins.registerConfiguration(config);
}
private static void registerConfiguration(Config config) {
if (config == null) {
return;
}
MixinEnvironment env = config.getEnvironment();
if (env != null) {
env.registerConfig(config.getName());
}
Mixins.getConfigs().add(config);
}
/**
* Get current pending configs set, only configs which have yet to be
* consumed are present in this set
*/
public static Set<Config> getConfigs() {
Set<Config> mixinConfigs = Blackboard.<Set<Config>>get(Mixins.CONFIGS_KEY);
if (mixinConfigs == null) {
mixinConfigs = new LinkedHashSet<Config>();
Launch.blackboard.put(Mixins.CONFIGS_KEY, mixinConfigs);
}
return mixinConfigs;
}
/**
* Register a gloabl error handler class
*
* @param handlerName Fully qualified class name
*/
public static void registerErrorHandlerClass(String handlerName) {
if (handlerName != null) {
Mixins.errorHandlers.add(handlerName);
}
}
/**
* Get current error handlers
*/
public static Set<String> getErrorHandlerClasses() {
return Collections.<String>unmodifiableSet(Mixins.errorHandlers);
}
}
@@ -0,0 +1,40 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use in conjunction with {@link Final} to indicate that whilst a field is
* final in the target class, mutation within the mixin is intentional.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mutable {
}
@@ -29,7 +29,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* Used to indicate a Mixin class member which is acting as a placeholder for a
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Decorator for methods which override a method in a supermixin which the
* containing mixin does not directly extend
@@ -0,0 +1,72 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation, when applied to a member method or field in a mixin,
* indicates that the member <b>should never</b> overwrite a matching membver in
* the target class. This indicates that the member differs from the normal
* "overlay-like" behaviour of mixins in general, and should only ever be
* <em>added</em> to the target. For public fields, the annotation has no
* effect.
*
* <p>Typical usage of this annotation would be to decorate a utility method in
* a mixin, or mark an interface-implementing method which must not overwrite a
* target if it exists (consider appropriate use of {@link Intrinsic} in these
* situations).</p>
*
* <p>Because of the mixed usage, this annotation has different implications for
* methods with differing visibility:</p>
*
* <dl>
* <dt>public methods</dt>
* <dd>public methods marked with this annotation are <b>discarded</b> if a
* matching target exists. A <tt>warning</tt>-level message is generated.</dd>
* <dt>private and protected methods</dt>
* <dd>non-public methods are <b>renamed</b> if a matching target method is
* found, this allows utility methods to be safely assigned meaningful names
* in code, but renamed if a conflict occurs when a mixin is applied.</dd>
* </dl>
*
* <p><strong>Notes</strong></p>
*
* <ul>
* <li>To mark all methods in a mixin as unique, apply the annotation to the
* mixin itself</li>
* <li>Uniqueness can be defined on a per-interface basis by using an
* {@link Implements} annotation with <tt>unique</tt> set to <tt>true</tt>
* </li>
* </ul>
*/
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Unique {
}
@@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Provides a token value into the attached environment
*/
@@ -26,6 +26,8 @@ package org.spongepowered.asm.mixin.extensibility;
import java.util.Set;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Interface for loaded mixin configurations
*/
@@ -35,6 +37,13 @@ public interface IMixinConfig {
* Default priority for mixin configs and mixins
*/
public static final int DEFAULT_PRIORITY = 1000;
/**
* Get the parent environment of this config
*
* @return the parent environment
*/
public abstract MixinEnvironment getEnvironment();
/**
* Get the name of the file from which this configuration object was
@@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility;
import org.apache.logging.log4j.Level;
/**
* Interface for objects which want to perform custom behaviour when fatal mixin
* errors occur. For example displaying a user-friendly error message
@@ -52,8 +51,9 @@ public interface IMixinErrorHandler {
WARN(Level.WARN),
/**
* Throw a {@link org.spongepowered.asm.mixin.MixinApplyError} to halt
* further processing if possible
* Throw a
* {@link org.spongepowered.asm.mixin.throwables.MixinApplyError} to
* halt further processing if possible
*/
ERROR(Level.FATAL);
@@ -64,6 +64,33 @@ public interface IMixinErrorHandler {
}
}
/**
* Called when an error occurs whilst initialising a mixin config. This
* allows the plugin to display more user-friendly error messages if
* required.
*
* <p>By default, when a critical error occurs the mixin processor will
* raise a warning if the config is not marked as "required" and will throw
* an {@link Error} if it is. This behaviour can be altered by returning
* different values from this method.</p>
*
* <p>The original throwable which was caught is passed in via the <code>
* th</code> parameter and the default action is passed in to the <code>
* action</code> parameter. A plugin can choose to output a friendly message
* but leave the original behaviour intact (by returning <code>null</code>
* or returning <code>action</code> directly. Alternatively it may throw a
* different exception or error, or can reduce the severity of the error by
* returning a different {@link ErrorAction}.</p>
*
* @param config Config being prepared when the error occurred
* @param th Throwable which was caught
* @param mixin Mixin which was being applied at the time of the error
* @param action Default action
* @return null to perform the default action (or return action) or new
* action to take
*/
public abstract ErrorAction onPrepareError(IMixinConfig config, Throwable th, IMixinInfo mixin, ErrorAction action);
/**
* Called when an error occurs applying a mixin. This allows
* the plugin to display more user-friendly error messages if required.
@@ -88,6 +115,6 @@ public interface IMixinErrorHandler {
* @return null to perform the default action (or return action) or new
* action to take
*/
public abstract ErrorAction onError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action);
public abstract ErrorAction onApplyError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action);
}
@@ -29,6 +29,9 @@ import java.util.List;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
/**
* Interface for MixinInfo, used in extensibility API
*/
public interface IMixinInfo {
/**
@@ -102,4 +105,5 @@ public interface IMixinInfo {
* @return the phase
*/
public abstract Phase getPhase();
}
@@ -0,0 +1,84 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.extensibility;
/**
* Interface for remap chain participants
*/
public interface IRemapper {
/**
* Map method name to the new name. Subclasses can override.
*
* @param owner owner of the method.
* @param name name of the method.
* @param desc descriptor of the method.
* @return new name of the method
*/
public abstract String mapMethodName(String owner, String name, String desc);
/**
* Map field name to the new name. Subclasses can override.
*
* @param owner owner of the field.
* @param name name of the field
* @param desc descriptor of the field
* @return new name of the field.
*/
public abstract String mapFieldName(String owner, String name, String desc);
/**
* Map type name to the new name. Subclasses can override.
*
* @param typeName Class name to convert
* @return new name for the class
*/
public abstract String map(String typeName);
/**
* Convert a mapped type name back to the original obfuscated name
*
* @param typeName Class name to convert
* @return old name for the class
*/
public abstract String unmap(String typeName);
/**
* Convert a descriptor to remapped form
*
* @param desc descriptor to convert
* @return new descriptor
*/
public abstract String mapDesc(String desc);
/**
* Convert a descriptor back to the original obfuscated form
*
* @param desc descriptor to convert
* @return old descriptor
*/
public abstract String unmapDesc(String desc);
}
@@ -27,7 +27,6 @@ package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Indicates that a local capture injector should coerce top-level primitive
* types to covariant types.
@@ -0,0 +1,111 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annotation for specifying the injection point for an {@link ModifyConstant}
* injector. Leaving all values unset causes the injection point to match all
* constants with the same type as the {@link ModifyConstant} handler's return
* type.
*
* <p>To match a specific constant, specify the appropriate value for the
* appropriate argument. Specifying values of different types will cause an
* error to be raised by the injector.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Constant {
/**
* Causes this injector to match ACONST_NULL (null object) literals
*
* @return true to match <tt>null</tt>
*/
public boolean nullValue() default false;
/**
* Specify an integer constant to match, includes byte and short values
*
* @return integer value to match
*/
public int intValue() default 0;
/**
* Specify a float constant to match
*
* @return float value to match
*/
public float floatValue() default 0.0F;
/**
* Specify a long constant to match
*
* @return long value to match
*/
public long longValue() default 0L;
/**
* Specify a double constant to match
*
* @return double value to match
*/
public double doubleValue() default 0.0;
/**
* Specify a String constant to match
*
* @return string value to match
*/
public String stringValue() default "";
/**
* Specify a type literal to match
*
* @return type literal to match
*/
public Class<?> classValue() default Object.class;
/**
* Ordinal offset. Many InjectionPoints will return every opcode matching
* their criteria, specifying <em>ordinal</em> allows a particular opcode to
* be identified from the returned list. The default value of -1 does not
* alter the behaviour and returns all matching opcodes. Specifying a value
* of 0 or higher returns <em>only</em> the requested opcode (if one exists:
* for example specifying an ordinal of 4 when only 2 opcodes are matched by
* the InjectionPoint is not going to work particularly well!)
*
* @return ordinal value for supported InjectionPoint types
*/
public int ordinal() default -1;
/**
* @return true to enable verbose debug logging for this injection point
*/
public boolean log() default false;
}
@@ -0,0 +1,65 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be used on any injector callback to define a value for
* total required injections across multiple callbacks. Much like
* {@link Inject#require()} it can be used to treat an injection failure as a
* critical error, however the <tt>require</tt> value specified applies to all
* injectors in the group. This can be used, for example, for 'surrogate'
* injectors where multiple injectors exist but only one is expected to succeed.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface Group {
/**
* The name of the injector group, any string
*
* @return group name
*/
public String name() default "";
/**
* Minimum required injections for this injector group
*
* @return required min value
*/
public int min() default -1;
/**
* Maximum allowed injections for this injector group
*
* @return allowed max value
*/
public int max() default -1;
}
@@ -29,8 +29,12 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a callback (or
@@ -41,6 +45,15 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
/**
* The identifier for this injector, can be retrieved via the
* {@link CallbackInfo#getId} accessor. If not specified, the ID defaults to
* the target method name.
*
* @return the injector id to use
*/
public String id() default "";
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
@@ -111,7 +124,6 @@ public @interface Inject {
*/
public LocalCapture locals() default LocalCapture.NO_CAPTURE;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link Inject} methods since it is
@@ -128,4 +140,47 @@ public @interface Inject {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,262 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
/**
* Used to keep track of instruction nodes in a {@link Target} method which are
* targetted by various types of injector. This collection is populated during
* the first injector pass and allows injectors to keep track of their targets
* even when the target method is being manipulated by other injectors.
*/
public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
/**
* Never gonna give you up
*/
private static final long serialVersionUID = 1L;
/**
* A node targetted by one or more injectors. Using this wrapper allows
* injectors to be aware of when their target node is removed or replace by
* another injector. It also allows injectors to decorate certain nodes with
* custom metadata to allow arbitration between injectors to take place.
*/
public static class InjectionNode implements Comparable<InjectionNode> {
/**
* The original node targetted
*/
private final AbstractInsnNode originalTarget;
/**
* Initially set to the {@link #originalTarget}, if an injector removes
* or replaces this node then points to the current target. Can be null
* if the node is removed.
*/
private AbstractInsnNode currentTarget;
/**
* Injector decorations on this node
*/
private Map<Object, Object> decorations;
/**
* Create a new node wrapper for the specified target node
*
* @param node target node
*/
public InjectionNode(AbstractInsnNode node) {
this.currentTarget = this.originalTarget = node;
}
/**
* Get the original target of this node
*/
public AbstractInsnNode getOriginalTarget() {
return this.originalTarget;
}
/**
* Get the current target of this node, can be null if the node was
* replaced
*/
public AbstractInsnNode getCurrentTarget() {
return this.currentTarget;
}
/**
* Replace this node with the specified target
*
* @param target new node
*/
public InjectionNode replace(AbstractInsnNode target) {
this.currentTarget = target;
return this;
}
/**
* Remove the node
*/
public InjectionNode remove() {
this.currentTarget = null;
return this;
}
/**
* Checks whether the original or current target of this node match the
* specified node
*
* @param node node to check
* @return true if the supplied node matches either of this node's
* internal identities
*/
public boolean matches(AbstractInsnNode node) {
return this.originalTarget == node || this.currentTarget == node;
}
/**
* Get whether this node has been replaced
*/
public boolean isReplaced() {
return this.originalTarget != this.currentTarget;
}
/**
* Get whether this node has been removed
*/
public boolean isRemoved() {
return this.currentTarget == null;
}
/**
* Decorate this node with arbitrary metadata for injector arbitration
*
* @param key meta key
* @param value meta value
*/
public <K, V> InjectionNode decorate(K key, V value) {
if (this.decorations == null) {
this.decorations = new HashMap<Object, Object>();
}
this.decorations.put(key, value);
return this;
}
/**
* Get whether this node is decorated with the specified key
*
* @param key meta key
* @return true if the specified decoration exists
*/
public <K> boolean hasDecoration(K key) {
return this.decorations != null && this.decorations.get(key) != null;
}
/**
* Get the specified decoration
*
* @param key meta key
* @return decoration value or null if absent
*/
@SuppressWarnings("unchecked")
public <K, V> V getDecoration(K key) {
return (V) (this.decorations == null ? null : this.decorations.get(key));
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(InjectionNode other) {
return other == null ? Integer.MAX_VALUE : this.hashCode() - other.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget));
}
}
/**
* Add a tracked node to this collection if it does not already exist
*
* @param node Instruction node to add
* @return wrapper for the specified node
*/
public InjectionNode add(AbstractInsnNode node) {
InjectionNode injectionNode = this.get(node);
if (injectionNode == null) {
injectionNode = new InjectionNode(node);
this.add(injectionNode);
}
return injectionNode;
}
/**
* Get a tracked node from this collection if it already exists, returns
* null if the node is not tracked
*
* @param node instruction node
* @return wrapper node or null if not tracked
*/
public InjectionNode get(AbstractInsnNode node) {
for (InjectionNode injectionNode : this) {
if (injectionNode.matches(node)) {
return injectionNode;
}
}
return null;
}
/**
* Get whether this collection contains a mapping for the specified insn
*
* @param node instruction node to check
* @return true if a wrapper exists for the node
*/
public boolean contains(AbstractInsnNode node) {
return this.get(node) != null;
}
/**
* Replace the specified node with the new node, does not update the wrapper
* if no wrapper exists for <tt>oldNode</tt>
*
* @param oldNode node being replaced
* @param newNode node to replace with
*/
public void replace(AbstractInsnNode oldNode, AbstractInsnNode newNode) {
InjectionNode injectionNode = this.get(oldNode);
if (injectionNode != null) {
injectionNode.replace(newNode);
}
}
/**
* Mark the specified node as removed, does not update the wrapper if no
* wrapper exists
*
* @param node node being removed
*/
public void remove(AbstractInsnNode node) {
InjectionNode injectionNode = this.get(node);
if (injectionNode != null) {
injectionNode.remove();
}
}
}
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,9 +32,14 @@ import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.points.AfterInvoke;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
@@ -43,6 +49,7 @@ import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke;
import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint;
import org.spongepowered.asm.mixin.injection.points.MethodHead;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
@@ -143,12 +150,12 @@ public abstract class InjectionPoint {
super(points);
}
@SuppressWarnings("unchecked")
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
boolean found = false;
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayList<AbstractInsnNode>[] allNodes = new ArrayList[this.components.length];
ArrayList<AbstractInsnNode>[] allNodes = (ArrayList<AbstractInsnNode>[]) Array.newInstance(ArrayList.class, this.components.length);
for (int i = 0; i < this.components.length; i++) {
allNodes[i] = new ArrayList<AbstractInsnNode>();
@@ -308,12 +315,15 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, At at) {
return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) {
List<String> args = Arrays.asList(at.args());
return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode());
}
/**
@@ -322,11 +332,13 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param node {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, AnnotationNode node) {
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, AnnotationNode node) {
String at = ASMHelper.<String>getAnnotationValue(node, "value");
List<String> args = ASMHelper.<List<String>>getAnnotationValue(node, "args");
String target = ASMHelper.<String>getAnnotationValue(node, "target", "");
@@ -339,7 +351,7 @@ public abstract class InjectionPoint {
args = ImmutableList.<String>of();
}
return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode);
return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode);
}
/**
@@ -348,6 +360,8 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at Injection point specifier
* @param shift Shift type to apply
* @param by Amount of shift to apply for the BY shift type
@@ -358,9 +372,9 @@ public abstract class InjectionPoint {
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, String at, At.Shift shift, int by,
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by,
List<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode);
InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, ordinal, opcode);
InjectionPoint point = null;
if (BeforeFieldAccess.CODE.equals(at)) {
@@ -379,6 +393,12 @@ public abstract class InjectionPoint {
point = new MethodHead(data);
} else if (AfterInvoke.CODE.equals(at)) {
point = new AfterInvoke(data);
} else if (BeforeLoadLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (AfterStoreLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
@SuppressWarnings("unchecked") Class<? extends InjectionPoint> cls = (Class<? extends InjectionPoint>) Class.forName(at);
@@ -0,0 +1,274 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information store for injector groups
*/
public class InjectorGroupInfo {
/**
* Storage for injector groups
*/
public static final class Map extends HashMap<String, InjectorGroupInfo> {
private static final long serialVersionUID = 1L;
private static final InjectorGroupInfo NO_GROUP = new InjectorGroupInfo("NONE", true);
@Override
public InjectorGroupInfo get(Object key) {
return this.forName(key.toString());
}
/**
* Get group for the specified name, creates the group in this map if
* it does not already exist
*
* @param name Name of group to fetch
* @return Existing group or new group if none was previously declared
*/
public InjectorGroupInfo forName(String name) {
InjectorGroupInfo value = super.get(name);
if (value == null) {
value = new InjectorGroupInfo(name);
this.put(name, value);
}
return value;
}
/**
* Parse a group from the specified method, use the default group name
* if no group name is specified on the annotation
*
* @param method (Possibly) annotated method
* @param defaultGroup Default group name to use
* @return Group or NO_GROUP if no group
*/
public InjectorGroupInfo parseGroup(MethodNode method, String defaultGroup) {
return this.parseGroup(ASMHelper.getInvisibleAnnotation(method, Group.class), defaultGroup);
}
/**
* Parse a group from the specified annotation, use the default group
* name if no group name is specified on the annotation
*
* @param annotation Annotation or null
* @param defaultGroup Default group name to use
* @return Group or NO_GROUP if no group
*/
public InjectorGroupInfo parseGroup(AnnotationNode annotation, String defaultGroup) {
if (annotation == null) {
return InjectorGroupInfo.Map.NO_GROUP;
}
String name = ASMHelper.<String>getAnnotationValue(annotation, "name");
if (name == null || name.isEmpty()) {
name = defaultGroup;
}
InjectorGroupInfo groupInfo = this.forName(name);
Integer min = ASMHelper.<Integer>getAnnotationValue(annotation, "min");
if (min != null && min.intValue() != -1) {
groupInfo.setMinRequired(min.intValue());
}
Integer max = ASMHelper.<Integer>getAnnotationValue(annotation, "max");
if (max != null && max.intValue() != -1) {
groupInfo.setMaxAllowed(max.intValue());
}
return groupInfo;
}
/**
* Validate all groups in this collection
*
* @throws InjectionValidationException if validation fails
*/
public void validateAll() throws InjectionValidationException {
for (InjectorGroupInfo group : this.values()) {
group.validate();
}
}
}
/**
* Group name
*/
private final String name;
/**
* Members of this group
*/
private final List<InjectionInfo> members = new ArrayList<InjectionInfo>();
/**
* True if this is the default group
*/
private final boolean isDefault;
/**
* Number of callbacks we require injected across this group
*/
private int minCallbackCount = -1;
/**
* Maximum number of callbacks allowed across this group
*/
private int maxCallbackCount = Integer.MAX_VALUE;
public InjectorGroupInfo(String name) {
this(name, false);
}
InjectorGroupInfo(String name, boolean flag) {
this.name = name;
this.isDefault = flag;
}
@Override
public String toString() {
return String.format("@Group(name=%s, min=%d, max=%d)", this.getName(), this.getMinRequired(), this.getMaxAllowed());
}
public boolean isDefault() {
return this.isDefault;
}
public String getName() {
return this.name;
}
public int getMinRequired() {
return Math.max(this.minCallbackCount, 1);
}
public int getMaxAllowed() {
return Math.min(this.maxCallbackCount, Integer.MAX_VALUE);
}
/**
* Get all members of this group as a read-only collection
*
* @return read-only view of group members
*/
public Collection<InjectionInfo> getMembers() {
return Collections.unmodifiableCollection(this.members);
}
/**
* Set the required minimum value for this group. Since this is normally
* done on the first {@link Group} annotation it is considered a
* warning-level event if a later annotation sets a different value. The
* highest value specified on all annotations is always used.
*
* @param min new value for min required
*/
public void setMinRequired(int min) {
if (min < 1) {
throw new IllegalArgumentException("Cannot set zero or negative value for injector group min count. Attempted to set min="
+ min + " on " + this);
}
if (this.minCallbackCount > 0 && this.minCallbackCount != min) {
LogManager.getLogger("mixin").warn("Conflicting min value '{}' on @Group({}), previously specified {}", min, this.name,
this.minCallbackCount);
}
this.minCallbackCount = Math.max(this.minCallbackCount, min);
}
/**
* Set the required minimum value for this group. Since this is normally
* done on the first {@link Group} annotation it is considered a
* warning-level event if a later annotation sets a different value. The
* highest value specified on all annotations is always used.
*
* @param max new value for max allowed
*/
public void setMaxAllowed(int max) {
if (max < 1) {
throw new IllegalArgumentException("Cannot set zero or negative value for injector group max count. Attempted to set max="
+ max + " on " + this);
}
if (this.maxCallbackCount < Integer.MAX_VALUE && this.maxCallbackCount != max) {
LogManager.getLogger("mixin").warn("Conflicting max value '{}' on @Group({}), previously specified {}", max, this.name,
this.maxCallbackCount);
}
this.maxCallbackCount = Math.min(this.maxCallbackCount, max);
}
/**
* Add a new member to this group
*
* @param member injector to add
* @return fluent interface
*/
public InjectorGroupInfo add(InjectionInfo member) {
this.members.add(member);
return this;
}
/**
* Validate all members in this group
*
* @return fluent interface
* @throws InjectionValidationException if validation fails
*/
public InjectorGroupInfo validate() throws InjectionValidationException {
if (this.members.size() == 0) {
// I have no idea how we got here, but it's not an error :/
return this;
}
int total = 0;
for (InjectionInfo member : this.members) {
total += member.getInjectedCallbackCount();
}
int min = this.getMinRequired();
int max = this.getMaxAllowed();
if (total < min) {
throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total));
} else if (total > max) {
throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total));
}
return this;
}
}
@@ -29,6 +29,11 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject an argument modifier to itself
* in the target method(s) identified by {@link #method}.
@@ -86,4 +91,47 @@ public @interface ModifyArg {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,135 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a constant modifier callback
* to itself in the target method(s) identified by {@link #method} at the
* specified LDC (or specialised const opcode) instruction in order to adjust
* the constant value returned.
*
* <p><tt>ModifyConstant</tt> callbacks should always take one argument of the
* appropriate constant type and return the same type. For example a
* <tt>ModifyConstant </tt> for a local of type {@link String} should have the
* signature:</p>
*
* <code>private String methodName(String variable) { ...</code>
*
* <p>The callback receives the original value of the constant, and should
* return the new value.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifyConstant {
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
* MemberInfo} which identifies the target method.
*
* @return method to inject into
*/
public String method();
/**
* Discriminator for the constant to match (injection point), if not
* specified then all constants matching the annotated handler's return type
* are matched
*
* @return the constant discriminator
*/
public Constant constant() default @Constant;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link ModifyConstant} methods since it is
* anticipated that in general the target of a {@link ModifyConstant}
* annotation will be an obfuscated method in the target class. However
* since it is possible to also apply mixins to non-obfuscated targets (or
* non- obfuscated methods in obfuscated targets, such as methods added by
* Forge) it may be necessary to suppress the compiler error which would
* otherwise be generated. Setting this value to <em>false</em> will cause
* the annotation processor to skip this annotation when attempting to build
* the obfuscation table for the mixin.
*
* @return True to instruct the annotation processor to search for
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,198 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a variable modifier callback
* to itself in the target method(s) identified by {@link #method}.
*
* <p><tt>ModifyVariable</tt> callbacks should always take one argument of the
* type to capture and return the same type. For example a <tt>ModifyVariable
* </tt> for a local of type {@link String} should have the signature:</p>
*
* <code>private String methodName(String variable) { ...</code>
*
* <p>The callback receives the current value of the local variable, and should
* return the new value.</p>
*
* <p>The injector has two operating modes, <em>explicit</em> and <em>implicit
* </em>, and can operate either on the entire LVT or on the method arguments
* only</p>.
*
* <p>In <em>explicit</em> mode, the variable to capture can be specified by
* specifying values for the discriminator arguments {@link #ordinal},
* {@link #index} and {@link #name}. The injector uses the discriminators in
* order to attempt to locate the variable to capture. If no local variable
* matches any discriminators, the capture fails.</p>
*
* <p>If no values for the capture discrimiators are specified, the injector
* operates in <em>implicit</em> mode. If exactly one variable of the capture
* type exists in the target LVT, then capture will succeed. However, if more
* than one variable of the required type is encountered in the LVT then an
* {@link InvalidInjectionException} is thrown.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifyVariable {
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
* MemberInfo} which identifies the target method.
*
* @return target method
*/
public String method();
/**
* An {@link At} annotation which describes the {@link InjectionPoint} in
* the target method. The specified {@link InjectionPoint} <i>must only</i>
* return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances
* and an exception will be thrown if this is not the case.
*
* @return {@link At} which identifies the target method invocation
*/
public At at();
/**
* When creating a {@link ModifyVariable} callback, you may wish to first
* inspect the local variable table in the target method at the injection
* point. Set this value to <tt>true</tt> to print the local variable table
* and perform no injection.
*
* @return true to print the LVT to the console
*/
public boolean print() default false;
/**
* Gets the local variable ordinal by type. For example, if there are 3
* {@link String} arguments in the local variable table, ordinal 0 specifies
* the first, 1 specifies the second, etc. Use <tt>ordinal</tt> when the
* index within the LVT is known. Takes precedence over {@link #index}.
*
* @return variable ordinal
*/
public int ordinal() default -1;
/**
* Gets the absolute index of the local variable within the local variable
* table to capture. The local variable at the specified index must be of
* the same type as the capture. Takes precedence over {@link #name}.
*
* @return argument index to modify or -1 for automatic
*/
public int index() default -1;
/**
* Gets the name of the variable to capture. Only used if the variable
* cannot be located via {@link #ordinal} or {@link #index}.
*
* @return possible names to capture, only useful when the LVT in the target
* method is known to be complete.
*/
public String[] name() default {};
/**
* Under normal circumstances the injector will consider all local variables
* including method arguments and all other local variables. This involves
* reading (and possibly generating) the local variable table for the method
* which can have mixed results. Set this value to <tt>true</tt> to <i>only
* </i> consider method arguments.
*
* @return true if this injector should only consider method arguments and
* not all locals.
*/
public boolean argsOnly() default false;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link ModifyVariable} methods since it is
* anticipated that in general the target of a {@link ModifyVariable}
* annotation will be an obfuscated method in the target class. However
* since it is possible to also apply mixins to non-obfuscated targets (or
* non- obfuscated methods in obfuscated targets, such as methods added by
* Forge) it may be necessary to suppress the compiler error which would
* otherwise be generated. Setting this value to <em>false</em> will cause
* the annotation processor to skip this annotation when attempting to build
* the obfuscation table for the mixin.
*
* @return True to instruct the annotation processor to search for
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -29,9 +29,16 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* <p>Specifies that this mixin method should redirect the specified
* {@link #method} call to the method decorated with this annotation.</p>
* method call or field access to the method decorated with this annotation.</p>
*
* <h4>Method Redirect Mode</h4>
*
* <p>The handler method signature must match the hooked method precisely
* <b>but</b> prepended with an arg of the owning object's type to accept the
@@ -68,6 +75,42 @@ import java.lang.annotation.Target;
* <pre>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</pre>
* </blockquote>
*
* <h4>Field Access Redirect Mode</h4>
*
* <p>The handler method signature varies depending on whether the redirector is
* handling a field <b>write</b> (<tt>PUTFIELD</tt>, <tt>PUTSTATIC</tt>) or a
* field <b>read</b> (<tt>GETFIELD</tt>, <tt>GETSTATIC</tt>).</p>
*
* <table width="100%">
* <tr>
* <th>Operation (OPCODE)</th>
* <th>Handler signature</th>
* </tr>
* <tr>
* <td>Read static field (<tt>GETSTATIC</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue()</code></td>
* </tr>
* <tr>
* <td>Read instance field (<tt>GETFIELD</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue(<b>OwnerType</b>
* owner)</code></td>
* </tr>
* <tr>
* <td>Write static field (<tt>PUTSTATIC</tt>)</td>
* <td><code>private void setFieldValue(<b>FieldType</b> value)</code></td>
* </tr>
* <tr>
* <td>Write instance field (<tt>PUTFIELD</tt>)</td>
* <td><code>private void getFieldValue(<b>OwnerType</b>
* owner, <b>FieldType</b> value)</code></td>
* </tr>
* </table>
*
* <p>It is also possible to capture the arguments of the target method in
* addition to the arguments being passed to the method call (for example in
* the code above this would be the <em>someInt</em> and <em>someString</em>
* arguments) by appending the arguments to the method signature.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -108,4 +151,47 @@ public @interface Redirect {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to decorate surrogate injector methods. See
* {@link Inject#locals()} for information.
@@ -25,6 +25,8 @@
package org.spongepowered.asm.mixin.injection.callback;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.util.Constants;
/**
* CallbackInfo instances are passed to callbacks in order to provide
@@ -34,9 +36,6 @@ import org.spongepowered.asm.lib.Type;
*/
public class CallbackInfo implements Cancellable {
protected static final String STRING = "Ljava/lang/String;";
protected static final String OBJECT = "Ljava/lang/Object;";
/**
* Method name being injected into, this is useful if a single callback is
* injecting into multiple methods.
@@ -65,11 +64,13 @@ public class CallbackInfo implements Cancellable {
}
/**
* Get the method name where this callback originated
* Get the ID of the injector which defined this callback. This defaults to
* the method name but can be overridden by specifying the {@link Inject#id}
* parameter on the injector
*
* @return the name of the calling method
* @return the injector ID
*/
public String getName() {
public String getId() {
return this.name;
}
@@ -118,15 +119,15 @@ public class CallbackInfo implements Cancellable {
return CallbackInfo.getConstructorDescriptor();
}
if (returnType.getSort() == Type.OBJECT) {
return String.format("(%sZ%s)V", CallbackInfo.STRING, CallbackInfo.OBJECT);
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return String.format("(%sZ%s)V", Constants.STRING, Constants.OBJECT);
}
return String.format("(%sZ%s)V", CallbackInfo.STRING, returnType.getDescriptor());
return String.format("(%sZ%s)V", Constants.STRING, returnType.getDescriptor());
}
static String getConstructorDescriptor() {
return String.format("(%sZ)V", CallbackInfo.STRING);
return String.format("(%sZ)V", Constants.STRING);
}
static String getIsCancelledMethodName() {
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.injection.callback;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.util.Constants;
/**
* For callbacks with a non-void return type, a CallbackInfoReturnable is passed
@@ -124,7 +125,7 @@ public class CallbackInfoReturnable<R> extends CallbackInfo {
// CHECKSTYLE:ON
static String getReturnAccessor(Type returnType) {
if (returnType.getSort() == Type.OBJECT) {
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return "getReturnValue";
}
@@ -132,8 +133,8 @@ public class CallbackInfoReturnable<R> extends CallbackInfo {
}
static String getReturnDescriptor(Type returnType) {
if (returnType.getSort() == Type.OBJECT) {
return String.format("()%s", CallbackInfo.OBJECT);
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return String.format("()%s", Constants.OBJECT);
}
return String.format("()%s", returnType.getDescriptor());
@@ -27,26 +27,27 @@ package org.spongepowered.asm.mixin.injection.callback;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.InjectionError;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.points.BeforeReturn;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Strings;
/**
* This class is responsible for generating the bytecode for injected callbacks
*/
@@ -148,10 +149,10 @@ public class CallbackInjector extends Injector {
*/
private boolean captureArgs = true;
Callback(MethodNode handler, Target target, final AbstractInsnNode node, final LocalVariableNode[] locals, boolean captureLocals) {
Callback(MethodNode handler, Target target, final InjectionNode node, final LocalVariableNode[] locals, boolean captureLocals) {
this.handler = handler;
this.target = target;
this.node = node;
this.node = node.getCurrentTarget();
this.locals = locals;
this.localTypes = locals != null ? new Type[locals.length] : null;
this.frameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic());
@@ -260,7 +261,7 @@ public class CallbackInjector extends Injector {
return false; // No @Coerce specified, types must match
}
boolean canCoerce = CallbackInjector.canCoerce(inTypes[arg], myTypes[arg]);
boolean canCoerce = Injector.canCoerce(inTypes[arg], myTypes[arg]);
if (!canCoerce) {
return false; // Can't coerce source type to local type, give up
}
@@ -277,8 +278,6 @@ public class CallbackInjector extends Injector {
}
}
private final Logger logger = LogManager.getLogger("mixin");
/**
* True if cancellable
*/
@@ -289,6 +288,11 @@ public class CallbackInjector extends Injector {
*/
private final LocalCapture localCapture;
/**
* ID to return from callbackinfo
*/
private final String identifier;
/**
* Make a new CallbackInjector with the supplied args
*
@@ -297,10 +301,11 @@ public class CallbackInjector extends Injector {
* be cancellable
* @param localCapture Local variable capture behaviour
*/
public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture) {
public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture, String identifier) {
super(info);
this.cancellable = cancellable;
this.localCapture = localCapture;
this.identifier = identifier;
}
/* (non-Javadoc)
@@ -310,15 +315,17 @@ public class CallbackInjector extends Injector {
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
if (ASMHelper.methodIsStatic(target.method) != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name);
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this);
}
if (Constants.INIT.equals(target.method.name)) {
if (Constants.CTOR.equals(target.method.name)) {
for (InjectionPoint injectionPoint : injectionPoints) {
if (!injectionPoint.getClass().equals(BeforeReturn.class)) {
throw new InvalidInjectionException(this.info, "Found injection point type " + injectionPoint.getClass().getSimpleName()
+ " targetting a ctor in " + this.classNode.name + ". Only RETURN allowed for a ctor target");
+ " targetting a ctor in " + this + ". Only RETURN allowed for a ctor target");
}
}
}
@@ -330,11 +337,11 @@ public class CallbackInjector extends Injector {
* org.objectweb.asm.tree.AbstractInsnNode)
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
protected void inject(Target target, InjectionNode node) {
LocalVariableNode[] locals = null;
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
locals = Locals.getLocalsAt(this.classNode, target.method, node);
locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
}
this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals()));
@@ -357,7 +364,7 @@ public class CallbackInjector extends Injector {
MethodNode callbackMethod = this.methodNode;
if (!callback.checkDescriptor(this.methodNode.desc)) {
if (this.info.getTargets().size() != 0) {
if (this.info.getTargets().size() > 1) {
return; // Look for a match in other targets before failing
}
@@ -367,24 +374,24 @@ public class CallbackInjector extends Injector {
// signature for the current locals. This allows silent failover
// if changes to the local variable table are EXPECTED for some
// reason.
MethodNode handler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (handler != null && ASMHelper.getVisibleAnnotation(handler, Surrogate.class) != null) {
MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) {
// Found a matching method, use it
callbackMethod = handler;
callbackMethod = surrogateHandler;
} else {
// No matching method, generate a message to bitch about it
String message = this.generateBadLVTMessage(callback);
switch (this.localCapture) {
case CAPTURE_FAILEXCEPTION:
this.logger.error("Injection error: {}", message);
Injector.logger.error("Injection error: {}", message);
callbackMethod = this.generateErrorMethod(callback, "org/spongepowered/asm/mixin/injection/InjectionError", message);
break;
case CAPTURE_FAILSOFT:
this.logger.warn("Injection warning: {}", message);
Injector.logger.warn("Injection warning: {}", message);
return;
default:
this.logger.error("Critical injection failure: {}", message);
Injector.logger.error("Critical injection failure: {}", message);
throw new InjectionError(message);
}
}
@@ -397,20 +404,29 @@ public class CallbackInjector extends Injector {
if (callback.checkDescriptor(returnableSig)) {
// Switching out CallbackInfo for CallbackInfoReturnable
// worked, so notify the user that they done derped
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: CallbackInfoReturnable is required!");
throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! CallbackInfoReturnable is required!");
}
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: expected " + callback.getDescriptor()
+ " but found " + this.methodNode.desc);
MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) {
// Found a matching surrogate method, use it
callbackMethod = surrogateHandler;
} else {
throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! Expected " + callback.getDescriptor()
+ " but found " + this.methodNode.desc);
}
}
}
this.createCallbackInfo(callback);
this.dupReturnValue(callback);
if (this.cancellable) {
this.createCallbackInfo(callback, true);
}
this.invokeCallback(callback, callbackMethod);
this.injectCancellationCode(callback);
callback.inject();
this.info.getTargets().clear();
this.info.notifyInjected(callback.target);
}
/**
@@ -422,9 +438,9 @@ public class CallbackInjector extends Injector {
private String generateBadLVTMessage(final Callback callback) {
int position = callback.target.method.instructions.indexOf(callback.node);
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(callback.localTypes, callback.frameSize);
String message = String.format("LVT in %s::%s has incompatible changes at opcode %d in callback %s%s.\nExpected: %s\n Found:%s",
this.classNode.name, callback.target.method.name, position, this.methodNode.name, this.methodNode.desc, expected, found);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.frameSize);
String message = String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s",
callback.target, position, this, expected, found);
return message;
}
@@ -444,7 +460,7 @@ public class CallbackInjector extends Injector {
insns.add(new TypeInsnNode(Opcodes.NEW, errorClass));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(message));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.INIT, "(Ljava/lang/String;)V", false));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.CTOR, "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
return method;
}
@@ -461,12 +477,12 @@ public class CallbackInjector extends Injector {
handlerSig.setModifiers(this.methodNode);
PrettyPrinter printer = new PrettyPrinter();
printer.add("%20s : %s", "Target Class", this.classNode.name.replace('/', '.'));
printer.add("%20s : %s", "Target Method", methodSig);
printer.add("%20s : %d", "Target Max LOCALS", callback.target.getMaxLocals());
printer.add("%20s : %d", "Initial Frame Size", callback.frameSize);
printer.add("%20s : %s", "Callback Name", this.methodNode.name);
printer.add("%20s : %s %s", "Instruction", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode()));
printer.kv("Target Class", this.classNode.name.replace('/', '.'));
printer.kv("Target Method", methodSig);
printer.kv("Target Max LOCALS", callback.target.getMaxLocals());
printer.kv("Initial Frame Size", callback.frameSize);
printer.kv("Callback Name", this.methodNode.name);
printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode()));
printer.hr();
if (callback.locals.length > callback.frameSize) {
printer.add(" %s %20s %s", "LOCAL", "TYPE", "NAME");
@@ -489,15 +505,27 @@ public class CallbackInjector extends Injector {
/**
* @param callback callback handle
* @param store store the callback info in a local variable
*/
private void createCallbackInfo(final Callback callback) {
this.dupReturnValue(callback);
callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, false);
private void createCallbackInfo(final Callback callback, boolean store) {
callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, !store);
callback.add(new InsnNode(Opcodes.DUP), true, true);
this.invokeCallbackInfoCtor(callback);
callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar));
this.invokeCallbackInfoCtor(callback, store);
if (store) {
callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar));
}
}
/**
* @param callback callback handle
*/
private void loadOrCreateCallbackInfo(final Callback callback) {
if (this.cancellable) {
callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true);
} else {
this.createCallbackInfo(callback, false);
}
}
/**
@@ -519,18 +547,20 @@ public class CallbackInjector extends Injector {
/**
* @param callback callback handle
* @param store true if storing in a local, false if this is happening at an
* invoke
*/
protected void invokeCallbackInfoCtor(final Callback callback) {
callback.add(new LdcInsnNode(callback.target.method.name), true, false);
callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, false);
protected void invokeCallbackInfoCtor(final Callback callback, boolean store) {
callback.add(new LdcInsnNode(this.getIdentifier(callback)), true, !store);
callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, !store);
if (callback.isAtReturn) {
callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar));
callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar), true, !store);
callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false));
callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false));
} else {
callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(), false));
callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(), false));
}
}
@@ -540,7 +570,7 @@ public class CallbackInjector extends Injector {
private void invokeCallback(final Callback callback, final MethodNode callbackMethod) {
// Push "this" onto the stack if the callback is not static
if (!this.isStatic) {
callback.add(new VarInsnNode(Opcodes.ALOAD, 0));
callback.add(new VarInsnNode(Opcodes.ALOAD, 0), false, true);
}
// Push the target method's parameters onto the stack
@@ -549,7 +579,7 @@ public class CallbackInjector extends Injector {
}
// Push the callback info onto the stack
callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true);
this.loadOrCreateCallbackInfo(callback);
// (Maybe) push the locals onto the stack
if (callback.canCaptureLocals) {
@@ -557,7 +587,19 @@ public class CallbackInjector extends Injector {
}
// Call the callback!
this.invokeMethod(callback, callbackMethod);
this.invokeHandler(callback, callbackMethod);
}
/**
* Get the identifier to use for the specified callback. If an id was
* specified by the end user on the annotation then use the value specified,
* otherwise defaults to the target method name.
*
* @param callback Callback being injected
* @return Identifier to use
*/
private String getIdentifier(Callback callback) {
return Strings.isNullOrEmpty(this.identifier) ? callback.target.method.name : this.identifier;
}
/**
@@ -631,21 +673,5 @@ public class CallbackInjector extends Injector {
}
return list;
}
public static boolean canCoerce(Type from, Type to) {
return CallbackInjector.canCoerce(from.getDescriptor(), to.getDescriptor());
}
public static boolean canCoerce(String from, String to) {
if (from.length() > 1 || to.length() > 1) {
return false;
}
return CallbackInjector.canCoerce(from.charAt(0), to.charAt(0));
}
public static boolean canCoerce(char from, char to) {
return to == 'I' && "IBSCZ".indexOf(from) > -1;
}
}
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Interface for things which can be cancelled
*/
@@ -24,6 +24,10 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Exception thrown when a consumer attemtps to call <tt>cancel()</tt> on a
* callback not marked as <tt>cancellable</tt>.
*/
public class CancellationException extends RuntimeException {
private static final long serialVersionUID = 1L;
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Specifies the behaviour for capturing local variables at an injection point.
*
@@ -30,6 +30,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
@@ -37,19 +39,26 @@ import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
/**
* Base class for bytecode injectors
*/
public abstract class Injector {
/**
* Log more things
*/
protected static final Logger logger = LogManager.getLogger("mixin");
/**
* Injection info
*/
@@ -64,6 +73,16 @@ public abstract class Injector {
* Callback method
*/
protected final MethodNode methodNode;
/**
* Arguments of the handler method
*/
protected final Type[] methodArgs;
/**
* Return type of the handler method
*/
protected final Type returnType;
/**
* True if the callback method is static
@@ -89,20 +108,46 @@ public abstract class Injector {
private Injector(ClassNode classNode, MethodNode methodNode) {
this.classNode = classNode;
this.methodNode = methodNode;
this.methodArgs = Type.getArgumentTypes(this.methodNode.desc);
this.returnType = Type.getReturnType(this.methodNode.desc);
this.isStatic = ASMHelper.methodIsStatic(this.methodNode);
}
@Override
public String toString() {
return String.format("%s::%s", this.classNode.name, this.methodNode.name);
}
/**
* Inject into the specified method at the specified injection points
* ...
*
* @param target Target method to inject into
* @param injectionPoints InjectionPoint instances which will identify
* target insns in the target method
* @return discovered injection points
*/
public final void injectInto(Target target, List<InjectionPoint> injectionPoints) {
public final List<InjectionNode> find(Target target, List<InjectionPoint> injectionPoints) {
this.sanityCheck(target, injectionPoints);
List<InjectionNode> myNodes = new ArrayList<InjectionNode>();
for (AbstractInsnNode node : this.findTargetNodes(target.method, injectionPoints)) {
this.addTargetNode(target, myNodes, node);
}
return myNodes;
}
protected void addTargetNode(Target target, List<InjectionNode> myNodes, AbstractInsnNode node) {
myNodes.add(target.injectionNodes.add(node));
}
public final void inject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
if (node.isRemoved()) {
if (this.info.getContext().getEnvironment().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target);
}
continue;
}
this.inject(target, node);
}
}
@@ -125,7 +170,7 @@ public abstract class Injector {
for (InjectionPoint injectionPoint : injectionPoints) {
nodes.clear();
if (injectionPoint.find(into.desc, insns, nodes)) {
if (this.findTargetNodes(into, injectionPoint, insns, nodes)) {
targetNodes.addAll(nodes);
}
}
@@ -134,28 +179,63 @@ public abstract class Injector {
return targetNodes;
}
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
// stub for subclasses
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, insns, nodes);
}
protected abstract void inject(Target target, AbstractInsnNode node);
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
if (target.classNode != this.classNode) {
throw new InvalidInjectionException(this.info, "Target class does not match injector class in " + this);
}
}
protected abstract void inject(Target target, InjectionNode node);
/**
* Invoke the handler method
*
* @param insns Instruction list to inject into
* @return injected insn node
*/
protected void invokeHandler(InsnList insns) {
this.invokeMethod(insns, this.methodNode);
protected AbstractInsnNode invokeHandler(InsnList insns) {
return this.invokeHandler(insns, this.methodNode);
}
protected void invokeMethod(InsnList insns, MethodNode methodNode) {
boolean isPrivate = (methodNode.access & Opcodes.ACC_PRIVATE) != 0;
/**
* Invoke a handler method
*
* @param insns Instruction list to inject into
* @param handler Actual method to invoke (may be different if using a
* surrogate)
* @return injected insn node
*/
protected AbstractInsnNode invokeHandler(InsnList insns, MethodNode handler) {
boolean isPrivate = (handler.access & Opcodes.ACC_PRIVATE) != 0;
int invokeOpcode = this.isStatic ? Opcodes.INVOKESTATIC : isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL;
insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, methodNode.name, methodNode.desc, false));
MethodInsnNode insn = new MethodInsnNode(invokeOpcode, this.classNode.name, handler.name, handler.desc, false);
insns.add(insn);
this.info.addCallbackInvocation(handler);
return insn;
}
protected static String printArgs(Type[] args) {
return "(" + Joiner.on("").join(args) + ")";
}
public static boolean canCoerce(Type from, Type to) {
return Injector.canCoerce(from.getDescriptor(), to.getDescriptor());
}
public static boolean canCoerce(String from, String to) {
if (from.length() > 1 || to.length() > 1) {
return false;
}
return Injector.canCoerce(from.charAt(0), to.charAt(0));
}
public static boolean canCoerce(char from, char to) {
return to == 'I' && "IBSCZ".indexOf(from) > -1;
}
}
@@ -32,27 +32,18 @@ import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
/**
* Base class for injectors which inject at method invokes
*/
public abstract class InvokeInjector extends Injector {
/**
* Arguments of the handler method
*/
protected final Type[] methodArgs;
/**
* Return type of the handler method
*/
protected final Type returnType;
protected final String annotationType;
/**
@@ -61,8 +52,6 @@ public abstract class InvokeInjector extends Injector {
*/
public InvokeInjector(InjectionInfo info, String annotationType) {
super(info);
this.methodArgs = Type.getArgumentTypes(this.methodNode.desc);
this.returnType = Type.getReturnType(this.methodNode.desc);
this.annotationType = annotationType;
}
@@ -73,8 +62,18 @@ public abstract class InvokeInjector extends Injector {
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
this.checkTarget(target);
}
/**
* Sanity checks on target
*
* @param target target
*/
protected void checkTarget(Target target) {
if (target.isStatic != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name);
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this);
}
}
@@ -84,13 +83,13 @@ public abstract class InvokeInjector extends Injector {
* org.objectweb.asm.tree.AbstractInsnNode)
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
if (!(node instanceof MethodInsnNode)) {
throw new InvalidInjectionException(this.info, this.annotationType + " annotation is targetting a non-method insn in " + target
+ " in " + this.classNode.name);
protected void inject(Target target, InjectionNode node) {
if (!(node.getCurrentTarget() instanceof MethodInsnNode)) {
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting a non-method insn in " + target
+ " in " + this);
}
this.inject(target, (MethodInsnNode)node);
this.injectAtInvoke(target, node);
}
/**
@@ -99,15 +98,16 @@ public abstract class InvokeInjector extends Injector {
* @param target Target to inject into
* @param node Discovered instruction node
*/
protected abstract void inject(Target target, MethodInsnNode node);
protected abstract void injectAtInvoke(Target target, InjectionNode node);
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @return injected insn node
*/
protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
}
/**
@@ -116,13 +116,14 @@ public abstract class InvokeInjector extends Injector {
* @param argMap Mapping of args to local variables
* @param startArg Starting arg to consume
* @param endArg Ending arg to consume
* @return injected insn node
*/
protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
this.pushArgs(args, insns, argMap, startArg, endArg);
this.invokeHandler(insns);
return this.invokeHandler(insns);
}
/**
@@ -31,10 +31,11 @@ import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
/**
* A bytecode injector which allows a single argument of a chosen method call to
@@ -76,18 +77,30 @@ public class ModifyArgInjector extends InvokeInjector {
if (this.singleArgMode) {
if (!this.methodArgs[0].equals(this.returnType)) {
throw new InvalidInjectionException(this.info, "@ModifyArg return type must match the parameter type."
throw new InvalidInjectionException(this.info, "@ModifyArg return type on " + this + " must match the parameter type."
+ " ARG=" + this.methodArgs[0] + " RETURN=" + this.returnType);
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.invoke.InvokeInjector
* #checkTarget(org.spongepowered.asm.mixin.injection.struct.Target)
*/
@Override
protected void checkTarget(Target target) {
if (!this.isStatic && target.isStatic) {
throw new InvalidInjectionException(this.info, "non-static callback method " + this + " targets a static method which is not supported");
}
}
/**
* Do the injection
*/
@Override
protected void inject(Target target, MethodInsnNode node) {
Type[] args = Type.getArgumentTypes(node.desc);
protected void injectAtInvoke(Target target, InjectionNode node) {
MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget();
Type[] args = Type.getArgumentTypes(methodNode.desc);
int argIndex = this.findArgIndex(target, args);
InsnList insns = new InsnList();
int extraLocals = 0;
@@ -98,7 +111,7 @@ public class ModifyArgInjector extends InvokeInjector {
extraLocals = this.injectMultiArgHandler(target, args, argIndex, insns);
}
target.insns.insertBefore(node, insns);
target.insns.insertBefore(methodNode, insns);
target.addToLocals(extraLocals);
target.addToStack(2 - (extraLocals - 1));
}
@@ -110,7 +123,7 @@ public class ModifyArgInjector extends InvokeInjector {
int[] argMap = this.storeArgs(target, args, insns, argIndex);
this.invokeHandlerWithArgs(args, insns, argMap, argIndex, argIndex + 1);
this.pushArgs(args, insns, argMap, argIndex + 1, args.length);
return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize();
return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize();
}
/**
@@ -118,7 +131,7 @@ public class ModifyArgInjector extends InvokeInjector {
*/
private int injectMultiArgHandler(Target target, Type[] args, int argIndex, InsnList insns) {
if (!Arrays.equals(args, this.methodArgs)) {
throw new InvalidInjectionException(this.info, "@ModifyArg method targets a method with an invalid signature "
throw new InvalidInjectionException(this.info, "@ModifyArg method " + this + " targets a method with an invalid signature "
+ Injector.printArgs(args) + ", expected " + Injector.printArgs(this.methodArgs));
}
@@ -126,14 +139,14 @@ public class ModifyArgInjector extends InvokeInjector {
this.pushArgs(args, insns, argMap, 0, argIndex);
this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
this.pushArgs(args, insns, argMap, argIndex + 1, args.length);
return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize();
return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize();
}
protected int findArgIndex(Target target, Type[] args) {
if (this.index > -1) {
if (this.index >= args.length || !args[this.index].equals(this.returnType)) {
throw new InvalidInjectionException(this.info, "Specified index " + this.index + " for @ModifyArg is invalid for args "
+ Injector.printArgs(args) + ", expected " + this.returnType);
+ Injector.printArgs(args) + ", expected " + this.returnType + " on " + this);
}
return this.index;
}
@@ -147,8 +160,7 @@ public class ModifyArgInjector extends InvokeInjector {
if (argIndex != -1) {
throw new InvalidInjectionException(this.info, "Found duplicate args with index [" + argIndex + ", " + arg + "] matching type "
+ this.returnType + " for @ModifyArg target " + target + " in " + this.classNode.name
+ ". Please specify index of desired arg.");
+ this.returnType + " for @ModifyArg target " + target + " in " + this + ". Please specify index of desired arg.");
}
argIndex = arg;
@@ -156,7 +168,7 @@ public class ModifyArgInjector extends InvokeInjector {
if (argIndex == -1) {
throw new InvalidInjectionException(this.info, "Could not find arg matching type " + this.returnType + " for @ModifyArg target "
+ target + " in " + this.classNode.name);
+ target + " in " + this);
}
return argIndex;
@@ -0,0 +1,94 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.invoke;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
/**
* A bytecode injector which allows a specific
*/
public class ModifyConstantInjector extends RedirectInjector {
/**
* @param info Injection info
*/
public ModifyConstantInjector(InjectionInfo info) {
super(info, "@ModifyConstant");
}
@Override
protected void inject(Target target, InjectionNode node) {
if (!this.preInject(node)) {
return;
}
if (node.isReplaced()) {
throw new UnsupportedOperationException("Target failure for " + this.info);
}
if (ASMHelper.isConstant(node.getCurrentTarget())) {
this.injectConstantModifier(target, node);
return;
}
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in "
+ target + " in " + this);
}
private void injectConstantModifier(Target target, InjectionNode node) {
final AbstractInsnNode constNode = node.getCurrentTarget();
final Type constantType = ASMHelper.getConstantType(constNode);
final InsnList before = new InsnList();
final InsnList after = new InsnList();
AbstractInsnNode invoke = this.invokeConstantHandler(constNode, constantType, target, before, after);
target.wrapNode(constNode, invoke, before, after);
}
private AbstractInsnNode invokeConstantHandler(AbstractInsnNode targetNode, Type constantType, Target target, InsnList before, InsnList after) {
final String handlerDesc = ASMHelper.generateDescriptor(constantType, constantType);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
if (!this.isStatic) {
before.add(new VarInsnNode(Opcodes.ALOAD, 0));
target.addToStack(1);
}
if (withArgs) {
this.pushArgs(target.arguments, after, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
return this.invokeHandler(after);
}
}
@@ -24,25 +24,36 @@
*/
package org.spongepowered.asm.mixin.injection.invoke;
import java.util.List;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.ObjectArrays;
import com.google.common.primitives.Ints;
/**
* <p>A bytecode injector which allows a method call to be redirected to the
* annotated handler method. The handler method signature must match the hooked
* method precisely <b>but</b> prepended with an arg of the owning object's type
* to accept the object instance the method was going to be invoked on. For
* example when hooking the following call:</p>
* <p>A bytecode injector which allows a method call or field access to be
* redirected to the annotated handler method. For method redirects, the handler
* method signature must match the hooked method precisely <b>but</b> prepended
* with an arg of the owning object's type to accept the object instance the
* method was going to be invoked on. For example when hooking the following
* call:</p>
*
* <blockquote><pre>
* int abc = 0;
@@ -62,27 +73,125 @@ import com.google.common.primitives.Ints;
* <p>For obvious reasons this does not apply for static methods, for static
* methods it is sufficient that the signature simply match the hooked method.
* </p>
*
* <p>For field redirections, see the details in {@link Redirect} for the
* required signature of the handler method.</p>
*/
public class RedirectInjector extends InvokeInjector {
/**
* Meta decoration object for redirector target nodes
*/
class Meta {
public static final String KEY = "redirector";
final int priority;
final boolean isFinal;
final String name;
final String desc;
public Meta(int priority, boolean isFinal, String name, String desc) {
this.priority = priority;
this.isFinal = isFinal;
this.name = name;
this.desc = desc;
}
RedirectInjector getOwner() {
return RedirectInjector.this;
}
}
protected Meta meta;
/**
* @param info Injection info
*/
public RedirectInjector(InjectionInfo info) {
super(info, "@Redirect");
this(info, "@Redirect");
}
protected RedirectInjector(InjectionInfo info, String annotationType) {
super(info, annotationType);
int priority = info.getContext().getPriority();
boolean isFinal = ASMHelper.getVisibleAnnotation(this.methodNode, Final.class) != null;
this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc);
}
@Override
protected void addTargetNode(Target target, List<InjectionNode> myNodes, AbstractInsnNode insn) {
InjectionNode node = target.injectionNodes.get(insn);
if (node != null ) {
Meta other = node.getDecoration(Meta.KEY);
if (other != null && other.getOwner() != this) {
if (other.priority >= this.meta.priority) {
Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}",
this.annotationType, this.info, this.meta.priority, other.name, other.priority);
return;
} else if (other.isFinal) {
throw new InvalidInjectionException(this.info, this.annotationType + " conflict: " + this
+ " failed because target was already remapped by " + other.name);
}
}
}
myNodes.add(target.injectionNodes.add(insn).decorate(Meta.KEY, this.meta));
}
@Override
protected void inject(Target target, InjectionNode node) {
if (!this.preInject(node)) {
return;
}
if (node.isReplaced()) {
throw new UnsupportedOperationException("Redirector target failure for " + this.info);
}
if (node.getCurrentTarget() instanceof MethodInsnNode) {
this.injectAtInvoke(target, node);
return;
}
if (node.getCurrentTarget() instanceof FieldInsnNode) {
this.injectAtFieldAccess(target, node);
return;
}
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in "
+ target + " in " + this);
}
protected boolean preInject(InjectionNode node) {
Meta other = node.getDecoration(Meta.KEY);
if (other.getOwner() != this) {
Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}",
this.annotationType, this.info, this.meta.priority, other.name, other.priority);
return false;
}
return true;
}
/**
* Do the injection
* Redirect a method invocation
*/
@Override
protected void inject(Target target, MethodInsnNode node) {
protected void injectAtInvoke(Target target, InjectionNode node) {
final MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget();
final boolean targetIsStatic = methodNode.getOpcode() == Opcodes.INVOKESTATIC;
final Type ownerType = Type.getType("L" + methodNode.owner + ";");
final Type returnType = Type.getReturnType(methodNode.desc);
final Type[] args = Type.getArgumentTypes(methodNode.desc);
final Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args);
boolean injectTargetParams = false;
boolean targetIsStatic = node.getOpcode() == Opcodes.INVOKESTATIC;
Type ownerType = Type.getType("L" + node.owner + ";");
Type returnType = Type.getReturnType(node.desc);
Type[] args = Type.getArgumentTypes(node.desc);
Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args);
String desc = Injector.printArgs(stackVars) + returnType;
if (!desc.equals(this.methodNode.desc)) {
@@ -90,23 +199,125 @@ public class RedirectInjector extends InvokeInjector {
if (alternateDesc.equals(this.methodNode.desc)) {
injectTargetParams = true;
} else {
throw new InvalidInjectionException(this.info, "@Redirect handler method has an invalid signature "
+ ", expected " + desc + " found " + this.methodNode.desc);
throw new InvalidInjectionException(this.info, this.annotationType + " handler method " + this
+ " has an invalid signature, expected " + desc + " found " + this.methodNode.desc);
}
}
InsnList insns = new InsnList();
int extraLocals = ASMHelper.getArgsSize(stackVars) + 1;
int extraStack = 1; // Normally only need 1 extra stack pos to store target ref
int[] argMap = this.storeArgs(target, stackVars, insns, 0);
if (injectTargetParams) {
extraLocals += ASMHelper.getArgsSize(target.arguments);
int argSize = ASMHelper.getArgsSize(target.arguments);
extraLocals += argSize;
extraStack += argSize;
argMap = Ints.concat(argMap, target.argIndices);
}
this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
target.insns.insertBefore(node, insns);
target.insns.remove(node);
AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
target.replaceNode(methodNode, insn, insns);
target.addToLocals(extraLocals);
target.addToStack(1);
target.addToStack(extraStack);
}
/**
* Redirect a field get or set operation
*/
private void injectAtFieldAccess(Target target, InjectionNode node) {
final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget();
final int opCode = fieldNode.getOpcode();
final boolean staticField = opCode == Opcodes.GETSTATIC || opCode == Opcodes.PUTSTATIC;
final Type ownerType = Type.getType("L" + fieldNode.owner + ";");
final Type fieldType = Type.getType(fieldNode.desc);
AbstractInsnNode invoke = null;
InsnList insns = new InsnList();
if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) {
invoke = this.injectAtGetField(insns, target, fieldNode, staticField, ownerType, fieldType);
} else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) {
invoke = this.injectAtPutField(insns, target, fieldNode, staticField, ownerType, fieldType);
} else {
throw new InvalidInjectionException(this.info, "Unspported opcode " + opCode + " on FieldInsnNode for " + this.info);
}
target.replaceNode(fieldNode, invoke, insns);
}
/**
* Inject opcodes to redirect a field getter. The injection will vary based
* on the staticness of the field and the handler thus there are four
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
final String handlerDesc = staticField ? ASMHelper.generateDescriptor(fieldType) : ASMHelper.generateDescriptor(fieldType, owner);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
if (!staticField) {
insns.add(new InsnNode(Opcodes.SWAP));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
target.addToStack(this.isStatic ? 0 : 1);
return this.invokeHandler(insns);
}
/**
* Inject opcodes to redirect a field setter. The injection will vary based
* on the staticness of the field and the handler thus there are four
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
String handlerDesc = staticField ? ASMHelper.generateDescriptor(null, fieldType) : ASMHelper.generateDescriptor(null, owner, fieldType);
boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter");
if (!this.isStatic) {
if (staticField) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
} else {
int marshallVar = target.allocateLocals(fieldType.getSize());
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar));
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
target.addToStack(!this.isStatic && !staticField ? 1 : 0);
return this.invokeHandler(insns);
}
/**
* Check that the handler descriptor matches the calculated descriptor for
* the field access being redirected.
*/
protected boolean checkDescriptor(String desc, Target target, String type) {
if (this.methodNode.desc.equals(desc)) {
return false;
}
int pos = desc.indexOf(')');
String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos));
if (this.methodNode.desc.equals(alternateDesc)) {
return true;
}
throw new InvalidInjectionException(this.info, this.annotationType + " method " + type + " " + this
+ " has an invalid signature. Expected " + desc + " but found " + this.methodNode.desc);
}
}
@@ -0,0 +1,81 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for STORE operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately after a
* local variable is written in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the STORE opcode for the matching local
* variable to search for, if not specified then the injection point returns
* <em>all </em> opcodes for which the parent annotation's discriminators
* match. The default value is <b>-1</b> which supresses ordinal checking.
* </dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "STORE",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("STORE")</pre>
* </blockquote>
*
* <p><b>Important Note:</b> Unlike other standard injection points, this class
* matches the insn immediately <b>after</b> the matching point.</p>
*/
public class AfterStoreLocal extends BeforeLoadLocal {
@SuppressWarnings("hiding")
public static final String CODE = "STORE";
public AfterStoreLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator local, InjectionPointData data) {
super(mixin, returnType, local, data, Opcodes.ISTORE, true);
}
}
@@ -0,0 +1,212 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.Collection;
import java.util.ListIterator;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for LOAD operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately before a
* local variable is accessed in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the LOAD opcode for the matching local variable
* to search for, if not specified then the injection point returns <em>all
* </em> opcodes for which the parent annotation's discriminators match. The
* default value is <b>-1</b> which supresses ordinal checking.</dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "LOAD",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("LOAD")</pre>
* </blockquote>
*/
public class BeforeLoadLocal extends ContextualInjectionPoint {
/**
* Keeps track of state within {@link #find}
*/
static class SearchState {
/**
* The target ordinal from the injection point
*/
private final int targetOrdinal;
/**
* The current ordinal
*/
private int ordinal = 0;
/**
* Flag to defer a {@link check} to the next opcode, to honour the after
* semantics of {@link AfterStoreLocal}.
*/
private boolean pendingCheck = false;
/**
* True if one or more opcodes was matched
*/
private boolean found = false;
/**
* Var node, captured for when deferring processing to the next opcode
*/
private VarInsnNode varNode;
SearchState(int targetOrdinal) {
this.targetOrdinal = targetOrdinal;
}
boolean success() {
return this.found;
}
boolean isPendingCheck() {
return this.pendingCheck;
}
void setPendingCheck() {
this.pendingCheck = true;
}
void register(VarInsnNode node) {
this.varNode = node;
}
void check(Collection<AbstractInsnNode> nodes, AbstractInsnNode insn, int local) {
this.pendingCheck = false;
if (local != this.varNode.var) {
return;
}
if (this.targetOrdinal == -1 || this.targetOrdinal == this.ordinal) {
nodes.add(insn);
this.found = true;
}
this.ordinal++;
this.varNode = null;
}
}
public static final String CODE = "LOAD";
/**
* Return type of the handler, also the type of the local variable we're
* interested in
*/
private final Type returnType;
/**
* Discriminator, parsed from parent annotation
*/
private final LocalVariableDiscriminator discriminator;
/**
* Target opcode, inflected from return type
*/
private final int opcode;
/**
* Target ordinal
*/
private final int ordinal;
/**
* True if this injection point should capture the opcode after a matching
* opcode, used by {@link AfterStoreLocal}.
*/
private boolean opcodeAfter;
public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) {
this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false);
}
protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data,
int opcode, boolean opcodeAfter) {
super(mixin);
this.returnType = returnType;
this.discriminator = discriminator;
this.opcode = data.getOpcode(returnType.getOpcode(opcode));
this.ordinal = data.getOrdinal();
this.opcodeAfter = opcodeAfter;
}
@Override
boolean find(Target target, Collection<AbstractInsnNode> nodes) {
SearchState state = new SearchState(this.ordinal);
ListIterator<AbstractInsnNode> iter = target.method.instructions.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
} else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) {
state.register((VarInsnNode)insn);
if (this.opcodeAfter) {
state.setPendingCheck();
} else {
int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
}
}
}
return state.success();
}
}
@@ -0,0 +1,45 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Thrown when an <em>implicit</em> discriminator (no args) fails to identify
* a unique candidate.
*/
public class InvalidImplicitDiscriminatorException extends MixinException {
private static final long serialVersionUID = 1L;
public InvalidImplicitDiscriminatorException(String message) {
super(message);
}
public InvalidImplicitDiscriminatorException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,348 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.LocalVariableNode;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* Encapsulates logic for identifying a local variable in a target method using
* 3 criteria: <em>ordinal</em>, <em>index</em> and <em>name</em>. This is used
* by the {@link ModifyVariableInjector} and its associated injection points.
*/
public class LocalVariableDiscriminator {
/**
* Discriminator context information, wraps all relevant information about
* a target location for use when performing discrimination
*/
public static class Context implements org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable {
/**
* Information about a local variable in the LVT, used during
* discrimination
*/
public class Local {
/**
* Ordinal value of this local variable type
*/
int ord = 0;
/**
* Local variable name
*/
String name;
/**
* Local variable type
*/
Type type;
public Local(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type);
}
}
/**
* Target method for this context
*/
final Target target;
/**
* The return type of the handler in question, also the type of the
* local variable that we care about
*/
final Type returnType;
/**
* Injection point
*/
final AbstractInsnNode node;
/**
* Base argument index, for static methods this is 0, for instance
* methods this is 1
*/
final int baseArgIndex;
/**
* Enumerated locals in this context
*/
final Local[] locals;
/**
* True if the handler (and target) are static
*/
private final boolean isStatic;
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
this.isStatic = ASMHelper.methodIsStatic(target.method);
this.returnType = returnType;
this.target = target;
this.node = node;
this.baseArgIndex = this.isStatic ? 0 : 1;
this.locals = this.initLocals(target, argsOnly, node);
this.initOrdinals();
}
private Local[] initLocals(Target target, boolean argsOnly, AbstractInsnNode node) {
if (!argsOnly) {
LocalVariableNode[] locals = Locals.getLocalsAt(target.classNode, target.method, node);
if (locals != null) {
Local[] lvt = new Local[locals.length];
for (int l = 0; l < locals.length; l++) {
if (locals[l] != null) {
lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc));
}
}
return lvt;
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
if (!this.isStatic) {
lvt[0] = new Local("this", Type.getType(target.classNode.name));
}
for (int local = this.baseArgIndex; local < lvt.length; local++) {
Type arg = target.arguments[local - this.baseArgIndex];
lvt[local] = new Local("arg" + local, arg);
}
return lvt;
}
private void initOrdinals() {
Map<Type, Integer> ordinalMap = new HashMap<Type, Integer>();
for (int l = 0; l < this.locals.length; l++) {
Integer ordinal = Integer.valueOf(0);
if (this.locals[l] != null) {
ordinal = ordinalMap.get(this.locals[l].type);
ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1));
this.locals[l].ord = ordinal.intValue();
}
}
}
@Override
public void print(PrettyPrinter printer) {
printer.add("%5s %7s %30s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE");
for (int l = this.baseArgIndex; l < this.locals.length; l++) {
Local local = this.locals[l];
if (local != null) {
Type localType = local.type;
String localName = local.name;
int ordinal = local.ord;
String candidate = this.returnType.equals(localType) ? "YES" : "-";
printer.add("[%3d] [%3d] %30s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate);
} else if (l > 0) {
Local prevLocal = this.locals[l - 1];
boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1;
printer.add("[%3d] %30s", l, isTop ? "<top>" : "-");
}
}
}
}
/**
* True to consider only method args
*/
private final boolean argsOnly;
/**
* Ordinal of the target variable or -1 to fail over to {@link index}
*/
private final int ordinal;
/**
* Ordinal of the target variable or -1 to fail over to {@link names}
*/
private final int index;
/**
* Candidate names for the local variable, if empty fails over to matching
* single local by type
*/
private final Set<String> names;
/**
* @param argsOnly
* @param ordinal target variable ordinal
* @param index target variable index
* @param names target variable names
*/
public LocalVariableDiscriminator(boolean argsOnly, int ordinal, int index, Set<String> names) {
this.argsOnly = argsOnly;
this.ordinal = ordinal;
this.index = index;
this.names = Collections.<String>unmodifiableSet(names);
}
/**
* True if this discriminator will examine only the target method args and
* won't consider the rest of the LVT at the target location
*/
public boolean isArgsOnly() {
return this.argsOnly;
}
/**
* Get the local variable ordinal (nth variable of type)
*/
public int getOrdinal() {
return this.ordinal;
}
/**
* Get the local variable absolute index
*/
public int getIndex() {
return this.index;
}
/**
* Get valid names for consideration
*/
public Set<String> getNames() {
return this.names;
}
/**
* Returns true if names is not empty
*/
public boolean hasNames() {
return !this.names.isEmpty();
}
/**
* If the user specifies no values for <tt>ordinal</tt>, <tt>index</tt> or
* <tt>names</tt> then we are considered to be operating in "implicit mode"
* where only a single local variable of the specified type is expected to
* exist.
*
* @param context Target context
* @return true if operating in implicit mode
*/
protected boolean isImplicit(final Context context) {
return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty();
}
public int findLocal(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
try {
return this.findLocal(new Context(returnType, argsOnly, target, node));
} catch (InvalidImplicitDiscriminatorException ex) {
return -1;
}
}
public int findLocal(Context context) {
if (this.isImplicit(context)) {
return this.findImplicitLocal(context);
}
return this.findExplicitLocal(context);
}
private int findImplicitLocal(final Context context) {
int found = 0;
int count = 0;
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
count++;
found = index;
}
if (count == 1) {
return found;
}
throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required.");
}
private int findExplicitLocal(final Context context) {
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
if (this.ordinal > -1) {
if (this.ordinal == local.ord) {
return index;
}
continue;
}
if (this.index >= context.baseArgIndex) {
if (this.index == index) {
return index;
}
continue;
}
if (this.names.contains(local.name)) {
return index;
}
}
return -1;
}
public static LocalVariableDiscriminator parse(AnnotationNode annotation) {
boolean argsOnly = ASMHelper.<Boolean>getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue();
int ordinal = ASMHelper.<Integer>getAnnotationValue(annotation, "ordinal", -1);
int index = ASMHelper.<Integer>getAnnotationValue(annotation, "index", -1);
Set<String> names = new HashSet<String>();
List<String> namesList = ASMHelper.<List<String>>getAnnotationValue(annotation, "name", (List<String>)null);
if (namesList != null) {
names.addAll(namesList);
}
return new LocalVariableDiscriminator(argsOnly, ordinal, index, names);
}
}
@@ -0,0 +1,209 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.Collection;
import java.util.List;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* A bytecode injector which allows a single local variable in the target method
* to be captured and altered. See also {@link LocalVariableDiscriminator} and
* {@link ModifyVariable}.
*/
public class ModifyVariableInjector extends Injector {
/**
* Target context information
*/
static class Context extends LocalVariableDiscriminator.Context {
/**
* Instructions to inject
*/
final InsnList insns = new InsnList();
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
super(returnType, argsOnly, target, node);
}
}
/**
* Specialised injection point which uses a target-aware search pattern
*/
abstract static class ContextualInjectionPoint extends InjectionPoint {
protected final MixinTargetContext mixin;
ContextualInjectionPoint(MixinTargetContext mixin) {
this.mixin = mixin;
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(Target target, Collection<AbstractInsnNode> nodes);
}
/**
* Print LVT
*/
private final boolean print;
/**
* True to consider only method args
*/
private final LocalVariableDiscriminator discriminator;
/**
* @param info Injection info
* @param print
*/
public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) {
super(info);
this.print = print;
this.discriminator = discriminator;
}
@Override
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
if (injectionPoint instanceof ContextualInjectionPoint) {
return ((ContextualInjectionPoint)injectionPoint).find(this.info.getContext().getTargetMethod(into), nodes);
}
return injectionPoint.find(into.desc, insns, nodes);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector
* #sanityCheck(org.spongepowered.asm.mixin.injection.callback.Target,
* java.util.List)
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
if (target.isStatic != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this);
}
int ordinal = this.discriminator.getOrdinal();
if (ordinal < -1) {
throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this);
}
if (this.discriminator.getIndex() == 0 && !this.isStatic) {
throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this);
}
}
/**
* Do the injection
*/
@Override
protected void inject(Target target, InjectionNode node) {
if (node.isReplaced()) {
throw new InvalidInjectionException(this.info, "Variable modifier target for " + this + " was removed by another injector");
}
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
if (this.print) {
this.printLocals(context);
}
try {
int local = this.discriminator.findLocal(context);
if (local > -1) {
this.inject(context, local);
}
} catch (InvalidImplicitDiscriminatorException ex) {
throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this, ex);
}
target.insns.insertBefore(context.node, context.insns);
target.addToStack(this.isStatic ? 1 : 2);
}
/**
* Pretty-print local variable information to stderr
*/
private void printLocals(final Context context) {
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" });
handlerSig.setModifiers(this.methodNode);
new PrettyPrinter()
.kvWidth(20)
.kv("Target Class", this.classNode.name.replace('/', '.'))
.kv("Target Method", context.target.method.name)
.kv("Callback Name", this.methodNode.name)
.kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false))
.kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(context.node.getOpcode())).hr()
.kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)")
.kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal())
.kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex())
.kv("Match name(s)", this.discriminator.hasNames() ? this.discriminator.getNames() : "any")
.kv("Args only", this.discriminator.isArgsOnly()).hr()
.add(context)
.print(System.err);
}
/**
* Perform the injection
*
* @param context target context
* @param local local variable to capture
*/
private void inject(final Context context, final int local) {
if (!this.isStatic) {
context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local));
this.invokeHandler(context.insns);
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local));
}
}
@@ -35,7 +35,6 @@ import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
/**
* <p>This injection point searches for INVOKEVIRTUAL, INVOKESTATIC and
* INVOKESPECIAL opcodes matching its arguments and returns a list of insns
@@ -71,9 +71,9 @@ public class BeforeInvoke extends InjectionPoint {
protected final MemberInfo target;
/**
* This strategy can be used to identify a particular invokation if the same
* This strategy can be used to identify a particular invocation if the same
* method is invoked at multiple points, if this value is -1 then the
* strategy returns <em>all</em> invokations of the method.
* strategy returns <em>all</em> invocations of the method.
*/
protected final int ordinal;
@@ -26,12 +26,16 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about a callback to inject, usually specified by {@link Inject}
*/
public class CallbackInjectionInfo extends InjectionInfo {
protected CallbackInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
@@ -39,10 +43,12 @@ public class CallbackInjectionInfo extends InjectionInfo {
}
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
protected Injector parseInjector(AnnotationNode injectAnnotation) {
boolean cancellable = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "cancellable", false);
LocalCapture locals = ASMHelper.<LocalCapture>getAnnotationValue(injectAnnotation, "locals", LocalCapture.class, LocalCapture.NO_CAPTURE);
String identifier = ASMHelper.<String>getAnnotationValue(injectAnnotation, "id", "");
return new CallbackInjector(this, cancellable, locals);
return new CallbackInjector(this, cancellable, locals, identifier);
}
}
@@ -28,24 +28,34 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.InjectorGroupInfo;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Contructs information about an injection from an {@link Inject} annotation
* and allows the injection to be processed.
@@ -68,8 +78,7 @@ public abstract class InjectionInfo {
* Mixin data
*/
protected final MixinTargetContext mixin;
/**
* Annotated method is static
*/
@@ -86,16 +95,41 @@ public abstract class InjectionInfo {
*/
protected final List<InjectionPoint> injectionPoints = new ArrayList<InjectionPoint>();
/**
* Map of lists of nodes enumerated by calling {@link #prepare}
*/
protected final Map<Target, List<InjectionNode>> targetNodes = new LinkedHashMap<Target, List<InjectionNode>>();
/**
* Bytecode injector
*/
protected Injector injector;
/**
* Injection group
*/
protected InjectorGroupInfo group;
/**
* Methods injected by injectors
*/
private final List<MethodNode> injectedMethods = new ArrayList<MethodNode>(0);
/**
* Number of callbacks we expect to inject into targets
*/
private int expectedCallbackCount = 1;
/**
* Number of callbacks we require injected
*/
private int requiredCallbackCount = 0;
/**
* Actual number of injected callbacks
*/
private int injectedCallbackCount = 0;
/**
* ctor
*
@@ -104,10 +138,10 @@ public abstract class InjectionInfo {
* @param annotation Annotation to parse
*/
protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
this.annotation = annotation;
this.method = method;
this.mixin = mixin;
this.classNode = mixin.getTargetClass();
this.method = method;
this.annotation = annotation;
this.classNode = mixin.getTargetClassNode();
this.isStatic = ASMHelper.methodIsStatic(method);
this.readAnnotation();
}
@@ -115,55 +149,78 @@ public abstract class InjectionInfo {
/**
* Parse the info from the supplied annotation
*/
@SuppressWarnings("unchecked")
protected void readAnnotation() {
if (this.annotation == null) {
return;
}
String type = "@" + this.annotation.desc.substring(this.annotation.desc.lastIndexOf('/') + 1, this.annotation.desc.length() - 1);
String type = "@" + ASMHelper.getSimpleName(this.annotation);
List<AnnotationNode> injectionPoints = this.readInjectionPoints(type);
this.findMethods(this.parseTarget(type), type);
this.parseInjectionPoints(injectionPoints);
this.parseRequirements();
this.injector = this.parseInjector(this.annotation);
}
protected MemberInfo parseTarget(String type) {
String method = ASMHelper.<String>getAnnotationValue(this.annotation, "method");
if (method == null) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing method name");
}
List<AnnotationNode> ats = null;
try {
MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
return targetMember;
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + ", has invalid target descriptor: \""
+ method + "\"");
}
}
@SuppressWarnings("unchecked")
protected List<AnnotationNode> readInjectionPoints(String type) {
Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at");
if (atValue instanceof List) {
ats = (List<AnnotationNode>)atValue;
return (List<AnnotationNode>)atValue;
} else if (atValue instanceof AnnotationNode) {
ats = new ArrayList<AnnotationNode>();
List<AnnotationNode> ats = new ArrayList<AnnotationNode>();
ats.add((AnnotationNode)atValue);
} else {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
return ats;
}
MemberInfo targetMember = MemberInfo.parse(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
this.findMethods(targetMember);
if (this.targets.size() == 0) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'");
}
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
}
protected void parseInjectionPoints(List<AnnotationNode> ats) {
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at);
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at);
if (injectionPoint != null) {
this.injectionPoints.add(injectionPoint);
}
}
}
protected void parseRequirements() {
this.group = this.mixin.getInjectorGroups().parseGroup(this.method, this.mixin.getDefaultInjectorGroup()).add(this);
this.injector = this.initInjector(this.annotation);
Integer expect = ASMHelper.<Integer>getAnnotationValue(this.annotation, "expect");
if (expect != null) {
this.expectedCallbackCount = expect.intValue();
}
Integer require = ASMHelper.<Integer>getAnnotationValue(this.annotation, "require");
if (require != null && require.intValue() > -1) {
this.requiredCallbackCount = require.intValue();
} else if (this.group.isDefault()) {
this.requiredCallbackCount = this.mixin.getDefaultRequiredInjections();
}
}
// stub
protected abstract Injector initInjector(AnnotationNode injectAnnotation);
protected abstract Injector parseInjector(AnnotationNode injectAnnotation);
/**
* Get whether there is enough valid information in this info to actually
@@ -176,13 +233,24 @@ public abstract class InjectionInfo {
}
/**
* Perform the injection
* Discover injection points
*/
public void prepare() {
this.targetNodes.clear();
for (MethodNode targetMethod : this.targets) {
Target target = this.mixin.getTargetMethod(targetMethod);
this.targetNodes.put(target, this.injector.find(target, this.injectionPoints));
}
}
/**
* Perform injections
*/
public void inject() {
while (this.targets.size() > 0) {
Target target = this.mixin.getTargetMethod(this.targets.removeFirst());
this.injector.injectInto(target, this.injectionPoints);
for (Entry<Target, List<InjectionNode>> entry : this.targetNodes.entrySet()) {
this.injector.inject(entry.getKey(), entry.getValue());
}
this.targets.clear();
}
/**
@@ -192,6 +260,30 @@ public abstract class InjectionInfo {
for (MethodNode method : this.injectedMethods) {
this.classNode.methods.add(method);
}
if ((MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) {
throw new InvalidInjectionException(this,
String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded",
this.getDescription(), this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount));
} else if (this.injectedCallbackCount < this.requiredCallbackCount) {
throw new InjectionError(
String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded",
this.getDescription(), this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount));
}
}
public void notifyInjected(Target target) {
// this.targets.remove(target.method);
}
protected String getDescription() {
return "Callback method";
}
@Override
public String toString() {
return InjectionInfo.describeInjector(this.mixin, this.annotation, this.method);
}
/**
@@ -238,6 +330,15 @@ public abstract class InjectionInfo {
public Collection<MethodNode> getTargets() {
return this.targets;
}
/**
* Get the injected callback count
*
* @return the injected callback count
*/
public int getInjectedCallbackCount() {
return this.injectedCallbackCount;
}
/**
* Inject a method into the target class
@@ -254,41 +355,66 @@ public abstract class InjectionInfo {
return method;
}
/**
* Notify method, called by injector when adding a callback into a target
*
* @param handler callback handler being invoked
*/
public void addCallbackInvocation(MethodNode handler) {
this.injectedCallbackCount++;
}
/**
* Finds methods in the target class which match searchFor
*
* @param searchFor member info to search for
* @param type annotation type
*/
private void findMethods(MemberInfo searchFor) {
private void findMethods(MemberInfo searchFor, String type) {
this.targets.clear();
int ordinal = 0;
for (MethodNode target : this.classNode.methods) {
if (searchFor.matches(target.name, target.desc, ordinal)) {
if (searchFor.matchAll && ASMHelper.methodIsStatic(target) != this.isStatic) {
boolean isMixinMethod = ASMHelper.getVisibleAnnotation(target, MixinMerged.class) != null;
if (searchFor.matchAll && (ASMHelper.methodIsStatic(target) != this.isStatic || target == this.method || isMixinMethod)) {
continue;
}
AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class);
if (merged != null) {
throw new InvalidInjectionException(this, "Cannot inject into a mixin method");
}
this.checkTarget(target);
this.targets.add(target);
ordinal++;
}
}
if (this.targets.size() == 0) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + searchFor.name + "'");
}
}
private void checkTarget(MethodNode target) {
AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class);
if (merged == null) {
return;
}
String owner = ASMHelper.<String>getAnnotationValue(merged, "mixin");
int priority = ASMHelper.<Integer>getAnnotationValue(merged, "priority");
if (priority >= this.mixin.getPriority() && !owner.equals(this.mixin.getClassName())) {
throw new InvalidInjectionException(this, this + " cannot inject into " + this.classNode.name + "::" + target.name + target.desc
+ " merged by " + owner + " with priority " + priority);
}
if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) {
throw new InvalidInjectionException(this, this + " cannot inject into @Final method " + this.classNode.name + "::" + target.name
+ target.desc + " merged by " + owner);
}
}
@SuppressWarnings("unchecked")
public static InjectionInfo parse(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = null;
try {
annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class);
} catch (IllegalArgumentException ex) {
throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": "
+ ex.getMessage());
}
AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(mixin, method);
if (annotation == null) {
return null;
@@ -300,8 +426,50 @@ public abstract class InjectionInfo {
return new ModifyArgInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) {
return new RedirectInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) {
return new ModifyVariableInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) {
return new ModifyConstantInjectionInfo(mixin, method, annotation);
}
return null;
}
@SuppressWarnings("unchecked")
public static AnnotationNode getInjectorAnnotation(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = null;
try {
annotation = ASMHelper.getSingleVisibleAnnotation(method,
Inject.class,
ModifyArg.class,
Redirect.class,
ModifyVariable.class,
ModifyConstant.class
);
} catch (IllegalArgumentException ex) {
throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": "
+ ex.getMessage());
}
return annotation;
}
public static String getInjectorPrefix(AnnotationNode annotation) {
if (annotation != null) {
if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) {
return "modify";
} else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) {
return "redirect";
} else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) {
return "localvar";
} else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) {
return "constant";
}
}
return "handler";
}
static String describeInjector(MixinTargetContext mixin, AnnotationNode annotation, MethodNode method) {
return String.format("%s->@%s::%s%s", mixin.toString(), ASMHelper.getSimpleName(annotation), method.name, method.desc);
}
}
@@ -28,8 +28,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spongepowered.asm.mixin.transformer.IReferenceMapperContext;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* Data read from an {@link org.spongepowered.asm.mixin.injection.At} annotation
@@ -45,8 +48,23 @@ public class InjectionPointData {
/**
* Mixin
*/
private final IReferenceMapperContext mixin;
private final MixinTargetContext mixin;
/**
* Injector callback
*/
private MethodNode method;
/**
* Parent annotation
*/
private AnnotationNode parent;
/**
* At arg
*/
private String at;
/**
* Target
*/
@@ -62,8 +80,12 @@ public class InjectionPointData {
*/
private final int opcode;
public InjectionPointData(IReferenceMapperContext mixin, List<String> args, String target, int ordinal, int opcode) {
public InjectionPointData(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, List<String> args, String target,
int ordinal, int opcode) {
this.mixin = mixin;
this.method = method;
this.parent = parent;
this.at = at;
this.target = target;
this.ordinal = Math.max(-1, ordinal);
this.opcode = opcode;
@@ -76,6 +98,9 @@ public class InjectionPointData {
}
private void parseArgs(List<String> args) {
if (args == null) {
return;
}
for (String arg : args) {
if (arg != null) {
int eqPos = arg.indexOf('=');
@@ -87,6 +112,18 @@ public class InjectionPointData {
}
}
}
public MixinTargetContext getMixin() {
return this.mixin;
}
public MethodNode getMethod() {
return this.method;
}
public AnnotationNode getParent() {
return this.parent;
}
public String get(String key, String defaultValue) {
String value = this.args.get(key);
@@ -102,7 +139,12 @@ public class InjectionPointData {
}
public MemberInfo get(String key) {
return MemberInfo.parse(this.get(key, ""), this.mixin);
try {
return MemberInfo.parseAndValidate(this.get(key, ""), this.mixin);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s",
this.at, key, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
}
}
private int parseInt(String string, int defaultValue) {
@@ -122,7 +164,12 @@ public class InjectionPointData {
}
public MemberInfo getTarget() {
return MemberInfo.parse(this.target, this.mixin);
try {
return MemberInfo.parseAndValidate(this.target, this.mixin);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s",
this.at, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
}
}
public int getOrdinal() {
@@ -0,0 +1,48 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Thrown when a {@link MemberInfo} fails basic syntax validation
*/
public class InvalidMemberDescriptorException extends MixinException {
private static final long serialVersionUID = 1L;
public InvalidMemberDescriptorException(String message) {
super(message);
}
public InvalidMemberDescriptorException(Throwable cause) {
super(cause);
}
public InvalidMemberDescriptorException(String message, Throwable cause) {
super(message, cause);
}
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more