Merge pull request #57 from modmuss50/upstream_merge

Merge Upstream 0.8.3
This commit is contained in:
modmuss50 authored and GitHub committed 2021-06-28 22:20:31 +01:00
commit e18ee5c8e5
185 files changed
+9666 -1597

No files matched your search

+60 -20
View File
@@ -1,34 +1,53 @@
### [![Build Status](http://ci.liteloader.com/view/Other/job/Mixin/badge/icon)](http://ci.liteloader.com/view/Other/job/Mixin/lastSuccessfulBuild/)
![Mixin Logo](docs/logo.png?raw=true)
![Mixin Logo](docs/javadoc/resources/logo.png?raw=true)
**Mixin** is a trait/mixin framework for Java using [ASM](http://asm.ow2.org/)
and hooking into the runtime class-loading process via Mojang's
[LegacyLauncher](https://github.com/Mojang/LegacyLauncher) system.
**Mixin** is a trait/mixin framework for Java using [ASM](https://asm.ow2.io/)
and hooking into the runtime classloading process via a set of pluggable
built-in or user-provided services. Built-in services currently support Mojang's
[LegacyLauncher](https://github.com/Mojang/LegacyLauncher) system, though this
is deprecated in favour of [ModLauncher](https://github.com/cpw/modlauncher) by
cpw, which has greater extensibility and has support for Java 8 and later.
### Documentation
The main documentation for **Mixin** can be found in the [Wiki](../../wiki).
The main documentation for **Mixin** can be found in the
[Wiki](https://github.com/SpongePowered/Mixin/wiki).
Additional documentation for individual features and annotations can be found in
the extensive [Javadoc](http://jenkins.liteloader.com/job/Mixin/javadoc/). For
additional help use the channel [`#mixin` on the
Sponge Discord Server](https://discord.gg/tBcwxz2).
additional help use the channel [`#mixin` on the Sponge Discord Server](https://discord.gg/tBcwxz2).
### Building Mixin
**Mixin** uses the [Gradle](http://gradle.org/) build automation system. To
perform a build, use gradle version 4.9 and execute
### Binaries
gradle
Mixin binaries are available via [Jenkins](https://jenkins.liteloader.com/view/Other/job/Mixin/)
and are published to the following maven repositories:
from within the project root directory. *(If you do not have Gradle installed on
your system you can instead run the supplied Gradle wrapper `gradlew`)*
* https://repo.spongepowered.org/repository/maven-public/ - SNAPHOTs and RELEASE
builds
* https://files.minecraftforge.net/maven/ - RELEASE builds only
### Integration with Eclipse IDE
### Tooling
The **Mixin** project can be integrated easily with Eclipse using Buildship.
Simply choose `Import` -> `Gradle Project` and follow the prompts.
For handling obfuscation tasks, Mixin provides an [Annotation Processor](https://github.com/SpongePowered/Mixin/wiki/Using-the-Mixin-Annotation-Processor)
which works at compile time to generate obfuscation mappings for your toolchain
to apply. If using Gradle 5 or later, annotation processors are no longer
automatically loaded from `compile` configurations and must be specified
explicitly via `annotationProcessor` configurations. For this purpose, Mixin
provides "fat jar" artefacts containing all required dependencies via the
`:processor` classifier. For example if your build uses the dependency
`org.spongepowered:mixin:1.2.3` then your annotationProcessor configuration
should specify dependency `org.spongepowered:mixin:1.2.3:processor`.
If you are using Mixin in a [Minecraft Forge](https://minecraftforge.net/)
project then the [MixinGradle](https://github.com/SpongePowered/MixinGradle)
plugin can be used to simplify the configuration of the Mixin Annotation
Processor. It provides a simple syntax for configuring the Mixin AP for your
project, see the [MixinGradle README](https://github.com/SpongePowered/MixinGradle/blob/master/README.md)
for how to configure MixinGradle.
### Integration with Eclipse
When developing using **Mixin**, you can use the **Mixin Annotation Processor**
within Eclipse to provide context-sensitive errors and warnings to help you more
@@ -45,11 +64,12 @@ easily troubleshoot your mixins. To do so:
7. Check the `Enable annotation processing` checkbox
8. Click the `New...` button next to the `Processor options` box
* Set `Key` to **reobfSrgFile**
* Set `Value` to the fully-qualified path to the `mcp-srg.srg` file (for Sponge
this can be found in `Sponge/build/srgs/mcp-srg.srg`)
* Set `Value` to the fully-qualified path to the `mcp-srg.srg` file (the
location of the mapping file varies by platform, if you are unsure where to
find it please follow the discord link below).
9. Click `OK` to apply the changes
### Integration with IntelliJ IDEA IDE
### Integration with IntelliJ IDEA
Enhanced functionality for working with **Mixin** in IntelliJ IDEA is available
via the [Minecraft Development for IntelliJ IDEA](https://plugins.jetbrains.com/idea/plugin/8327)
@@ -57,6 +77,11 @@ plugin developed by [DemonWav](https://github.com/demonwav).
### Version History
[Specifying the `minVersion` property in your configurations](https://github.com/SpongePowered/Mixin/wiki/PSA-Forward-Compatibility-Features-in-Mixin)
is extrememly important. The following version history can be used to determine
when features were introduced (and sometimes when major bugs are squashed) in
order to help you determine which `minVersion` you should specify.
<table width="100%">
<thead>
<tr>
@@ -67,13 +92,28 @@ plugin developed by [DemonWav](https://github.com/demonwav).
</thead>
<tbody>
<tr>
<td valign="top"><b>0.8.1</b></td>
<td valign="top"><b>0.8.3</b></td>
<td valign="top">February 2021</td>
<td valign="top">
<ul>
<li>Added dynamic target selector support and <tt>&#64;Desc</tt>
target selector</li>
<li>Added pattern target selector</li>
<li>Added more expressive quantifier support to explicit target
selectors</li>
<li>Facelift and overall improvements to javadoc</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><b><s>0.8.1</s> (0.8.2)</b></td>
<td valign="top">September 2020</td>
<td valign="top">
<ul>
<li><b>Hotfix for supporting ModLauncher 7.0</b></li>
<li>Fix critical issue with resolving obfuscated members in inherited
interfaces</li>
<li><b>Updated to ASM 7.2</b></li>
</ul>
</td>
</tr>
+49 -2
View File
@@ -4,19 +4,22 @@ buildscript {
jcenter()
}
dependencies {
classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0'
classpath 'com.github.jengelman.gradle.plugins:shadow:6.1.0'
}
}
// Apply plugin
apply plugin: 'java'
apply plugin: 'license'
apply plugin: 'checkstyle'
apply plugin: 'maven-publish'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'com.github.johnrengelman.shadow'
// Default tasks
defaultTasks 'build'
defaultTasks 'licenseFormat', 'check', 'build'
// Basic project information
group = 'net.fabricmc'
@@ -164,8 +167,24 @@ dependencies {
}
javadoc {
classpath += sourceSets.legacy.output // why?
exclude '**/throwables'
classpath += sourceSets.legacy.output
source sourceSets.ap.allJava
options.encoding = 'UTF-8'
exclude {
it.relativePath.file && it.relativePath.pathString =~ 'tools' && !(it.name =~ /SuppressedBy|package-info/) }
options {
docTitle 'Welcome to the Mixin Javadoc'
overview 'docs/javadoc/overview.html'
stylesheetFile file('docs/javadoc/mixin.css')
addBooleanOption '-allow-script-in-comments', true
}
doLast {
copy {
from 'docs/javadoc/resources'
into outputDirectory
}
}
}
// Eclipse
@@ -190,6 +209,34 @@ processResources {
from 'LICENSE.txt'
}
// License header formatting
license {
ext {
name = "Mixin"
organization = "SpongePowered"
url = "https://www.spongepowered.org"
}
include '**/*.java'
header file("HEADER.txt")
sourceSets = project.sourceSets
ignoreFailures false
strictCheck true
mapping {
java = 'SLASHSTAR_STYLE'
}
}
checkstyle {
configProperties = [
"name" : project.name,
"organization": project.organization,
"url" : project.url,
"year" : project.inceptionYear
]
configFile = file("checkstyle.xml")
toolVersion = '8.36.1'
}
// Source compiler configuration
tasks.withType(JavaCompile) {
options.compilerArgs += ['-Xlint:all', '-Xlint:-path', '-proc:none']
-4
View File
@@ -92,9 +92,7 @@
<metadata name="net.sf.eclipsecs.core.comment" value="Package members"/>
<property name="scope" value="package"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="suppressLoadErrors" value="true"/>
<property name="tokens" value="METHOD_DEF"/>
</module>
<module name="JavadocTagContinuationIndentation">
@@ -104,9 +102,7 @@
<metadata name="net.sf.eclipsecs.core.comment" value="Public members"/>
<property name="scope" value="public"/>
<property name="excludeScope" value="package"/>
<property name="allowMissingThrowsTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="suppressLoadErrors" value="true"/>
<property name="tokens" value="METHOD_DEF"/>
</module>
<module name="NonEmptyAtclauseDescription"/>
+306
View File
@@ -0,0 +1,306 @@
@import url('jdk8_stylesheet.css');
/* Montserrat font, for sponge style */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700;900');
span.summary {
clear: both;
display: block;
}
span.summary.p {
padding: 12px 0;
}
span.summary hr {
color: transparent;
margin: 8px;
}
.subTitle .block .summary {
margin-block-start: 0;
}
.tableSubHeadingColor {
background-color:#EEEEFF;
}
.altColor, .rowColor {
background-color:#FFFFFF;
}
/* altColor and rowColor get screwed up by hidden classes so just use css */
tr.altColor:nth-child(even), tr.rowColor:nth-child(even) {
background: #EEE;
}
sup {
font-size:8px;
}
tt {
color: #6c4e0b;
}
code i, dt i {
color: #996c0c;
}
a:link, a:visited, code b {
color: #c79015;
}
a:hover, a:focus, a:active, code em {
color: #e8aa21;
}
code b, code em, code i, dt i {
font-style: normal;
font-weight: normal;
}
ins {
background-color: #ffd26d;
text-decoration: none;
}
del {
color: #AAA;
text-decoration: none;
}
table.infoTable {
border-collapse: collapse;
}
table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th, table.selectorTable td, table.selectorTable th {
padding: 6px 8px;
background-color: #F0F0F0;
}
table.cellTable th, table.cellTable td {
text-align: center;
}
table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th, table.selectorTable th, table.selectorTable td.th {
background-color: #CCC;
font-weight: bold;
}
table.selectorTable tbody td, table.selectorTable thead th {
border-left: 6px solid #FFF;
}
table.selectorTable tbody td {
font-family: 'Consolas', monospace;
}
table.selectorTable th, table.selectorTable td.th {
background: transparent;
font-family: inherit;
}
table.selectorTable thead th.ownr { background-color: #CFC }
table.selectorTable thead th.name { background-color: #CCF }
table.selectorTable thead th.quan { background-color: #FFC }
table.selectorTable thead th.desc { background-color: #FCC }
table.selectorTable tbody td.ownr { background-color: #F0FFF0 }
table.selectorTable tbody td.name { background-color: #F0F0FF }
table.selectorTable tbody td.quan { background-color: #FFFFF0 }
table.selectorTable tbody td.desc { background-color: #FFF0F0 }
span.aownr { background-color: #DFD }
span.aname { background-color: #DDF }
span.aquan { background-color: #FFD }
span.adesc { background-color: #FDD }
span.ownr {color: #090 }
span.name {color: #009 }
span.quan {color: #990 }
span.desc {color: #900 }
a[name] {
color: #353833;
}
a[name]:hover {
text-decoration:none;
color: #353833;
}
body {
background-color: #FFF;
}
body, div.block {
font-family: Tahoma, sans-serif, sans;
font-size: 15px;
}
.indexContainer,
td.colFirst, th.colFirst, td.colLast, th.colLast, td.colOne, th.colOne,
.indexHeader h1, .header ul li, .footer ul li {
font-size: 16px;
}
.indexHeader span {
font-size: 24px;
}
.indexHeader h1 {
font-size:13px;
}
.indexContainer h2 {
font-size: 17px;
}
.bar a, .bar a:link, .bar a:visited, .bar a:active {
color:#FFFFFF;
}
.bar {
font-size: 17px;
}
.tab {
color: #FFFFFF;
}
.topNav, .bottomNav, .bar {
color: #FFFFFF;
background-color: #666;
}
.topNav, .bottomNav {
font-size: 16px;
}
.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {
color:#FFFFFF;
}
.subNav {
background-color: #CCC;
font-size: 15px;
}
.navBarCell1Rev {
background-color: #e8aa21;
color: #000;
}
.header ul li, .footer ul li {
font-size:13px;
}
.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span,
.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span {
background-color: #e8aa21;
padding: 6px 12px;
height: auto;
font-family: Montserrat;
text-transform: uppercase;
}
.memberSummary caption span.activeTableTab span {
background-color: #e8aa21;
padding: 6px 12px;
height: auto;
border-bottom: 2px solid #e8aa21;
}
.memberSummary caption span.tableTab span {
background-color: #666;
padding: 6px 12px;
height: auto;
border-bottom: 2px solid white;
}
.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary {
border-width: 2px;
}
.title, h1, h2, h3, h4, h5, h6, .h1 {
font-family: 'Montserrat';
}
.title {
font-weight: 700;
color: #666;
}
h1.overviewTitle, .header img {
margin: 32px 0 0 0;
}
h1, .h1 {
font-weight: bold;
font-size: 45px;
}
h2 {
font-size: 32px;
}
h3 {
font-style: normal;
}
h1.title, .summary.h1 {
text-transform: uppercase;
}
pre, code, tt, dt code, table tr td dt code {
font-family: 'Consolas', monospace;
font-size: 16px;
}
.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {
font-size: 15px;
}
.contentContainer .description .block dl dt {
background: #CCC;
display: inline-block;
padding: 6px 12px;
margin-left: 20px;
}
.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {
font-family: Tahoma, sans-serif, sans;
font-size: 15px;
}
.contentContainer .description .block dl dd {
background: #F0F0F0;
margin: -6px 0 0 40px;
padding: 12px;
}
div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4, ul.blockList ul.blockList ul.blockList li.blockList h3 {
background-color: #CCC;
border: 0;
margin: 0 0 6px -8px;
padding: 9px 12px;
}
th.colFirst, th.colLast, th.colOne, .constantsSummary th {
background: #CCC;
padding: 8px;
}
blockquote {
background-color: #F5F5F5;
padding: 12px 40px;
margin: 12px 0;
}
blockquote pre {
margin: 0;
}
ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {
padding-top: 1px;
border: 0;
background-color: #F5F5F5;
}
+37
View File
@@ -0,0 +1,37 @@
<body>
<p class="summary">
<b>Mixin</b> is a trait/mixin framework for Java using
<a target="_top" href="http://asm.ow2.org/">ASM</a> and hooking into
the runtime class-loading process via Mojang's
<a target="_top" href="https://github.com/Mojang/LegacyLauncher">
LegacyLauncher</a> system. The main documentation for <b>Mixin</b> can
be found in the
<a target="_top" href="https://github.com/SpongePowered/Mixin/wiki">
Wiki</a>.
</p>
<p id="description">
This Javadoc contains documentation for individual features and
annotations. For additional help use the channel
<a target="_blank" href="https://discord.gg/tBcwxz2"><code>#mixin</code>
on the Sponge Discord Server</a>.
</p>
<script type="text/javascript">
// Insert mixin logo
let titleNode = document.querySelector('h1.title');
let logoImg = document.createElement('IMG');
logoImg.src = 'logo.png';
logoImg.title = 'SpongePowered MIXIN';
titleNode.parentElement.insertBefore(logoImg, titleNode);
// Make sure we get the correct block
let summaryBlock = document.querySelector(".contentContainer .block .summary").parentElement;
let headerBlock = document.querySelector(".subTitle .block");
headerBlock.innerHTML = summaryBlock.innerHTML;
document.querySelector(".subTitle").nextElementSibling.remove();
summaryBlock.remove();
titleNode.classList.add('overviewTitle');
</script>
</body>
+574
View File
@@ -0,0 +1,574 @@
/* Javadoc style sheet */
/*
Overall document style
*/
@import url('resources/fonts/dejavu.css');
body {
background-color:#ffffff;
color:#353833;
font-family:'DejaVu Sans', Arial, Helvetica, sans-serif;
font-size:14px;
margin:0;
}
a:link, a:visited {
text-decoration:none;
color:#4A6782;
}
a:hover, a:focus {
text-decoration:none;
color:#bb7a2a;
}
a:active {
text-decoration:none;
color:#4A6782;
}
a[name] {
color:#353833;
}
a[name]:hover {
text-decoration:none;
color:#353833;
}
pre {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
}
h1 {
font-size:20px;
}
h2 {
font-size:18px;
}
h3 {
font-size:16px;
font-style:italic;
}
h4 {
font-size:13px;
}
h5 {
font-size:12px;
}
h6 {
font-size:11px;
}
ul {
list-style-type:disc;
}
code, tt {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
margin-top:8px;
line-height:1.4em;
}
dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
padding-top:4px;
}
table tr td dt code {
font-family:'DejaVu Sans Mono', monospace;
font-size:14px;
vertical-align:top;
padding-top:4px;
}
sup {
font-size:8px;
}
/*
Document title and Copyright styles
*/
.clear {
clear:both;
height:0px;
overflow:hidden;
}
.aboutLanguage {
float:right;
padding:0px 21px;
font-size:11px;
z-index:200;
margin-top:-9px;
}
.legalCopy {
margin-left:.5em;
}
.bar a, .bar a:link, .bar a:visited, .bar a:active {
color:#FFFFFF;
text-decoration:none;
}
.bar a:hover, .bar a:focus {
color:#bb7a2a;
}
.tab {
background-color:#0066FF;
color:#ffffff;
padding:8px;
width:5em;
font-weight:bold;
}
/*
Navigation bar styles
*/
.bar {
background-color:#4D7A97;
color:#FFFFFF;
padding:.8em .5em .4em .8em;
height:auto;/*height:1.8em;*/
font-size:11px;
margin:0;
}
.topNav {
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.bottomNav {
margin-top:10px;
background-color:#4D7A97;
color:#FFFFFF;
float:left;
padding:0;
width:100%;
clear:right;
height:2.8em;
padding-top:10px;
overflow:hidden;
font-size:12px;
}
.subNav {
background-color:#dee3e9;
float:left;
width:100%;
overflow:hidden;
font-size:12px;
}
.subNav div {
clear:left;
float:left;
padding:0 0 5px 6px;
text-transform:uppercase;
}
ul.navList, ul.subNavList {
float:left;
margin:0 25px 0 0;
padding:0;
}
ul.navList li{
list-style:none;
float:left;
padding: 5px 6px;
text-transform:uppercase;
}
ul.subNavList li{
list-style:none;
float:left;
}
.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {
color:#FFFFFF;
text-decoration:none;
text-transform:uppercase;
}
.topNav a:hover, .bottomNav a:hover {
text-decoration:none;
color:#bb7a2a;
text-transform:uppercase;
}
.navBarCell1Rev {
background-color:#F8981D;
color:#253441;
margin: auto 5px;
}
.skipNav {
position:absolute;
top:auto;
left:-9999px;
overflow:hidden;
}
/*
Page header and footer styles
*/
.header, .footer {
clear:both;
margin:0 20px;
padding:5px 0 0 0;
}
.indexHeader {
margin:10px;
position:relative;
}
.indexHeader span{
margin-right:15px;
}
.indexHeader h1 {
font-size:13px;
}
.title {
color:#2c4557;
margin:10px 0;
}
.subTitle {
margin:5px 0 0 0;
}
.header ul {
margin:0 0 15px 0;
padding:0;
}
.footer ul {
margin:20px 0 5px 0;
}
.header ul li, .footer ul li {
list-style:none;
font-size:13px;
}
/*
Heading styles
*/
div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
background-color:#dee3e9;
border:1px solid #d0d9e0;
margin:0 0 6px -8px;
padding:7px 5px;
}
ul.blockList ul.blockList li.blockList h3 {
padding:0;
margin:15px 0;
}
ul.blockList li.blockList h2 {
padding:0px 0 20px 0;
}
/*
Page layout container styles
*/
.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer {
clear:both;
padding:10px 20px;
position:relative;
}
.indexContainer {
margin:10px;
position:relative;
font-size:12px;
}
.indexContainer h2 {
font-size:13px;
padding:0 0 3px 0;
}
.indexContainer ul {
margin:0;
padding:0;
}
.indexContainer ul li {
list-style:none;
padding-top:2px;
}
.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {
font-size:12px;
font-weight:bold;
margin:10px 0 0 0;
color:#4E4E4E;
}
.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {
margin:5px 0 10px 0px;
font-size:14px;
font-family:'DejaVu Sans Mono',monospace;
}
.serializedFormContainer dl.nameValue dt {
margin-left:1px;
font-size:1.1em;
display:inline;
font-weight:bold;
}
.serializedFormContainer dl.nameValue dd {
margin:0 0 0 1px;
font-size:1.1em;
display:inline;
}
/*
List styles
*/
ul.horizontal li {
display:inline;
font-size:0.9em;
}
ul.inheritance {
margin:0;
padding:0;
}
ul.inheritance li {
display:inline;
list-style:none;
}
ul.inheritance li ul.inheritance {
margin-left:15px;
padding-left:15px;
padding-top:1px;
}
ul.blockList, ul.blockListLast {
margin:10px 0 10px 0;
padding:0;
}
ul.blockList li.blockList, ul.blockListLast li.blockList {
list-style:none;
margin-bottom:15px;
line-height:1.4;
}
ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {
padding:0px 20px 5px 10px;
border:1px solid #ededed;
background-color:#f8f8f8;
}
ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList {
padding:0 0 5px 8px;
background-color:#ffffff;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockList {
margin-left:0;
padding-left:0;
padding-bottom:15px;
border:none;
}
ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast {
list-style:none;
border-bottom:none;
padding-bottom:0;
}
table tr td dl, table tr td dl dt, table tr td dl dd {
margin-top:0;
margin-bottom:1px;
}
/*
Table styles
*/
.overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary {
width:100%;
border-left:1px solid #EEE;
border-right:1px solid #EEE;
border-bottom:1px solid #EEE;
}
.overviewSummary, .memberSummary {
padding:0px;
}
.overviewSummary caption, .memberSummary caption, .typeSummary caption,
.useSummary caption, .constantsSummary caption, .deprecatedSummary caption {
position:relative;
text-align:left;
background-repeat:no-repeat;
color:#253441;
font-weight:bold;
clear:none;
overflow:hidden;
padding:0px;
padding-top:10px;
padding-left:1px;
margin:0px;
white-space:pre;
}
.overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link,
.useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link,
.overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover,
.useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover,
.overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active,
.useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active,
.overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited,
.useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited {
color:#FFFFFF;
}
.overviewSummary caption span, .memberSummary caption span, .typeSummary caption span,
.useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
padding-bottom:7px;
display:inline-block;
float:left;
background-color:#F8981D;
border: none;
height:16px;
}
.memberSummary caption span.activeTableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#F8981D;
height:16px;
}
.memberSummary caption span.tableTab span {
white-space:nowrap;
padding-top:5px;
padding-left:12px;
padding-right:12px;
margin-right:3px;
display:inline-block;
float:left;
background-color:#4D7A97;
height:16px;
}
.memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab {
padding-top:0px;
padding-left:0px;
padding-right:0px;
background-image:none;
float:none;
display:inline;
}
.overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd,
.useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd {
display:none;
width:5px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .activeTableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
float:left;
background-color:#F8981D;
}
.memberSummary .tableTab .tabEnd {
display:none;
width:5px;
margin-right:3px;
position:relative;
background-color:#4D7A97;
float:left;
}
.overviewSummary td, .memberSummary td, .typeSummary td,
.useSummary td, .constantsSummary td, .deprecatedSummary td {
text-align:left;
padding:0px 0px 12px 10px;
}
th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th,
td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{
vertical-align:top;
padding-right:0px;
padding-top:8px;
padding-bottom:3px;
}
th.colFirst, th.colLast, th.colOne, .constantsSummary th {
background:#dee3e9;
text-align:left;
padding:8px 3px 3px 7px;
}
td.colFirst, th.colFirst {
white-space:nowrap;
font-size:13px;
}
td.colLast, th.colLast {
font-size:13px;
}
td.colOne, th.colOne {
font-size:13px;
}
.overviewSummary td.colFirst, .overviewSummary th.colFirst,
.useSummary td.colFirst, .useSummary th.colFirst,
.overviewSummary td.colOne, .overviewSummary th.colOne,
.memberSummary td.colFirst, .memberSummary th.colFirst,
.memberSummary td.colOne, .memberSummary th.colOne,
.typeSummary td.colFirst{
width:25%;
vertical-align:top;
}
td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover {
font-weight:bold;
}
.tableSubHeadingColor {
background-color:#EEEEFF;
}
.altColor {
background-color:#FFFFFF;
}
.rowColor {
background-color:#EEEEEF;
}
/*
Content styles
*/
.description pre {
margin-top:0;
}
.deprecatedContent {
margin:0;
padding:10px 0;
}
.docSummary {
padding:0;
}
ul.blockList ul.blockList ul.blockList li.blockList h3 {
font-style:normal;
}
div.block {
font-size:14px;
font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif;
}
td.colLast div {
padding-top:0px;
}
td.colLast a {
padding-bottom:3px;
}
/*
Formatting effect styles
*/
.sourceLineNo {
color:green;
padding:0 30px 0 0;
}
h1.hidden {
visibility:hidden;
overflow:hidden;
font-size:10px;
}
.block {
display:block;
margin:3px 10px 2px 0px;
color:#474747;
}
.deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink,
.overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel,
.seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink {
font-weight:bold;
}
.deprecationComment, .emphasizedPhrase, .interfaceName {
font-style:italic;
}
div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase,
div.block div.block span.interfaceName {
font-style:normal;
}
div.contentContainer ul.blockList li.blockList h2{
padding-bottom:0px;
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

+1 -1
View File
@@ -5,7 +5,7 @@ description=Mixin (Fabric fork)
url=https://fabricmc.net
organization=FabricMC
buildVersion=0.9.4
upstreamMixinVersion=0.8.2
upstreamMixinVersion=0.8.3
buildType=RELEASE
asmVersion=9.1
legacyForgeAsmVersion=5.0.3
@@ -41,6 +41,7 @@ import org.spongepowered.asm.mixin.transformer.ext.IHotSwap;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.transformers.MixinClassReader;
import org.spongepowered.asm.util.asm.ASM;
/**
@@ -65,7 +66,7 @@ public class MixinAgent implements IHotSwap {
byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined);
if (mixinBytecode != null) {
ClassNode classNode = new ClassNode(ASM.API_VERSION);
ClassReader cr = new ClassReader(classfileBuffer);
ClassReader cr = new MixinClassReader(classfileBuffer, className);
cr.accept(classNode, ClassReader.EXPAND_FRAMES);
List<String> targets = this.reloadMixin(className, classNode);
@@ -128,7 +128,7 @@ class MixinAgentClassLoader extends ClassLoader {
*/
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,
cw.visit(MixinEnvironment.getCompatibilityLevel().getClassVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null,
Type.getInternalName(Object.class), null);
// create init method
@@ -24,6 +24,7 @@
*/
package org.spongepowered.tools.obfuscation;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -38,9 +39,19 @@ import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.struct.SelectorAnnotationContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.util.asm.IAnnotatedElement;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementAccessor;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementInvoker;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementSliceInjectionPoint;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite;
import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible;
@@ -55,10 +66,12 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle;
import org.spongepowered.tools.obfuscation.mirror.TypeUtils;
import org.spongepowered.tools.obfuscation.struct.InjectorRemap;
import com.google.common.base.Strings;
/**
* Information about a mixin stored during processing
*/
class AnnotatedMixin {
class AnnotatedMixin implements IMixinContext, IAnnotatedElement {
/**
* Mixin annotation
@@ -225,6 +238,10 @@ class AnnotatedMixin {
} else if (type == null) {
this.printMessage(Kind.ERROR, "Mixin target " + softTarget + " could not be found", this);
return null;
} else if (type.isImaginary()) {
this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " could not be fully resolved.", this,
SuppressedBy.UNRESOLVABLE_TARGET);
return null;
} else if (type.isPublic()) {
SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : SuppressedBy.PUBLIC_TARGET;
this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " is public and must be specified in value", this, suppressedBy);
@@ -285,7 +302,7 @@ class AnnotatedMixin {
/**
* Get the mixin class
*/
public TypeElement getMixin() {
public TypeElement getMixinElement() {
return this.mixin;
}
@@ -299,6 +316,7 @@ class AnnotatedMixin {
/**
* Get the mixin class reference
*/
@Override
public String getClassRef() {
return this.classRef;
}
@@ -365,45 +383,99 @@ class AnnotatedMixin {
public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) {
this.methods.remove(method);
this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, remap));
AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap);
this.injectors.registerInjector(injectorElement);
List<AnnotationHandle> ats = inject.getAnnotationList("at");
for (AnnotationHandle at : ats) {
this.registerInjectionPoint(method, inject, at, remap, "@At(%s)");
List<IAnnotationHandle> ats = inject.getAnnotationList("at");
for (IAnnotationHandle at : ats) {
this.registerInjectionPoint(method, inject, "at", (AnnotationHandle)at, remap, "@At(%s)");
}
List<AnnotationHandle> slices = inject.getAnnotationList("slice");
for (AnnotationHandle slice : slices) {
List<IAnnotationHandle> slices = inject.getAnnotationList("slice");
for (IAnnotationHandle slice : slices) {
String id = slice.<String>getValue("id", "");
String coord = "slice";
if (!Strings.isNullOrEmpty(id)) {
coord += "." + id;
}
SelectorAnnotationContext sliceContext = new SelectorAnnotationContext(injectorElement, slice, coord);
AnnotationHandle from = slice.getAnnotation("from");
IAnnotationHandle from = slice.getAnnotation("from");
if (from != null) {
this.registerInjectionPoint(method, inject, from, remap, "@Slice[" + id + "](from=@At(%s))");
this.registerSliceInjectionPoint(method, inject, "from", (AnnotationHandle)from, remap, "@Slice[" + id + "](from=@At(%s))",
sliceContext);
}
AnnotationHandle to = slice.getAnnotation("to");
IAnnotationHandle to = slice.getAnnotation("to");
if (to != null) {
this.registerInjectionPoint(method, inject, to, remap, "@Slice[" + id + "](to=@At(%s))");
this.registerSliceInjectionPoint(method, inject, "to", (AnnotationHandle)to, remap, "@Slice[" + id + "](to=@At(%s))", sliceContext);
}
}
}
public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap remap, String format) {
this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at, remap), format);
public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at,
InjectorRemap remap, String format) {
this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, this, selectorCoordinate, at, remap), format);
}
public void registerSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at,
InjectorRemap remap, String format, ISelectorContext parentContext) {
this.injectors.registerInjectionPoint(new AnnotatedElementSliceInjectionPoint(element, inject, this, selectorCoordinate, at, remap,
parentContext), format);
}
public void registerAccessor(ExecutableElement element, AnnotationHandle accessor, boolean shouldRemap) {
this.methods.remove(element);
this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, shouldRemap));
this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, this, shouldRemap));
}
public void registerInvoker(ExecutableElement element, AnnotationHandle invoker, boolean shouldRemap) {
this.methods.remove(element);
this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, shouldRemap));
this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, this, shouldRemap));
}
public void registerSoftImplements(AnnotationHandle implementsAnnotation) {
this.softImplements.process(implementsAnnotation);
}
@Override
public ReferenceMapper getReferenceMapper() {
return null;
}
@Override
public String getClassName() {
return this.getClassRef().replace('/', '.');
}
@Override
public String getTargetClassRef() {
return this.primaryTarget.getName();
}
@Override
public IMixinInfo getMixin() {
throw new UnsupportedOperationException("MixinInfo not available at compile time");
}
@Override
public Extensions getExtensions() {
throw new UnsupportedOperationException("Mixin Extensions not available at compile time");
}
@Override
public boolean getOption(Option option) {
throw new UnsupportedOperationException("Options not available at compile time");
}
@Override
public int getPriority() {
throw new UnsupportedOperationException("Priority not available at compile time");
}
@Override
public IAnnotationHandle getAnnotation(Class<? extends Annotation> annotationClass) {
return AnnotationHandle.of(this.mixin, annotationClass);
}
}
@@ -24,6 +24,7 @@
*/
package org.spongepowered.tools.obfuscation;
import java.lang.annotation.Annotation;
import java.util.List;
import javax.annotation.processing.Messager;
@@ -33,13 +34,17 @@ import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.obfuscation.mapping.IMapping;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.asm.IAnnotatedElement;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.asm.util.throwables.ConstraintViolationException;
import org.spongepowered.asm.util.throwables.InvalidConstraintException;
import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible;
@@ -64,7 +69,7 @@ abstract class AnnotatedMixinElementHandler {
*
* @param <E> type of inner element
*/
abstract static class AnnotatedElement<E extends Element> {
abstract static class AnnotatedElement<E extends Element> implements IAnnotatedElement {
protected final E element;
@@ -102,8 +107,72 @@ abstract class AnnotatedMixinElementHandler {
messager.printMessage(kind, msg, this.element, this.annotation.asMirror(), suppressedBy);
}
@Override
public IAnnotationHandle getAnnotation(Class<? extends Annotation> annotationClass) {
return AnnotationHandle.of(this.element, annotationClass);
}
}
abstract static class AnnotatedElementExecutable extends AnnotatedElement<ExecutableElement> implements ISelectorContext {
private final IMixinContext context;
private final String selectorCoordinate;
public AnnotatedElementExecutable(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, String selectorCoordinate) {
super(element, annotation);
this.context = context;
this.selectorCoordinate = selectorCoordinate;
}
@Override
public ISelectorContext getParent() {
return null;
}
@Override
public IMixinContext getMixin() {
return this.context;
}
@Override
public Object getMethod() {
return new IAnnotatedElement() {
@Override
public IAnnotationHandle getAnnotation(Class<? extends Annotation> annotationClass) {
return AnnotationHandle.of(AnnotatedElementExecutable.this.getElement(), annotationClass);
}
@Override
public String toString() {
return AnnotatedElementExecutable.this.getElement().getSimpleName().toString();
}
};
}
@Override
public IAnnotationHandle getSelectorAnnotation() {
return this.getAnnotation();
}
@Override
public String getSelectorCoordinate(boolean leaf) {
return leaf ? this.selectorCoordinate : TypeUtils.getName(this.element);
}
@Override
public String remap(String reference) {
return reference;
}
@Override
public String toString() {
return TypeUtils.getName(this.element);
}
}
/**
* A name of an element which may have aliases
*/
@@ -486,12 +555,12 @@ abstract class AnnotatedMixinElementHandler {
* Checks whether the referenced method exists in all targets and raises
* warnings where appropriate
*/
protected final void validateReferencedTarget(ExecutableElement method, AnnotationHandle inject, ITargetSelector reference, String type) {
if (!(reference instanceof ITargetSelectorByName)) {
protected final void validateReferencedTarget(AnnotatedElementExecutable elem, String reference, ITargetSelector targetSelector, String subject) {
if (!(targetSelector instanceof ITargetSelectorByName)) {
return;
}
ITargetSelectorByName nameRef = (ITargetSelectorByName)reference;
ITargetSelectorByName nameRef = (ITargetSelectorByName)targetSelector;
String signature = nameRef.toDescriptor();
for (TypeHandle target : this.mixin.getTargets()) {
@@ -501,8 +570,8 @@ abstract class AnnotatedMixinElementHandler {
MethodHandle targetMethod = target.findMethod(nameRef.getName(), signature);
if (targetMethod == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(),
SuppressedBy.TARGET);
this.ap.printMessage(Kind.WARNING, "Cannot find target method \"" + nameRef.getName() + nameRef.getDesc() + "\" for " + subject
+ " in " + target, elem.getElement(), elem.getAnnotation().asMirror(), SuppressedBy.TARGET);
}
}
}
@@ -30,18 +30,12 @@ import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.gen.AccessorInfo;
import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorName;
import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorType;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.Constants;
@@ -60,21 +54,21 @@ import com.google.common.base.Strings;
/**
* A module for {@link AnnotatedMixin} which handles accessors
*/
public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler implements IMixinContext {
class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler {
/**
* Accessor element
*/
static class AnnotatedElementAccessor extends AnnotatedElement<ExecutableElement> {
static class AnnotatedElementAccessor extends AnnotatedElementExecutable {
protected final boolean shouldRemap;
protected final TypeMirror returnType;
protected String targetName;
public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) {
super(element, annotation);
public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) {
super(element, annotation, context, "value");
this.shouldRemap = shouldRemap;
this.returnType = this.getElement().getReturnType();
}
@@ -105,12 +99,12 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
return TypeUtils.getTypeName(this.getTargetType());
}
public String getAccessorDesc() {
public String getTargetDesc() {
return TypeUtils.getInternalName(this.getTargetType());
}
public ITargetSelectorRemappable getContext() {
return new MemberInfo(this.getTargetName(), null, this.getAccessorDesc());
return new MemberInfo(this.getTargetName(), null, this.getTargetDesc());
}
public AccessorType getAccessorType() {
@@ -147,8 +141,8 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
private AccessorType type = AccessorType.METHOD_PROXY;
public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) {
super(element, annotation, shouldRemap);
public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) {
super(element, annotation, context, shouldRemap);
}
@Override
@@ -186,8 +180,8 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
}
@Override
public String getAccessorDesc() {
return TypeUtils.getDescriptor(this.getElement());
public String getTargetDesc() {
return this.getDesc();
}
@Override
@@ -201,56 +195,11 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
}
}
public AnnotatedMixinElementHandlerAccessor(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
}
@Override
public ReferenceMapper getReferenceMapper() {
return null;
}
@Override
public String getClassName() {
return this.mixin.getClassRef().replace('/', '.');
}
@Override
public String getClassRef() {
return this.mixin.getClassRef();
}
@Override
public String getTargetClassRef() {
throw new UnsupportedOperationException("Target class not available at compile time");
}
@Override
public IMixinInfo getMixin() {
throw new UnsupportedOperationException("MixinInfo not available at compile time");
}
@Override
public Extensions getExtensions() {
throw new UnsupportedOperationException("Mixin Extensions not available at compile time");
}
@Override
public boolean getOption(Option option) {
throw new UnsupportedOperationException("Options not available at compile time");
}
@Override
public int getPriority() {
throw new UnsupportedOperationException("Priority not available at compile time");
}
@Override
public Target getTargetMethod(MethodNode into) {
throw new UnsupportedOperationException("Target not available at compile time");
}
/**
* Register a new accessor
*
@@ -294,7 +243,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
return;
}
targetField = new FieldHandle(target.getName(), elem.getTargetName(), elem.getDesc());
targetField = new FieldHandle(target.getName(), elem.getTargetName(), elem.getTargetDesc());
}
if (!elem.shouldRemap()) {
@@ -326,7 +275,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
return;
}
targetMethod = new MethodHandle(target, elem.getTargetName(), elem.getDesc());
targetMethod = new MethodHandle(target, elem.getTargetName(), elem.getTargetDesc());
}
if (!elem.shouldRemap()) {
@@ -387,7 +336,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH
}
private String inflectAccessorTarget(AnnotatedElementAccessor elem) {
return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", this, false);
return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", elem, false);
}
}
@@ -35,15 +35,18 @@ import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException;
import org.spongepowered.tools.obfuscation.ext.SpecialPackages;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
@@ -61,12 +64,12 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
/**
* Injector element
*/
static class AnnotatedElementInjector extends AnnotatedElement<ExecutableElement> {
static class AnnotatedElementInjector extends AnnotatedElementExecutable {
private final InjectorRemap state;
public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, InjectorRemap shouldRemap) {
super(element, annotation);
public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, InjectorRemap shouldRemap) {
super(element, annotation, context, "method");
this.state = shouldRemap;
}
@@ -100,7 +103,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
/**
* Injection point element
*/
static class AnnotatedElementInjectionPoint extends AnnotatedElement<ExecutableElement> {
static class AnnotatedElementInjectionPoint extends AnnotatedElementExecutable {
private final AnnotationHandle at;
@@ -108,8 +111,9 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
private final InjectorRemap state;
public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap state) {
super(element, inject);
public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context, String selectorCoordinate,
AnnotationHandle at, InjectorRemap state) {
super(element, inject, context, selectorCoordinate);
this.at = at;
this.state = state;
}
@@ -121,7 +125,17 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
public AnnotationHandle getAt() {
return this.at;
}
public AnnotationMirror getAtErrorElement(CompilerEnvironment compilerEnvironment) {
// JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work
return (compilerEnvironment == CompilerEnvironment.JDT ? this.getAt() : this.getAnnotation()).asMirror();
}
@Override
public IAnnotationHandle getSelectorAnnotation() {
return this.getAt();
}
public String getAtArg(String key) {
if (this.args == null) {
this.args = new HashMap<String, String>();
@@ -147,39 +161,61 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
}
static class AnnotatedElementSliceInjectionPoint extends AnnotatedElementInjectionPoint {
private final ISelectorContext parentContext;
public AnnotatedElementSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context,
String selectorCoordinate, AnnotationHandle at, InjectorRemap state, ISelectorContext parentContext) {
super(element, inject, context, selectorCoordinate, at, state);
this.parentContext = parentContext;
}
@Override
public ISelectorContext getParent() {
return this.parentContext;
}
}
AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
}
public void registerInjector(AnnotatedElementInjector elem) {
for (String reference : elem.getAnnotation().<String>getList("method")) {
ITargetSelector targetSelector = TargetSelector.parse(reference);
try {
targetSelector.validate();
} catch (InvalidMemberDescriptorException ex) {
elem.printMessage(this.ap, Kind.ERROR, ex.getMessage());
}
this.registerInjectorTarget(elem, reference, TargetSelector.parse(reference, elem), elem + ".method=\"" + reference + "\"");
}
if (!(targetSelector instanceof ITargetSelectorRemappable)) {
continue;
}
ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector;
if (targetMember.getName() == null) {
continue;
}
if (targetMember.getDesc() != null) {
this.validateReferencedTarget(elem.getElement(), elem.getAnnotation(), targetMember, elem.toString());
}
if (!elem.shouldRemap()) {
continue;
}
for (IAnnotationHandle desc : elem.getAnnotation().getAnnotationList("target")) {
String subject = String.format("%s.target=@Desc(id = \"%s\")", elem, desc.<String>getValue("id", ""));
this.registerInjectorTarget(elem, null, TargetSelector.parse(desc, elem), subject);
}
}
private void registerInjectorTarget(AnnotatedElementInjector elem, String reference, ITargetSelector targetSelector, String subject) {
try {
targetSelector.validate();
} catch (InvalidSelectorException ex) {
elem.printMessage(this.ap, Kind.ERROR, ex.getMessage());
}
if (!(targetSelector instanceof ITargetSelectorByName)) {
return;
}
ITargetSelectorByName targetMember = (ITargetSelectorByName)targetSelector;
if (targetMember.getName() == null) {
return;
}
if (targetMember.getDesc() != null) {
this.validateReferencedTarget(elem, reference, targetMember, subject);
}
if (targetSelector instanceof ITargetSelectorRemappable && elem.shouldRemap()) {
for (TypeHandle target : this.mixin.getTargets()) {
if (!this.registerInjector(elem, reference, targetMember, target)) {
if (!this.registerInjector(elem, reference, (ITargetSelectorRemappable)targetMember, target)) {
break;
}
}
@@ -191,7 +227,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
if (desc == null) {
Kind error = this.mixin.isMultiTarget() ? Kind.ERROR : Kind.WARNING;
if (target.isSimulated()) {
elem.printMessage(this.ap, Kind.NOTE, elem + " target '" + reference + "' in @Pseudo mixin will not be obfuscated");
elem.printMessage(this.ap, Kind.OTHER, elem + " target '" + reference + "' in @Pseudo mixin will not be obfuscated");
} else if (target.isImaginary()) {
elem.printMessage(this.ap, error, elem + " target requires method signature because enclosing type information for "
+ target + " is unavailable");
@@ -227,8 +263,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
String conflictType = this.mixin.isMultiTarget() ? "Multi-target" : "Target";
if (elem.hasCoerceArgument() && targetMember.getOwner() == null && targetMember.getDesc() == null) {
ITargetSelector oldMember = TargetSelector.parse(ex.getOld());
ITargetSelector newMember = TargetSelector.parse(ex.getNew());
ITargetSelector oldMember = TargetSelector.parse(ex.getOld(), elem);
ITargetSelector newMember = TargetSelector.parse(ex.getNew(), elem);
String oldName = oldMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)oldMember).getName() : oldMember.toString();
String newName = newMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)newMember).getName() : newMember.toString();
if (oldName != null && oldName.equals(newName)) {
@@ -256,91 +292,95 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
* and process the references
*/
public void registerInjectionPoint(AnnotatedElementInjectionPoint elem, String format) {
if (!elem.shouldRemap()) {
return;
ITargetSelector targetSelector = null;
String targetReference = elem.getAt().<String>getValue("target");
if (targetReference != null) {
targetSelector = TargetSelector.parse(targetReference, elem);
try {
targetSelector.validate();
} catch (InvalidSelectorException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment()));
}
}
String type = InjectionPointData.parseType(elem.getAt().<String>getValue("value"));
String target = elem.getAt().<String>getValue("target");
String type = InjectionPointData.parseType(elem.getAt().<String>getValue("value", ""));
ITargetSelector classSelector = null;
String classReference = elem.getAtArg("class");
if ("NEW".equals(type) && classReference != null) {
classSelector = TargetSelector.parse(classReference, elem);
try {
classSelector.validate();
} catch (InvalidSelectorException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment()));
}
}
if ("NEW".equals(type)) {
this.remapNewTarget(String.format(format, type + ".<target>"), target, elem);
this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem);
} else {
this.remapReference(String.format(format, type + ".<target>"), target, elem);
if (elem.shouldRemap()) {
if ("NEW".equals(type)) {
this.remapNewTarget(String.format(format, type + ".<target>"), targetReference, targetSelector, elem);
this.remapNewTarget(String.format(format, type + ".args[class]"), classReference, classSelector, elem);
} else {
this.remapReference(String.format(format, type + ".<target>"), targetReference, targetSelector, elem);
}
}
}
protected final void remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) {
if (reference == null) {
protected final void remapNewTarget(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) {
if (!(selector instanceof ITargetSelectorConstructor)) {
return;
}
ITargetSelector selector = TargetSelector.parse(reference);
if (selector instanceof ITargetSelectorConstructor) {
ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector;
String target = member.toCtorType();
if (target != null) {
String desc = member.toCtorDesc();
MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V");
ObfuscationData<MappingMethod> remapped = this.obf.getDataProvider().getRemappedMethod(m);
if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) {
this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(),
elem.getAnnotation().asMirror(), SuppressedBy.MAPPING);
return;
}
ObfuscationData<String> mappings = new ObfuscationData<String>();
for (ObfuscationType type : remapped) {
MappingMethod mapping = remapped.get(type);
if (desc == null) {
mappings.put(type, mapping.getOwner());
} else {
mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";"));
}
}
this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings);
ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector;
String target = member.toCtorType();
if (target != null) {
String desc = member.toCtorDesc();
MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V");
ObfuscationData<MappingMethod> remapped = this.obf.getDataProvider().getRemappedMethod(m);
if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) {
this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(),
elem.getAnnotation().asMirror(), SuppressedBy.MAPPING);
return;
}
ObfuscationData<String> mappings = new ObfuscationData<String>();
for (ObfuscationType type : remapped) {
MappingMethod mapping = remapped.get(type);
if (desc == null) {
mappings.put(type, mapping.getOwner());
} else {
mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";"));
}
}
this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings);
}
elem.notifyRemapped();
}
protected final void remapReference(String subject, String reference, AnnotatedElementInjectionPoint elem) {
if (reference == null) {
protected final void remapReference(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) {
if (!(selector instanceof ITargetSelectorRemappable)) {
return;
}
ITargetSelector targetSelector = TargetSelector.parse(reference);
if (!(targetSelector instanceof ITargetSelectorRemappable)) {
return;
}
ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector;
// JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work
AnnotationMirror errorsOn = (this.ap.getCompilerEnvironment() == CompilerEnvironment.JDT ? elem.getAt() : elem.getAnnotation()).asMirror();
ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)selector;
AnnotationMirror errorElement = elem.getAtErrorElement(this.ap.getCompilerEnvironment());
if (!targetMember.isFullyQualified()) {
String missing = targetMember.getOwner() == null ? (targetMember.getDesc() == null ? "owner and signature" : "owner") : "signature";
this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorsOn);
this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorElement);
return;
}
try {
targetMember.validate();
} catch (InvalidMemberDescriptorException ex) {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), errorsOn);
}
try {
if (targetMember.isField()) {
ObfuscationData<MappingField> obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember);
if (obfFieldData.isEmpty()) {
if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) {
this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(),
errorsOn, SuppressedBy.MAPPING);
errorElement, SuppressedBy.MAPPING);
}
return;
}
@@ -350,7 +390,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
if (obfMethodData.isEmpty()) {
if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) {
this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(),
errorsOn, SuppressedBy.MAPPING);
errorElement, SuppressedBy.MAPPING);
}
return;
}
@@ -360,7 +400,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
// Since references are fully-qualified, it shouldn't be possible for there to be multiple mappings, however
// we catch and log the error in case something weird happens in the mapping provider
this.ap.printMessage(Kind.ERROR, "Unexpected reference conflict for " + subject + ": " + reference + " -> "
+ ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorsOn);
+ ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorElement);
return;
}
@@ -33,6 +33,7 @@ import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Interface.Remap;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle;
import org.spongepowered.tools.obfuscation.mirror.MethodHandle;
@@ -42,7 +43,7 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle;
/**
* A module for {@link AnnotatedMixin} whic handles soft-implements clauses
*/
public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler {
class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler {
AnnotatedMixinElementHandlerSoftImplements(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
@@ -63,15 +64,15 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl
return;
}
List<AnnotationHandle> interfaces = implementsAnnotation.getAnnotationList("value");
List<IAnnotationHandle> interfaces = implementsAnnotation.getAnnotationList("value");
// Derp?
if (interfaces.size() < 1) {
this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixin(), implementsAnnotation.asMirror());
this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixinElement(), implementsAnnotation.asMirror());
return;
}
for (AnnotationHandle interfaceAnnotation : interfaces) {
for (IAnnotationHandle interfaceAnnotation : interfaces) {
Remap remap = interfaceAnnotation.<Remap>getValue("remap", Remap.ALL);
if (remap == Remap.NONE) {
continue;
@@ -82,8 +83,8 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl
String prefix = interfaceAnnotation.<String>getValue("prefix");
this.processSoftImplements(remap, iface, prefix);
} catch (Exception ex) {
this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), this.mixin.getMixin(),
interfaceAnnotation.asMirror());
this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(),
this.mixin.getMixinElement(), ((AnnotationHandle)interfaceAnnotation).asMirror());
}
}
}
@@ -139,13 +139,19 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
*/
private Properties properties;
/**
* No informational messages, I'm hunting wabbits
*/
private boolean beVewyVewyQuiet;
/**
* Private constructor, get instances using {@link #getMixinsForEnvironment}
*/
private AnnotatedMixins(ProcessingEnvironment processingEnv) {
this.env = this.detectEnvironment(processingEnv);
this.processingEnv = processingEnv;
this.beVewyVewyQuiet = this.env == CompilerEnvironment.JDT || "true".equalsIgnoreCase(this.getOption(SupportedOptions.QUIET));
MessageRouter.setMessager(processingEnv.getMessager());
String pluginVersion = this.checkPluginVersion(this.getOption(SupportedOptions.PLUGIN_VERSION));
@@ -557,7 +563,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
public void printMessage(Kind kind, CharSequence msg) {
if (kind == Kind.OTHER) return;
if (this.env == CompilerEnvironment.JAVAC || kind != Kind.NOTE) {
if (!this.beVewyVewyQuiet || kind != Kind.NOTE) {
this.processingEnv.getMessager().printMessage(kind, msg);
}
}
@@ -626,7 +632,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
name = name.replace('/', '.');
Elements elements = this.processingEnv.getElementUtils();
TypeElement element = elements.getTypeElement(name);
TypeElement element = this.getTypeElement(name, elements);
if (element != null) {
try {
return new TypeHandle(element);
@@ -647,6 +653,66 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
return null;
}
/**
* Get a TypeElement representing another type in the current processing
* environment. This method attempts substitution of '$' symbols appearing
* in the class name when requesting TypeElements from the processing env.
*/
public TypeElement getTypeElement(String name) {
return this.getTypeElement(name.replace('/', '.'), this.processingEnv.getElementUtils());
}
private TypeElement getTypeElement(String name, Elements elements) {
// Try fetching directly first
TypeElement element = elements.getTypeElement(name);
if (element != null || name.indexOf('$') < 0) {
return element;
}
int lastDotPos = name.lastIndexOf('.');
String pkg = lastDotPos > -1 ? name.substring(0, lastDotPos) : "";
name = name.substring(pkg.length());
// Name has '$' in it, try naive replacement first, this will work for
// most cases where there is a single '$' symbol
element = elements.getTypeElement(pkg + name.replace('$', '.'));
if (element != null) {
return element;
}
char[] source = name.toCharArray();
char[] dest = new char[source.length];
int occurs = 0;
for (int offset = 0; offset < source.length; offset++) {
if (source[offset] == '$') {
occurs++;
}
}
// Ok someone is trolling if there are more than 10 '$' symbols in a
// name! 10 is an arbitary number, we could do more but the loop below
// is expensive and something horrible is probably happening if there
// are that many '$' signs. We can also skip here if occurs < 2 because
// we already tested that case above when we replaced "all"
if (occurs > 10 || occurs < 2) {
return null;
}
// Try all possible combinations of replacing '$' with '.' starting at
// the end of the string. Not really ideal but if we haven't resolved
// the class name by replacing all '$' with '.' then this is our only
// remaining approach.
for (int mask = 1; mask < 1 << occurs && element == null; mask++) {
for (int offset = source.length - 1, index = 0; offset >= 0; offset--) {
dest[offset] = (source[offset] == '$' && (mask & (1 << index++)) != 0) ? '.' : source[offset];
}
element = elements.getTypeElement(pkg + new String(dest));
}
return element;
}
/**
* Returns a simulated TypeHandle for a non-existing type
*/
@@ -40,7 +40,7 @@ import org.spongepowered.asm.mixin.Mixin;
/**
* Base class for mixin annotation processor modules
*/
public abstract class MixinObfuscationProcessor extends AbstractProcessor {
abstract class MixinObfuscationProcessor extends AbstractProcessor {
/**
* Mixin info manager
@@ -37,7 +37,6 @@ import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.ObfuscationUtil;
@@ -281,7 +280,7 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment
}
}
return transformed ? new MemberInfo(method.getName(), owner, desc, method.getMatchCount() > 1) : null;
return transformed ? method.move(owner).transform(desc) : null;
}
/**
@@ -47,6 +47,7 @@ public final class SupportedOptions {
public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile";
public static final String MAPPING_TYPES = "mappingTypes";
public static final String PLUGIN_VERSION = "pluginVersion";
public static final String QUIET = "quiet";
private SupportedOptions() {}
@@ -65,7 +66,8 @@ public final class SupportedOptions {
SupportedOptions.DEFAULT_OBFUSCATION_ENV,
SupportedOptions.DEPENDENCY_TARGETS_FILE,
SupportedOptions.MAPPING_TYPES,
SupportedOptions.PLUGIN_VERSION
SupportedOptions.PLUGIN_VERSION,
SupportedOptions.QUIET
);
options.addAll(
ObfuscationServices.getInstance().getSupportedOptions()
@@ -24,6 +24,8 @@
*/
package org.spongepowered.tools.obfuscation;
import org.spongepowered.asm.mixin.Overwrite;
/**
* A centralised list of tokens supported by the AP for use in
* {@link SuppressWarnings} annotations. Collected here mainly for
@@ -33,45 +35,79 @@ public enum SuppressedBy {
/**
* Suppress warnings for constraint violations
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'constraints'</i>)</b></code>
* </div>
*/
CONSTRAINTS("constraints"),
/**
* Suppress warnings about overwrite visibility upgrading/downgrading target
* visibility
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'visibility'</i>)</b></code>
* </div>
*/
VISIBILITY("visibility"),
/**
* Suppress warnings when an injector target cannot be found
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'target'</i>)</b></code>
* </div>
*/
TARGET("target"),
/**
* Suppress warnings when a class, method or field mapping cannot be located
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'mapping'</i>)</b></code>
* </div>
*/
MAPPING("mapping"),
/**
* Suppress warnings for when an <tt>&#064;Overwrite</tt> method is missing
* javadoc, or author or reason tags
* Suppress warnings for when an {@link Overwrite &#064;Overwrite} method is
* missing javadoc, or author or reason tags
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'overwrite'</i>)</b></code>
* </div>
*/
OVERWRITE("overwrite"),
/**
* Suppress warnings when a mixin target specified by name is located in the
* default package
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'default-package'</i>)</b></code>
* </div>
*/
DEFAULT_PACKAGE("default-package"),
/**
* Suppress warnings when a mixin target is resolved by the AP as visible
* but cannot be referenced with a class literal for some reason
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'public-target'</i>)</b></code>
* </div>
*/
PUBLIC_TARGET("public-target"),
/**
* Suppress warning when a mixin target is resolved by the AP as imaginary
* (unresolvable via Mirror at compile time), for example for anonymous
* inner classes or other synthetic member classes
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'unresolvable-target'</i>)</b></code>
* </div>
*/
UNRESOLVABLE_TARGET("unresolvable-target"),
/**
* The default java "raw types" suppressions
* <div class="example">Usage:
* <code><b>&#64;SuppressWarnings(<i>'rawtypes'</i>)</b></code>
* </div>
*/
RAW_TYPES("rawtypes");
@@ -65,7 +65,7 @@ public class MappingProviderTSrg extends MappingProvider {
this.inputMappings.addAll(Files.readLines(input, Charset.defaultCharset()));
for (String line : this.inputMappings) {
if (Strings.isNullOrEmpty(line) || line.startsWith("#")) {
if (Strings.isNullOrEmpty(line) || line.startsWith("#") || line.startsWith("tsrg2") || line.startsWith("\t\t")) {
continue;
}
@@ -28,6 +28,7 @@ import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
@@ -35,6 +36,10 @@ import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import org.objectweb.asm.Type;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.collect.ImmutableList;
@@ -42,7 +47,7 @@ import com.google.common.collect.ImmutableList;
* A wrapper for {@link AnnotationMirror} which provides a more convenient way
* to access annotation values.
*/
public final class AnnotationHandle {
public final class AnnotationHandle implements IAnnotationHandle {
public static final AnnotationHandle MISSING = new AnnotationHandle(null);
@@ -75,10 +80,22 @@ public final class AnnotationHandle {
*
* @return true if the annotation exists
*/
@Override
public boolean exists() {
return this.annotation != null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.util.asm.IAnnotationHandle#getDesc()
*/
@Override
public String getDesc() {
if (this.annotation == null) {
return "java/lang/Annotation";
}
return TypeUtils.getInternalName(this.annotation.getAnnotationType());
}
@Override
public String toString() {
if (this.annotation == null) {
@@ -96,6 +113,7 @@ public final class AnnotationHandle {
* @return value or default if not set
* @param <T> duck type
*/
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T getValue(String key, T defaultValue) {
if (this.annotation == null) {
@@ -120,6 +138,7 @@ public final class AnnotationHandle {
* @param <T> duck type
* @return value or null if not present or not set
*/
@Override
public <T> T getValue() {
return this.getValue("value", null);
}
@@ -132,6 +151,7 @@ public final class AnnotationHandle {
* @param <T> duck type
* @return value or null if not present or not set
*/
@Override
public <T> T getValue(String key) {
return this.getValue(key, null);
}
@@ -154,7 +174,8 @@ public final class AnnotationHandle {
* @param key key to search for in the value map
* @return value or <tt>null</tt> if not set
*/
public AnnotationHandle getAnnotation(String key) {
@Override
public IAnnotationHandle getAnnotation(String key) {
Object value = this.getValue(key);
if (value instanceof AnnotationMirror) {
return AnnotationHandle.of((AnnotationMirror)value);
@@ -187,6 +208,7 @@ public final class AnnotationHandle {
* @param <T> list element duck type
* @return list of values
*/
@Override
public <T> List<T> getList(String key) {
List<AnnotationValue> list = this.<List<AnnotationValue>>getValue(key, Collections.<AnnotationValue>emptyList());
return AnnotationHandle.<T>unwrapAnnotationValueList(list);
@@ -198,15 +220,16 @@ public final class AnnotationHandle {
* @param key key to fetch
* @return list of annotations
*/
public List<AnnotationHandle> getAnnotationList(String key) {
@Override
public List<IAnnotationHandle> getAnnotationList(String key) {
Object val = this.getValue(key, null);
if (val == null) {
return Collections.<AnnotationHandle>emptyList();
return Collections.<IAnnotationHandle>emptyList();
}
// Fix for JDT, single values are just returned as a bare AnnotationMirror
if (val instanceof AnnotationMirror) {
return ImmutableList.<AnnotationHandle>of(AnnotationHandle.of((AnnotationMirror)val));
return ImmutableList.<IAnnotationHandle>of(AnnotationHandle.of((AnnotationMirror)val));
}
@SuppressWarnings("unchecked") List<AnnotationValue> list = (List<AnnotationValue>)val;
@@ -214,7 +237,25 @@ public final class AnnotationHandle {
for (AnnotationValue value : list) {
annotations.add(new AnnotationHandle((AnnotationMirror)value.getValue()));
}
return Collections.<AnnotationHandle>unmodifiableList(annotations);
return Collections.<IAnnotationHandle>unmodifiableList(annotations);
}
@Override
public Type getTypeValue(String key) {
TypeMirror typeMirror = this.<TypeMirror>getValue(key);
return typeMirror == null ? Type.VOID_TYPE : Type.getType(TypeUtils.getInternalName(typeMirror));
}
@Override
public List<Type> getTypeList(String key) {
List<Type> list = this.<Type>getList(key);
for (ListIterator<Type> iter = list.listIterator(); iter.hasNext();) {
Object next = iter.next();
if (next instanceof TypeMirror) {
iter.set(Type.getType(TypeUtils.getInternalName((TypeMirror)next)));
}
}
return list;
}
protected AnnotationValue getAnnotationValue(String key) {
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Base package for the Mixin Annotation Processor.
*/
package org.spongepowered.tools.obfuscation;
@@ -79,7 +79,7 @@ public class MappingWriterJson extends MappingWriter {
try {
writer = this.openFileWriter(output, type + " output");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
gson.toJson(mappings, writer);
} catch (IOException ex) {
ex.printStackTrace();
@@ -140,11 +140,7 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl
@Override
public AcceptResult accept(MixinPlatformManager manager, IContainerHandle handle) {
try {
this.clCoreModManager = MixinPlatformAgentFMLLegacy.getCoreModManagerClass();
} catch (ClassNotFoundException ex) {
MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.",
ex.getMessage());
if (this.getCoreModManagerClass() == null) {
return AcceptResult.INVALID;
}
@@ -298,30 +294,6 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl
public void prepare() {
this.initInjectionState |= MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_INJECTION);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinPlatformAgent
* #initPrimaryContainer()
*/
@Override
public void initPrimaryContainer() {
if (this.clCoreModManager != null) {
// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider");
this.injectRemapper();
}
}
private void injectRemapper() {
try {
MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS);
Class<?> clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFMLLegacy.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.platform.IMixinPlatformAgent#inject()
@@ -357,6 +329,30 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl
return !MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_DEOBF);
}
/**
* Attempt to get the FML CoreModManager, tries the post-1.8 namespace first
* and falls back to 1.7.10 if class lookup fails
*/
private Class<?> getCoreModManagerClass() {
if (this.clCoreModManager != null) {
return this.clCoreModManager;
}
try {
try {
this.clCoreModManager = Class.forName(GlobalProperties.getString(
GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS));
} catch (ClassNotFoundException ex) {
this.clCoreModManager = Class.forName(MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS_LEGACY);
}
} catch (ClassNotFoundException ex) {
MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.",
ex.getMessage());
}
return this.clCoreModManager;
}
/**
* Check whether a tweaker ending with <tt>tweakName</tt> has been enqueued
* but not yet visited.
@@ -373,19 +369,6 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl
return false;
}
/**
* Attempt to get the FML CoreModManager, tries the post-1.8 namespace first
* and falls back to 1.7.10 if class lookup fails
*/
private static Class<?> getCoreModManagerClass() throws ClassNotFoundException {
try {
return Class.forName(GlobalProperties.getString(
GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS));
} catch (ClassNotFoundException ex) {
return Class.forName(MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS_LEGACY);
}
}
@SuppressWarnings("unchecked")
private static List<String> getIgnoredMods(Class<?> clCoreModManager) throws IllegalAccessException, InvocationTargetException {
Method mdGetIgnoredMods = null;
@@ -412,7 +395,22 @@ public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract impl
*/
@Override
public void init() {
// Nothing to do here
if (this.getCoreModManagerClass() != null) {
// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider");
this.injectRemapper();
}
}
private void injectRemapper() {
try {
MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS);
Class<?> clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFMLLegacy.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)
@@ -38,14 +38,14 @@ import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.launch.GlobalProperties;
import org.spongepowered.asm.launch.GlobalProperties.Keys;
import org.spongepowered.asm.launch.platform.MainAttributes;
import org.spongepowered.asm.launch.platform.container.IContainerHandle;
import org.spongepowered.asm.launch.platform.container.ContainerHandleURI;
import org.spongepowered.asm.launch.platform.container.ContainerHandleVirtual;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.launch.platform.container.IContainerHandle;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
@@ -58,15 +58,16 @@ import org.spongepowered.asm.service.IMixinAuditTrail;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.ITransformerProvider;
import org.spongepowered.asm.service.MixinServiceAbstract;
import org.spongepowered.asm.transformers.MixinClassReader;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.common.collect.ImmutableList.Builder;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
@@ -81,7 +82,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
public static final Keys BLACKBOARD_KEY_TWEAKCLASSES = Keys.of("TweakClasses");
public static final Keys BLACKBOARD_KEY_TWEAKS = Keys.of("Tweaks");
private static final String MIXIN_TWEAKER_CLASS = "org.spongepowered.asm.launch.MixinTweaker";
private static final String MIXIN_TWEAKER_CLASS = MixinServiceAbstract.LAUNCH_PACKAGE + "MixinTweaker";
// Consts
private static final String STATE_TWEAKER = MixinServiceAbstract.MIXIN_PACKAGE + "EnvironmentStateTweaker";
@@ -576,7 +577,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
*/
@Override
public ClassNode getClassNode(String className) throws ClassNotFoundException, IOException {
return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES);
return this.getClassNode(className, this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES);
}
/* (non-Javadoc)
@@ -585,7 +586,7 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
*/
@Override
public ClassNode getClassNode(String className, boolean runTransformers) throws ClassNotFoundException, IOException {
return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES);
return this.getClassNode(className, this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES);
}
/**
@@ -595,9 +596,9 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
* @param flags ClassReader flags
* @return ASM Tree view of the specified class
*/
private ClassNode getClassNode(byte[] classBytes, int flags) {
private ClassNode getClassNode(String className, byte[] classBytes, int flags) {
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(classBytes);
ClassReader classReader = new MixinClassReader(classBytes, className);
classReader.accept(classNode, flags);
return classNode;
}
@@ -618,5 +619,5 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
return 0;
}
}
@@ -35,6 +35,7 @@ import net.minecraft.launchwrapper.Launch;
public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstrap {
private static final String SERVICE_PACKAGE = "org.spongepowered.asm.service.";
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
private static final String MIXIN_UTIL_PACKAGE = "org.spongepowered.asm.util.";
private static final String LEGACY_ASM_PACKAGE = "org.spongepowered.asm.lib.";
@@ -61,7 +62,8 @@ public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstra
// Essential ones
Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.SERVICE_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.LAUNCH_PACKAGE);
// Important ones
Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.ASM_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.LEGACY_ASM_PACKAGE);
@@ -24,6 +24,8 @@
*/
package org.spongepowered.asm.launch;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
@@ -32,6 +34,9 @@ import org.spongepowered.asm.launch.platform.CommandLineOptions;
import org.spongepowered.asm.launch.platform.MixinPlatformManager;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.service.IMixinInternal;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
/**
@@ -61,13 +66,19 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.8.2";
public static final String VERSION = "0.8.3";
/**
* Transformer factory
*/
private static final String MIXIN_TRANSFORMER_FACTORY_CLASS = "org.spongepowered.asm.mixin.transformer.MixinTransformer$Factory";
/**
* Log all the things
*/
private static final Logger logger = LogManager.getLogger("mixin");
// These are Klass local, with luck this shouldn't be a problem
private static boolean initialised = false;
private static boolean initState = true;
@@ -77,7 +88,7 @@ public abstract class MixinBootstrap {
MixinService.boot();
MixinService.getService().prepare();
}
/**
* Platform manager instance
*/
@@ -134,6 +145,7 @@ public abstract class MixinBootstrap {
}
MixinBootstrap.registerSubsystem(MixinBootstrap.VERSION);
MixinBootstrap.offerInternals();
if (!MixinBootstrap.initialised) {
MixinBootstrap.initialised = true;
@@ -207,4 +219,31 @@ public abstract class MixinBootstrap {
GlobalProperties.put(GlobalProperties.Keys.INIT, version);
}
private static void offerInternals() {
IMixinService service = MixinService.getService();
try {
for (IMixinInternal internal : MixinBootstrap.getInternals()) {
service.offer(internal);
}
} catch (AbstractMethodError ex) {
// outdated service
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static List<IMixinInternal> getInternals() throws MixinError {
List<IMixinInternal> internals = new ArrayList<IMixinInternal>();
try {
Class<IMixinInternal> clTransformerFactory = (Class<IMixinInternal>)Class.forName(MixinBootstrap.MIXIN_TRANSFORMER_FACTORY_CLASS);
Constructor<IMixinInternal> ctor = clTransformerFactory.getDeclaredConstructor();
ctor.setAccessible(true);
internals.add(ctor.newInstance());
} catch (ReflectiveOperationException ex) {
throw new MixinError(ex);
}
return internals;
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Classes which support environment-agnostic launch logic for the Mixin
* subsystem and base classes and interfaces for environment-specific adapters.
*/
package org.spongepowered.asm.launch;
@@ -80,7 +80,7 @@ public class MixinConnectorManager {
}
try {
IMixinConnector connector = connectorClass.newInstance();
IMixinConnector connector = connectorClass.getDeclaredConstructor().newInstance();
this.connectors.add(connector);
MixinConnectorManager.logger.info("Successfully loaded Mixin Connector [" + connectorClassName + "]");
} catch (ReflectiveOperationException ex) {
@@ -28,6 +28,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -69,7 +70,7 @@ public class MixinContainer {
String simpleName = clazz.getSimpleName();
MixinContainer.logger.debug("Instancing new {} for {}", simpleName, this.handle);
IMixinPlatformAgent agent = clazz.newInstance();
IMixinPlatformAgent agent = clazz.getDeclaredConstructor().newInstance();
AcceptResult acceptAction = agent.accept(manager, this.handle);
if (acceptAction == AcceptResult.ACCEPTED) {
@@ -79,7 +80,7 @@ public class MixinContainer {
continue;
}
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(), this.handle);
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(Locale.ROOT), this.handle);
} catch (InstantiationException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
@@ -297,7 +297,6 @@ public class MixinPlatformManager {
*/
final void addConnector(String connectorClass) {
this.connectors.addConnector(connectorClass);
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Default (platform-agnostic) container handles
*/
package org.spongepowered.asm.launch.platform.container;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Base classes for environment-specific adapters and default platform-agnostic
* handlers for environment and mixin containers.
*/
package org.spongepowered.asm.launch.platform;
@@ -31,7 +31,13 @@ import java.lang.annotation.Target;
/**
* Pseudo-implements decorator for Mixins with conflicting methods in a
* superclass to soft-implement an interface
* superclass to soft-implement an interface.
*
* <p>See <a target="_top"
* href="https://github.com/SpongePowered/Mixin/wiki/Introduction-to-Mixins -
* Resolving-Method-Signature-Conflicts">Introduction to Mixins - Resolving
* Method Signature Conflicts</a> for details on soft implementation of
* interfaces.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -46,10 +46,10 @@ import java.lang.annotation.Target;
* <p>Consider the following code:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* public int soft$getSomething() {
* return this.getSomething();
* }</pre></blockquote>
*
*public int soft$getSomething() {
* return this.getSomething();
*}</pre></blockquote>
*
* <p>This type of accessor is common when an interface conflict occurs, but has
* the problem that the injected accessor will be effectively self-referential
@@ -61,9 +61,9 @@ import java.lang.annotation.Target;
*
* <blockquote><pre>&#064;Shadow private int something;
*
* public int soft$getSomething() {
* return this.something;
* }</pre></blockquote>
*public int soft$getSomething() {
* return this.something;
*}</pre></blockquote>
*
* <p>But this has the drawback of forcing the mixin to re-implement the target
* method, and thus forces ongoing maintenance of the mixin to include updating
@@ -75,21 +75,21 @@ import java.lang.annotation.Target;
* accessor with {@link Intrinsic &#064;Intrinsic}:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* &#064;Intrinsic // don't merge the method if the target already exists
* public int soft$getSomething() {
* return this.getSomething();
* }</pre></blockquote>
*
*&#064;Intrinsic <del>// don't merge the method if the target already exists
*</del>public int soft$getSomething() {
* return this.getSomething();
*}</pre></blockquote>
*
* <p>This is ideal if the accessor is simply providing a proxy through to an
* underlying obfuscated method, as in the example above. However, if the new
* method contains additional code, such as in this example:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
* }</pre></blockquote>
*
*public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
*}</pre></blockquote>
*
* <p>Then we still have the original problem that the method becomes re-entrant
* without specifying the additional Overwrite. We can solve this with the
@@ -108,11 +108,11 @@ import java.lang.annotation.Target;
* accessor will call the overwritten method.</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* &#064;Intrinsic(displace = true) // if the target already exists, displace it
* public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
* }</pre></blockquote>
*
*&#064;Intrinsic(displace = true) // if the target already exists, displace it
*public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
*}</pre></blockquote>
*
*/
@Target({ ElementType.METHOD })
@@ -30,7 +30,22 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Decorator for mixin classes
* The main decorator for mixin classes, this annotation denotes a class as a
* mixin and specifies two key attributes:
*
* <dl>
* <dt>The target classes</dt>
* <dd>Every mixin requires at least one target class in order to be valid.
* The target classes should be specified via {@link #value} where possible
* using class literals. However for anonymous inner classes,
* package-private classes, or unavailable classes (eg. synthetic classes)
* being targetted via {@link Pseudo &#64;Pseudo}, the targets should be
* specified via the {@link #targets} instead.</dd>
* <dt>The priority</dt>
* <dd>The mixin {@link #priority} is used to express the mixin's desired
* ordering with respect to other mixins being applied to the same target
* class.</dd>
* </dl>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -46,18 +61,34 @@ public @interface Mixin {
/**
* Since specifying targets in {@link #value} requires that the classes be
* publicly visible, this property is provided to allow package-private,
* anonymous innner, and private inner classes to be referenced. Referencing
* an otherwise public class using this property is an error condition and
* will throw an exception at runtime. It is completely fine to specify both
* public and private targets for the same mixin however.
* anonymous innner, and private inner, or unavailable ({@link Pseudo
* &#64;Pseudo} classes to be referenced. Referencing an otherwise public
* class using this property is an error condition and will raise a warning
* at runtime or an error if {@link MixinEnvironment.Option#DEBUG_STRICT
* strict checks} are enabled. It is completely fine to specify both publi
* and private targets for the same mixin however.
*
* <p>Note that unlike class literals specified in {@link #value}, imports
* are not supported and therefore the class specified here must be
* fully-qualified with the package name.</p>
*
* @return protected or package-private classes this mixin targets
* @return protected, package-private, or {@link Pseudo pseudo} classes this
* mixin targets
*/
public String[] targets() default { };
/**
* Priority for the mixin, relative to other mixins targetting the same
* classes
* classes. By default mixins inherit their priority from the parent
* configuration that contains them, setting this value allows the priority
* to be overridden on a per-mixin basis.
*
* <p>Priorities sort mixins into <em>natural order</em> with lower priority
* mixins being applied first. This changes the nature of priority based on
* your intentions. Especially with respect to injectors, which must be
* considered on a case-by-case basis since the semantics of priority vary
* by injector because of first-come-first-served versus implied ordering of
* injectors such as inject-at-HEAD.</p>
*
* @return the mixin priority (relative to other mixins targetting the same
* class)
@@ -66,7 +97,7 @@ public @interface Mixin {
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link Shadow} and
* obfuscation mapping for all {@link Overwrite}, {@link Shadow} and
* {@link org.spongepowered.asm.mixin.injection.Inject} annotated members
* since it is anticipated that in general the target of a {@link Mixin}
* will be an obfuscated class and all annotated members will need to be
@@ -84,4 +115,5 @@ public @interface Mixin {
* obfuscation mappings for this annotation (default true).
*/
public boolean remap() default true;
}
@@ -56,6 +56,7 @@ import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.IConsumer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.asm.ASM;
import org.spongepowered.asm.util.perf.Profiler;
@@ -591,12 +592,12 @@ public final class MixinEnvironment implements ITokenProvider {
public static enum CompatibilityLevel {
/**
* Java 6 and above
* Java 6 (1.6) or above is required
*/
JAVA_6(6, Opcodes.V1_6, 0),
/**
* Java 7 and above
* Java 7 (1.7) or above is required
*/
JAVA_7(7, Opcodes.V1_7, 0) {
@@ -608,9 +609,9 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 8 and above
* Java 8 (1.8) or above is required
*/
JAVA_8(8, Opcodes.V1_8, LanguageFeature.METHODS_IN_INTERFACES) {
JAVA_8(8, Opcodes.V1_8, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -620,9 +621,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 9 and above
* Java 9 or above is required
*/
JAVA_9(9, Opcodes.V9, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) {
JAVA_9(9, Opcodes.V9, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -632,9 +634,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 10 and above
* Java 10 or above is required
*/
JAVA_10(10, Opcodes.V10, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) {
JAVA_10(10, Opcodes.V10, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -644,10 +647,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 10 and above
* Java 11 or above is required
*/
JAVA_11(11, Opcodes.V11, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_11(11, Opcodes.V11, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -659,8 +662,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 12 and above
*/
JAVA_12(12, Opcodes.V12, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_12(12, Opcodes.V12, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -672,8 +675,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 13 and above
*/
JAVA_13(13, Opcodes.V13, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_13(13, Opcodes.V13, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -685,8 +688,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 14 and above
*/
JAVA_14(14, Opcodes.V14, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_14(14, Opcodes.V14, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -698,8 +701,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 16 and above
*/
JAVA_15(15, Opcodes.V15, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_15(15, Opcodes.V15, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -711,8 +714,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 16 and above
*/
JAVA_16(16, Opcodes.V16, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_16(16, Opcodes.V16, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -724,8 +727,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 17 and above
*/
JAVA_17(17, Opcodes.V17, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_17(17, Opcodes.V17, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -734,33 +737,6 @@ public final class MixinEnvironment implements ITokenProvider {
};
/**
* Bitmask values for language features supported
*/
public static class LanguageFeature {
/**
* Language version supports methods in interfaces
*/
public static final int METHODS_IN_INTERFACES = 1;
/**
* Language version supports private methods in interfaces
*/
public static final int PRIVATE_METHODS_IN_INTERFACES = 2;
/**
* Native nesting
*/
public static final int NESTING = 4;
/**
* Dynamic constants
*/
public static final int DYNAMIC_CONSTANTS = 8;
}
/**
* Default compatibility level to use if not specified by the service
*/
@@ -790,11 +766,35 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Class version expected at this compatibility level
*
* @deprecated Use getClassVersion
*/
@Deprecated
public int classVersion() {
return this.classVersion;
}
/**
* Class version expected at this compatibility level
*/
public int getClassVersion() {
return this.classVersion;
}
/**
* Get the major class version expected at this compatibility level
*/
public int getClassMajorVersion() {
return this.classVersion & 0xFFFF;
}
/**
* Get all supported language features
*/
public int getLanguageFeatures() {
return this.languageFeatures;
}
/**
* Get whether this environment supports non-abstract methods in
* interfaces, true in Java 1.8 and above
@@ -803,18 +803,18 @@ public final class MixinEnvironment implements ITokenProvider {
*/
@Deprecated
public boolean supportsMethodsInInterfaces() {
return (this.languageFeatures & LanguageFeature.METHODS_IN_INTERFACES) != 0;
return (this.languageFeatures & LanguageFeatures.METHODS_IN_INTERFACES) != 0;
}
/**
* Get whether the specified {@link LanguageFeature} is supported by
* Get whether the specified {@link LanguageFeatures} is supported by
* this runtime.
*
* @param languageFeature language feature (or features) to check
* @param languageFeatures language feature (or features) to check
* @return true if all specified language features are supported
*/
public boolean supports(int languageFeature) {
return (this.languageFeatures & languageFeature) != 0;
public boolean supports(int languageFeatures) {
return (this.languageFeatures & languageFeatures) == languageFeatures;
}
/**
@@ -864,6 +864,25 @@ public final class MixinEnvironment implements ITokenProvider {
return level.canElevateTo(this);
}
/**
* Return the minimum language level required to support the specified
* language feature(s). Returns <tt>null</tt> if no compatibility level
* available can support the requested language features.
*
* @param languageFeatures Language feature(s) to check for
* @return Lowest compatibility level which supports the requested
* language feature, or null if no levels support the requested
* feature
*/
public static CompatibilityLevel requiredFor(int languageFeatures) {
for (CompatibilityLevel level : CompatibilityLevel.values()) {
if (level.supports(languageFeatures)) {
return level;
}
}
return null;
}
static String getSupportedVersions() {
StringBuilder sb = new StringBuilder();
@@ -1058,7 +1077,8 @@ public final class MixinEnvironment implements ITokenProvider {
printer.kv("Internal Version", version);
printer.kv("Java Versions Supported", CompatibilityLevel.getSupportedVersions());
printer.kv("Current Compatibility Level", MixinEnvironment.getCompatibilityLevel());
printer.kv("Detected ASM API Version", ASM.getApiVersionString()).hr();
printer.kv("Detected ASM API Version", ASM.getApiVersionString());
printer.kv("Detected ASM Supports Java", ASM.getClassVersionString()).hr();
printer.kv("Service Name", serviceName);
printer.kv("Mixin Service Class", this.service.getClass().getName());
printer.kv("Global Property Service Class", MixinService.getGlobalPropertyService().getClass().getName()).hr();
@@ -1147,7 +1167,7 @@ public final class MixinEnvironment implements ITokenProvider {
@SuppressWarnings("unchecked")
Class<? extends IEnvironmentTokenProvider> providerClass =
(Class<? extends IEnvironmentTokenProvider>)this.service.getClassProvider().findClass(providerName, true);
IEnvironmentTokenProvider provider = providerClass.newInstance();
IEnvironmentTokenProvider provider = providerClass.getDeclaredConstructor().newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
MixinEnvironment.logger.error("Error instantiating " + providerName, th);
@@ -30,23 +30,38 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A Mixin marked as <b>Pseudo</b> is allowed to target classes which are not
* available at compile time and may not be available at runtime. This means
* that certain restrictions apply:
* A Mixin marked as <tt>&#64;Pseudo</tt> is allowed to target classes which are
* not available at <em>compile time</em> and may not be available at runtime.
* This can be used in situations where - for one reason or another - a target
* class is not available to a project being compiled and would therefore fail
* AP verification. The target class is simulated by the AP using knowledge of
* only the superclass of the target (or at least, any <em>available</em> known
* superclass of the target. This means that certain restrictions apply:
*
* <p>In particular, the superclass requirement for pseudo mixins is extremely
* important if the target has an obfuscated class in its hierarchy. For example
* let's assume that we're mixing into a class <tt>SomeCustomScreen</tt> from
* another party which extends <tt>GuiScreen</tt> which is obfuscated.
* Attempting to inject into <tt>initGui</tt> will succeed at dev time and fail
* at production time, because the reference is obfuscated. We can overcome this
* by ensuring the mixin inherits from the same superclass, thus allowing
* <tt>initGui</tt> to be resolved in the superclass hierarchy (this is not the
* case for normal mixins).</p>
* <p>The superclass requirement for pseudo mixins is extremely important <b>if
* the target has an obfuscated class in its hierarchy</b>. For example
* let's assume that we're mixing into a class <tt>CustomGuiScreen</tt> from
* another party which extends <tt>GuiScreen</tt>, where <tt>GuiScreen</tt> is
* an obfuscated class. <tt>GuiScreen</tt> contains an obfuscated method
* <tt>initGui</tt> which the (&#64;Pseudo) target class overrides. Attempting
* to inject into <tt>initGui</tt> would succeed at dev time but would fail
* at production time, because the reference is obfuscated. Normally when a
* target overrides an obfuscated method in this way, the AP can resolve the
* obfuscation by walking the superclass hierarchy of the target in order to
* discover a mapping. However when the target is not available at compile time
* the AP cannot do this and must rely on only information from the mixin
* itself. We can overcome this problem by ensuring the mixin inherits from the
* same superclass (or at least a superclass which contains the obfuscated
* methods or fields used in the mixin), thus allowing our example <tt>initGui
* </tt> method to be resolved in the superclass hierarchy. This behaviour is
* not available to normal mixins as the AP always resolves the hierarchy via
* the target class metadata when it is available.</p>
*
* <p>{@link Overwrite} methods which are <b>not</b> inherited from a superclass
* (if the target is obfuscated) <b>must</b> be decorated manually with aliases.
* </p>
* <p>If the target class contains obfuscated methods which the mixin needs to
* {@link Overwrite} or {@link Shadow} which are <b>not</b> inherited from a
* superclass (eg. the target is obfuscated), the {@link Overwrite} or
* {@link Shadow} <b>must</b> be decorated manually with <tt>aliases</tt> since
* there is no mechanism for the AP to resolve the mappings automatically.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* See {@link org.spongepowered.asm.mixin.connect.IMixinConnector}
*/
package org.spongepowered.asm.mixin.connect;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Interfaces for internal Mixin objects which provide extensibility for mixin
* consumers.
*/
package org.spongepowered.asm.mixin.extensibility;
@@ -75,7 +75,7 @@ public abstract class AccessorGenerator {
MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name,
method.desc, null, null);
accessor.visibleAnnotations = new ArrayList<AnnotationNode>();
accessor.visibleAnnotations.add(this.info.getAnnotation());
accessor.visibleAnnotations.add(this.info.getAnnotationNode());
accessor.maxLocals = maxLocals;
accessor.maxStack = maxStack;
return accessor;
@@ -67,9 +67,9 @@ public class AccessorGeneratorFieldSetter extends AccessorGeneratorField {
return;
}
if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
LogManager.getLogger("mixin").warn("{} for final field {}::{} is not @Mutable", this.info,
((MixinTargetContext)this.info.getContext()).getTarget(), this.targetField.name);
((MixinTargetContext)this.info.getMixin()).getTarget(), this.targetField.name);
}
}
@@ -74,7 +74,7 @@ public class AccessorGeneratorMethodProxy extends AccessorGenerator {
if (!this.targetIsStatic) {
method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
Bytecode.loadArgs(this.argTypes, method.instructions, this.targetIsStatic ? 0 : 1);
Bytecode.loadArgs(this.argTypes, method.instructions, this.info.isStatic ? 0 : 1);
boolean isInterface = Bytecode.hasFlag(this.info.getClassNode(), Opcodes.ACC_INTERFACE);
boolean isPrivate = Bytecode.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE);
int opcode = this.targetIsStatic ? Opcodes.INVOKESTATIC : isInterface ? Opcodes.INVOKEINTERFACE : (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL);
@@ -41,7 +41,7 @@ public class AccessorGeneratorObjectFactory extends AccessorGeneratorMethodProxy
public AccessorGeneratorObjectFactory(AccessorInfo info) {
super(info, true);
if (!info.isStatic()) {
throw new InvalidInjectionException(info.getContext(), String.format("%s is invalid. Factory method must be static.", this.info));
throw new InvalidInjectionException(info.getMixin(), String.format("%s is invalid. Factory method must be static.", this.info));
}
}
@@ -39,16 +39,17 @@ import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.struct.SpecialMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.asm.ElementNode;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
@@ -302,6 +303,7 @@ public class AccessorInfo extends SpecialMethodInfo {
this.type = this.initType();
this.targetFieldType = this.initTargetFieldType();
this.target = this.initTarget();
this.annotation.visit("target", this.target.toString());
}
protected AccessorType initType() {
@@ -331,9 +333,7 @@ public class AccessorInfo extends SpecialMethodInfo {
}
protected ITargetSelector initTarget() {
MemberInfo target = new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor());
this.annotation.visit("target", target.toString());
return target;
return new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor());
}
protected String getTargetName(String name) {
@@ -345,7 +345,7 @@ public class AccessorInfo extends SpecialMethodInfo {
}
return inflectedTarget;
}
return TargetSelector.parseName(name, this.mixin);
return TargetSelector.parseName(name, this);
}
/**
@@ -355,7 +355,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* <tt>foo</tt> for example.
*/
protected String inflectTarget() {
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin,
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this,
this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE));
}
@@ -376,7 +376,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return inflected target member name or <tt>null</tt> if name cannot be
* inflected
*/
public static String inflectTarget(String name, AccessorType type, String description, IMixinContext context, boolean verbose) {
public static String inflectTarget(String name, AccessorType type, String description, ISelectorContext context, boolean verbose) {
return AccessorInfo.inflectTarget(AccessorName.of(name), type, description, context, verbose);
}
@@ -397,7 +397,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return inflected target member name or <tt>null</tt> if name cannot be
* inflected
*/
public static String inflectTarget(AccessorName name, AccessorType type, String description, IMixinContext context, boolean verbose) {
public static String inflectTarget(AccessorName name, AccessorType type, String description, ISelectorContext context, boolean verbose) {
if (name != null) {
if (!type.isExpectedPrefix(name.prefix) && verbose) {
LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", description, name.prefix,
@@ -462,7 +462,7 @@ public class AccessorInfo extends SpecialMethodInfo {
@Override
public String toString() {
String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR";
return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString,
return String.format("%s->@%s[%s]::%s%s", this.mixin, Annotations.getSimpleName(this.annotation), typeString,
this.methodName, this.method.desc);
}
@@ -510,7 +510,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return best match
*/
protected <TNode> TNode findTarget(List<ElementNode<TNode>> nodes) {
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure("orphan"), nodes);
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure(Configure.ORPHAN), nodes);
try {
return result.getSingleResult(true);
@@ -27,7 +27,9 @@ package org.spongepowered.asm.mixin.gen;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result;
@@ -35,7 +37,6 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.asm.ElementNode;
/**
* Information about an invoker
@@ -102,7 +103,8 @@ class InvokerInfo extends AccessorInfo {
}
private MethodNode findTargetMethod() {
Result<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure("orphan"), ElementNode.methodList(this.classNode));
Result<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure(Configure.ORPHAN),
ElementNode.methodList(this.classNode));
try {
return result.getSingleResult(true);
@@ -0,0 +1,32 @@
/*
* 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.
*/
/**
* Generators, a special type of injector which replace the annotated method
* with synthetic content, see
* {@link org.spongepowered.asm.mixin.gen.Accessor &#64;Accessor} and
* {@link org.spongepowered.asm.mixin.gen.Invoker &#64;Invoker}.
*/
package org.spongepowered.asm.mixin.gen;
@@ -43,7 +43,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, String message) {
super(info.getContext(), message);
super(info.getMixin(), message);
this.info = info;
}
@@ -53,7 +53,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, Throwable cause) {
super(info.getContext(), cause);
super(info.getMixin(), cause);
this.info = info;
}
@@ -63,7 +63,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
super(info.getMixin(), message, cause);
this.info = info;
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Exceptions for generators.
*/
package org.spongepowered.asm.mixin.gen.throwables;
@@ -165,6 +165,12 @@ public @interface At {
*/
public String target() default "";
/**
* Target descriptor used in place of string-based descriptors for
* {@link #target}
*/
public Desc desc() default @Desc("");
/**
* Ordinal offset. Many InjectionPoints will return every opcode matching
* their criteria, specifying <em>ordinal</em> allows a particular opcode to
@@ -0,0 +1,150 @@
/*
* 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.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
/**
* <p>A descriptor for matching a target element, for details of usage see
* {@link DynamicSelectorDesc}.</p>
*
* <p>Unlike {@link MemberInfo Explicit Target Selectors} which can match any
* element of a candidate member, <tt>&#064;Desc</tt> descriptors always match
* all elements of a target explicitly. Element defaults are as follows:</p>
*
* <blockquote><dl>
* <dt>{@link #owner}</dt>
* <dd>Defaults to the current target of the mixin if not specified</dd>
* <dt>{@link #ret}</dt>
* <dd>Defaults to <tt>void</tt></dd>
* <dt>{@link #args}</dt>
* <dd>Defaults to an empty array matching a target with <b>no arguments</b>,
* omitting this value does <em>not</em> mean "match any" signature and
* will explicitly match targets with no arguments. This value is ignored
* for fields.</dd>
* </dl></blockquote>
*
* <h4>Notes</h4>
*
* <ul>
* <li>It should be noted that specifying the only required value
* ({@link #value}) will therefore match elements with owner type equal to the
* current mixin target, taking no arguments and returning void.</li>
*
* <li>Note that when matching fields the value of {@link #args} is ignored.
* </li>
* </ul>
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Descriptors.class)
public @interface Desc {
/**
* The identifier for this descriptor. Can be an implicit coordinate or a
* user-defined string. IDs are not case-sensitive but must be unique within
* a mixin or resolution scope. For more details on resolution for
* descriptors see {@link DynamicSelectorDesc}.
*/
public String id() default "";
/**
* The owner of the member to match. The "owner" is the class which declares
* the member <b>or, ocasionally</b> the type of class upon which a virtual
* call is being made. For example if a class <tt>SuperType</tt> defines a
* method <tt>doSomething</tt>, usually <tt>owner</tt> will be
* <tt>SuperType</tt>. However note that where a method retrieves a
* reference to a derived type <tt>DerivedType</tt> which overrides
* <tt>doSomething</tt>, it's possible the invocation will be made using
* that type. To ensure usage of the correct type, inspect the disassembled
* bytecode for your target.
*
* <p>When <tt>owner</tt> is not specified, it defaults to the <em>current
* </em> target of the mixin.</p>
*/
public Class<?> owner() default void.class;
/**
* The name of the member to match. Must be specified. Matched
* case-sensitively against targets.
*/
public String value();
/**
* The return type of a method to match, or the declared type of a field.
* Defaults to <tt>void</tt>.
*/
public Class<?> ret() default void.class;
/**
* The argument types of a method to match, ignored for fields. Note that
* failing to specify this value <b>matches a target with no arguments</b>.
*/
public Class<?>[] args() default { };
/**
* The next elements of this descriptor path, evaluated in order for each
* recurse point.
*/
// public Next[] next() default { };
/**
* The minimum number of times this selector should match. By default the
* selector is allowed to match no targets. When selecting fields or methods
* setting this value to anything other than 0 or 1 is pointless since the
* member can either be present or absent. However when matching method <em>
* calls</em> or field <em>accesses</em> (eg. when using this value inside
* {@link At#desc &#64;At.desc}) this allows a minimum number of matches to
* be specified in order to provide early validation that the selector
* matched the correct number of candidates. To specify an exact number of
* matches, set {@link #max max} to the same value as <tt>min</tt>. Values
* less than zero are ignored since selectors cannot match a negative number
* of times.
*/
public int min() default 0;
/**
* The maximum number of times this selector can match. By default the
* selector is allowed to match an unlimited number of targets. When
* selecting fields or methods, setting this value to anything other than 1
* is pointless since the member can either be present or absent. However
* when matching method <em>calls</em> or field <em>accesses</em> (eg. when
* using this value inside {@link At#desc &#64;At.desc}) this allows a
* maximum number of matches to be specified in order to limit the number of
* times that the selector can match candidates. To specify an exact number
* of matches, set <tt>max</tt> to the same value as {@link #min min}.
* Values less than 1 are treated as <tt>Integer.MAX_VALUE</tt> (the
* default) since setting a value of 0 or less has no meaning.
*/
public int max() default Integer.MAX_VALUE;
}
@@ -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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Collection type for {@link Desc} to allow {@link Repeatable} to work.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Descriptors {
/**
* Desc annotations for element
*/
Desc[] value();
}
@@ -26,28 +26,24 @@ package org.spongepowered.asm.mixin.injection;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.util.IMessageSink;
/**
* Context for an injection point, used to access the mixin as well as the owner
* method and annotation for the injection point
*/
public interface IInjectionPointContext extends IMessageSink {
/**
* Get the mixin context for this injection
*/
public abstract IMixinContext getContext();
public interface IInjectionPointContext extends IMessageSink, ISelectorContext {
/**
* Get the injection handler method
*/
@Override
public abstract MethodNode getMethod();
/**
* Get the parent annotation (eg. the &#064;Inject annotation)
*/
public abstract AnnotationNode getAnnotation();
public abstract AnnotationNode getAnnotationNode();
}
@@ -122,7 +122,15 @@ public @interface Inject {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* Array of {@link Slice} annotations which describe the method bisections
@@ -30,12 +30,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
@@ -49,38 +52,89 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.points.*;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.IMessageSink;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
/**
* <p>Base class for injection point discovery classes. Each subclass describes
* a strategy for locating code injection points within an instruction list,
* with the {@link #find} method populating a collection with insn nodes from
* the supplied list which satisfy its strategy.</p>
* with the {@link #find find} method populating a collection with insn nodes
* from the supplied list which satisfy its strategy.</p>
*
* <p>This base class also contains composite strategy factory methods such as
* {@link #and} and {@link #or} which allow strategies to be combined using
* intersection (and) or union (or) relationships to allow multiple strategies
* to be easily combined.</p>
* {@link #and and} and {@link #or or} which allow strategies to be combined
* using intersection (and) or union (or) relationships to allow multiple
* strategies to be easily combined.</p>
*
* <p>You are free to create your own injection point subclasses, but take note
* that it <b>is allowed</b> for a single InjectionPoint instance to be used for
* multiple injections and thus implementing classes MUST NOT cache the insn
* list, event, or nodes instance passed to the {@link #find} method, as each
* call to {@link #find} must be considered a separate functional contract and
* the InjectionPoint's lifespan is not linked to the discovery lifespan,
* therefore it is important that the InjectionPoint implementation is fully
* <b>stateless</b>.</p>
* <h4>Built-in Injection Points</h4>
*
* <p>The following built-in Injection Points are available:</p>
*
* <ul>
* <li>{@link MethodHead HEAD} - Selects the first insn</li>
* <li>{@link BeforeReturn RETURN} - Selects RETURN insns</li>
* <li>{@link BeforeFinalReturn TAIL} - Selects the last RETURN insn</li>
* <li>{@link BeforeInvoke INVOKE} - Selects method invocations</li>
* <li>{@link AfterInvoke INVOKE_ASSIGN} - Selects STORE insns after method
* invocations which return a value</li>
* <li>{@link BeforeFieldAccess FIELD} - Selects field access insns</li>
* <li>{@link BeforeNew NEW} - Selects object constructions</li>
* <li>{@link BeforeStringInvoke INVOKE_STRING} - Selects method invocations
* where a specific string is passed to the invocation.</li>
* <li>{@link JumpInsnPoint JUMP} - Selects branching (jump) instructions</li>
* <li>{@link BeforeConstant CONSTANT} - Selects constant values</li>
* </ul>
*
* <p>Additionally, the two special injection points are available which are
* only supported for use with {@link ModifyVariable &#64;ModifyVariable}:</p>
*
* <ul>
* <li>{@link BeforeLoadLocal LOAD} - Selects xLOAD insns matching the <tt>
* ModifyVariable</tt> discriminators.</li>
* <li>{@link AfterStoreLocal STORE} - Selects xSTORE insns matching the <tt>
* ModifyVariable</tt> discriminators.</li>
* </ul>
*
* <p>See the javadoc for each type for more details on the scheme used by each
* injection point.</p>
*
* <h4>Custom Injection Points</h4>
*
* <p>You are free to create your own injection point subclasses. Once defined,
* they can be used by your mixins in one of two ways:</p>
*
* <ol>
* <li>Specify the fully-qualified name of the injection point class in the
* {@link At#value &#64;At.value}.</li>
* <li>Decorate your injection point class with {@link AtCode &#64;AtCode}
* annotation which specifies a namespace and shortcode for the injection
* point, and register the class in your mixin config. You can then specify
* the namespaced code (eg. <tt>MYMOD:CUSTOMPOINT</tt>) in {@link At#value
* &#64;At.value}.</li>
* </ol>
*
* <p>When writing custom injection points, note that the general contract of
* injection points is that they be entirely - or at least behaviourally -
* stateless. It <b>is allowed</b> for a single InjectionPoint instance to be
* used by the mixin processor for multiple injections and thus implementing
* classes <em>MUST NOT</em> cache the insn list, event, or nodes instance
* passed to the {@link #find find} method, as each call to {@link #find find}
* must be considered a separate contract and the InjectionPoint's lifespan is
* not linked to the discovery lifespan. It is therefore important that the
* InjectionPoint implementation is fully stateless and that calls to
* {@link #find find} are idempotent.</p>
*/
public abstract class InjectionPoint {
@@ -91,9 +145,18 @@ public abstract class InjectionPoint {
@Target(ElementType.TYPE)
public @interface AtCode {
/**
* Namespace for this code. Final selectors will be specified as
* <tt>&lt;namespace&gt;:&lt;code&gt;</tt> in order to avoid overlaps
* between consumer-provided injection points. Uses namespace from
* parent config if not specified.
*/
public String namespace() default "";
/**
* The string code used to specify the annotated injection point in At
* annotations
* annotations, prefixed with namespace from the annotation or from the
* declaring configuration.
*/
public String value();
@@ -199,18 +262,18 @@ public abstract class InjectionPoint {
static {
// Standard Injection Points
InjectionPoint.register(BeforeFieldAccess.class);
InjectionPoint.register(BeforeInvoke.class);
InjectionPoint.register(BeforeNew.class);
InjectionPoint.register(BeforeReturn.class);
InjectionPoint.register(BeforeStringInvoke.class);
InjectionPoint.register(JumpInsnPoint.class);
InjectionPoint.register(MethodHead.class);
InjectionPoint.register(AfterInvoke.class);
InjectionPoint.register(BeforeLoadLocal.class);
InjectionPoint.register(AfterStoreLocal.class);
InjectionPoint.register(BeforeFinalReturn.class);
InjectionPoint.register(BeforeConstant.class);
InjectionPoint.registerBuiltIn(BeforeFieldAccess.class);
InjectionPoint.registerBuiltIn(BeforeInvoke.class);
InjectionPoint.registerBuiltIn(BeforeNew.class);
InjectionPoint.registerBuiltIn(BeforeReturn.class);
InjectionPoint.registerBuiltIn(BeforeStringInvoke.class);
InjectionPoint.registerBuiltIn(JumpInsnPoint.class);
InjectionPoint.registerBuiltIn(MethodHead.class);
InjectionPoint.registerBuiltIn(AfterInvoke.class);
InjectionPoint.registerBuiltIn(BeforeLoadLocal.class);
InjectionPoint.registerBuiltIn(AfterStoreLocal.class);
InjectionPoint.registerBuiltIn(BeforeFinalReturn.class);
InjectionPoint.registerBuiltIn(BeforeConstant.class);
}
private final String slice;
@@ -467,9 +530,23 @@ public abstract class InjectionPoint {
List<AbstractInsnNode> list = (nodes instanceof List) ? (List<AbstractInsnNode>) nodes : new ArrayList<AbstractInsnNode>(nodes);
this.input.find(desc, insns, nodes);
for (int i = 0; i < list.size(); i++) {
list.set(i, insns.get(insns.indexOf(list.get(i)) + this.shift));
for (ListIterator<AbstractInsnNode> iter = list.listIterator(); iter.hasNext();) {
int sourceIndex = insns.indexOf(iter.next());
int newIndex = sourceIndex + this.shift;
if (newIndex >= 0 && newIndex < insns.size()) {
iter.set(insns.get(newIndex));
} else {
// Shifted beyond the start or end of the insnlist, into the dark void
iter.remove();
// Decorate the injector with the info in case it fails
int absShift = Math.abs(this.shift);
char operator = absShift != this.shift ? '-' : '+';
this.input.addMessage(
"@At.shift offset outside the target bounds: Index (index(%d) %s offset(%d) = %d) is outside the allowed range (0-%d)",
sourceIndex, operator, absShift, newIndex, insns.size());
}
}
if (nodes != list) {
@@ -566,7 +643,7 @@ public abstract class InjectionPoint {
public static List<InjectionPoint> parse(IInjectionPointContext context, List<AnnotationNode> ats) {
Builder<InjectionPoint> injectionPoints = ImmutableList.<InjectionPoint>builder();
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(context, at);
InjectionPoint injectionPoint = InjectionPoint.parse(new InjectionPointAnnotationContext(context, at, "at"), at);
if (injectionPoint != null) {
injectionPoints.add(injectionPoint);
}
@@ -617,7 +694,7 @@ public abstract class InjectionPoint {
* failed
*/
public static InjectionPoint parse(IMixinContext context, MethodNode method, AnnotationNode parent, AnnotationNode at) {
return InjectionPoint.parse(new AnnotatedMethodInfo(context, method, parent), at);
return InjectionPoint.parse(new InjectionPointAnnotationContext(new AnnotatedMethodInfo(context, method, parent), at, "at"), at);
}
/**
@@ -694,19 +771,19 @@ public abstract class InjectionPoint {
public static InjectionPoint parse(IInjectionPointContext context, String at, At.Shift shift, int by,
List<String> args, String target, String slice, int ordinal, int opcode, String id) {
InjectionPointData data = new InjectionPointData(context, at, args, target, slice, ordinal, opcode, id);
Class<? extends InjectionPoint> ipClass = findClass(context.getContext(), data);
InjectionPoint point = InjectionPoint.create(context.getContext(), data, ipClass);
Class<? extends InjectionPoint> ipClass = InjectionPoint.findClass(context.getMixin(), data);
InjectionPoint point = InjectionPoint.create(context.getMixin(), data, ipClass);
return InjectionPoint.shift(context, point, shift, by);
}
@SuppressWarnings("unchecked")
private static Class<? extends InjectionPoint> findClass(IMixinContext context, InjectionPointData data) {
String type = data.getType();
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type);
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type.toUpperCase(Locale.ROOT));
if (ipClass == null) {
if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
if (type.matches("^([A-Za-z_][A-Za-z0-9_]*[\\.\\$])+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
ipClass = (Class<? extends InjectionPoint>)Class.forName(type);
ipClass = (Class<? extends InjectionPoint>)MixinService.getService().getClassProvider().findClass(type);
InjectionPoint.types.put(type, ipClass);
} catch (Exception ex) {
throw new InvalidInjectionException(context, data + " could not be loaded or is not a valid InjectionPoint", ex);
@@ -730,6 +807,8 @@ public abstract class InjectionPoint {
InjectionPoint point = null;
try {
point = ipCtor.newInstance(data);
} catch (InvocationTargetException ex) {
throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex.getCause());
} catch (Exception ex) {
throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex);
}
@@ -746,7 +825,7 @@ public abstract class InjectionPoint {
} else if (shift == At.Shift.AFTER) {
return InjectionPoint.after(point);
} else if (shift == At.Shift.BY) {
InjectionPoint.validateByValue(context.getContext(), context.getMethod(), context.getAnnotation(), point, by);
InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotationNode(), point, by);
return InjectionPoint.shift(point, by);
}
}
@@ -778,7 +857,7 @@ public abstract class InjectionPoint {
allowed = InjectionPoint.MAX_ALLOWED_SHIFT_BY;
}
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Bytecode.getSimpleName(parent), point,
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Annotations.getSimpleName(parent), point,
by, context, method.name, limitBreached, allowed, advice);
if (err == ShiftByViolationBehaviour.WARN && allowed < InjectionPoint.MAX_ALLOWED_SHIFT_BY) {
@@ -791,7 +870,7 @@ public abstract class InjectionPoint {
protected String getAtCode() {
AtCode code = this.getClass().<AtCode>getAnnotation(AtCode.class);
return code == null ? this.getClass().getName() : code.value();
return code == null ? this.getClass().getName() : code.value().toUpperCase();
}
/**
@@ -800,19 +879,56 @@ public abstract class InjectionPoint {
*
* @param type injection point type to register
*/
@Deprecated
public static void register(Class<? extends InjectionPoint> type) {
InjectionPoint.register(type, null);
}
/**
* Register an injection point class. The supplied class must be decorated
* with an {@link AtCode} annotation for registration purposes.
*
* @param type injection point type to register
* @param namespace namespace for AtCode
*/
public static void register(Class<? extends InjectionPoint> type, String namespace) {
AtCode code = type.<AtCode>getAnnotation(AtCode.class);
if (code == null) {
throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode");
}
String annotationNamespace = code.namespace();
if (!Strings.isNullOrEmpty(annotationNamespace)) {
namespace = annotationNamespace;
}
Class<? extends InjectionPoint> existing = InjectionPoint.types.get(code.value());
if (existing != null && !existing.equals(type)) {
LogManager.getLogger("mixin").debug("Overriding InjectionPoint {} with {} (previously {})", code.value(), type.getName(),
existing.getName());
} else if (Strings.isNullOrEmpty(namespace)) {
LogManager.getLogger("mixin").warn("Registration of InjectionPoint {} with {} without specifying namespace is deprecated.",
code.value(), type.getName());
}
InjectionPoint.types.put(code.value(), type);
String id = code.value().toUpperCase(Locale.ROOT);
if (!Strings.isNullOrEmpty(namespace)) {
id = namespace.toUpperCase(Locale.ROOT) + ":" + id;
}
InjectionPoint.types.put(id, type);
}
/**
* Register a built-in injection point class. Skips validation and
* namespacing checks
*
* @param type injection point type to register
*/
private static void registerBuiltIn(Class<? extends InjectionPoint> type) {
String code = type.<AtCode>getAnnotation(AtCode.class).value().toUpperCase(Locale.ROOT);
InjectionPoint.types.put(code, type);
InjectionPoint.types.put("MIXIN:" + code, type);
}
}
@@ -38,24 +38,35 @@ 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}. This type of injection
* provides a lightweight mechanism for changing a single argument of a target
* method invocation. To affect multiple arguments at once, use {@link
* ModifyArgs} instead.
* provides a lightweight mechanism for changing a single argument of a selected
* method invocation within the target method(s). To affect multiple arguments
* of an invocation all at once, use {@link ModifyArgs} instead.
*
* <p>Consider the following method call:</p>
* <p>Use this injector when a method contains an method invocation and you wish
* to change a single value being <em>passed to</em> that method. If you need to
* alter an argument <em>received by</em> a target method, use {@link
* ModifyVariable} instead.</p>
*
* <blockquote><pre>// x, y and z are of type float
*someObject.setLocation(x, y, z, true);</pre></blockquote>
* <p>Consider the following method:</p>
*
* <p>Let us assume that we wish to modify the <tt>y</tt> value in the method
* call. We know that the arguments are <tt>float</tt>s and that the <tt>y</tt>
* value is the <em>second</em> (index = 1) <tt>float</tt> argument. Thus our
* injector requires the following signature:
* <blockquote><pre><code>private void targetMethod() {
* Entity someEntity = this.obtainEntity();
* float x = 1.0F, y = 3.0F, z = 0.1F;
* someEntity.<ins>setLocation</ins>(x, <ins>y</ins>, z, true);
*}</code></pre>
*</blockquote>
*
* <p>Let us assume that we wish to modify the <ins><tt>y</tt></ins> value when
* calling the <ins><tt>setLocation</tt></ins> method. We know that the
* arguments are <tt>float</tt>s and that the <tt>y</tt> value is the <em>second
* </em> (index = 1) <tt>float</tt> argument. Thus our injector requires the
* following signature:
*
* <blockquote><pre>&#064;ModifyArg(method = "...", at = ..., index = 1)
*private float adjustYCoord(float y) {
* return y + 64.0F;
*}</pre></blockquote>
* <blockquote><code>&#064;ModifyArg(method = "targetMethod", at = &#64;At(value
* = "INVOKE", target = "<ins>setLocation(FFFZ)V</ins>"), index = 1)<br />
* private float adjustYCoord(float y) {<br />
* &nbsp; &nbsp; return y + 64.0F;<br />
* }</code></blockquote>
*
* <p>The callback consumes the original value of <tt>y</tt> and returns the
* adjusted value.</p>
@@ -64,10 +75,11 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* arguments if required, to provide additional context for the callback. In
* this case the arguments of the callback should match the target method:</p>
*
* <blockquote><pre>&#064;ModifyArg(method = "...", at = ..., index = 1)
*private float adjustYCoord(float x, float y, float z, boolean interpolate) {
* return (x == 0 && y == 0) ? 0 : y;
*}</pre></blockquote>
* <blockquote><code>&#064;ModifyArg(method = "targetMethod", at = &#64;At(value
* = "INVOKE", target = "<ins>setLocation(FFFZ)V</ins>"), index = 1)<br />
* private float adjustYCoord(float x, float y, float z, boolean interpolate) {
* <br />&nbsp; &nbsp; return (x == 0 &amp;&amp; y == 0) ? 0 : y;<br />
* }</code></blockquote>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -80,7 +92,15 @@ public @interface ModifyArg {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -85,7 +85,15 @@ public @interface ModifyArgs {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -67,7 +67,15 @@ public @interface ModifyConstant {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* Array of {@link Slice} annotations which describe the method bisections
@@ -30,6 +30,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
@@ -37,20 +39,29 @@ 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}.
* to itself in the target method(s) identified by {@link #method}. The variable
* modifier can modify a single local variable in the target method frame.
*
* <p>If the variable being modified is a method argument, specifying the
* <tt>{@link #argsOnly argsOnly=true}</tt> reduces the overhead of calculating
* the local variable table for the method.</p>
*
* <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>
* </tt> for a local of type <ins>{@link String}</ins> should have the
* signature:</p>
*
* <code>private String methodName(String variable) { ...</code>
* <blockquote><code>private <ins>String</ins> myHandlerMethod(<ins>String</ins>
* variable) {<br />&nbsp; &nbsp; ...</code></blockquote>
*
* <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>.
* </em>, and can operate either on the entire LVT or on the {@link #argsOnly
* method arguments only}.</p>
*
* <h4>Explicit mode</h4>
*
* <p>In <em>explicit</em> mode, the variable to capture can be specified by
* specifying values for the discriminator arguments {@link #ordinal},
@@ -58,12 +69,32 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* order to attempt to locate the variable to capture. If no local variable
* matches any discriminators, the capture fails.</p>
*
* <h4>Implicit mode</h4>
*
* <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>
*
* <h4>Context-sensitive injection points</h4>
*
* <p>Normally the {@link InjectionPoint injection points} specified by {@link
* #at} are independent of the injector being used. With <tt>ModifyVariable</tt>
* there are two special injection points which consume the discriminator from
* the annotation:</p>
*
* <ul>
* <li>{@link BeforeLoadLocal LOAD} - matches <tt>xLOAD</tt> insns <em>for
* the variable matched by the discriminator</em> in the target method.</li>
* <li>{@link AfterStoreLocal STORE} - matches <tt>xSTORE</tt> insns <em>for
* the variable matched by the discriminator</em> in the target method.</li>
* </ul>
*
* <p>See the javadoc for each injection point for details.</p>
*
* <h4>Notes</h4>
*
* <p>Like other injectors, the callback signature can optionally include the
* target method arguments by simply appending them to the handler method
* signature.</p>
@@ -79,7 +110,15 @@ public @interface ModifyVariable {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -93,7 +132,8 @@ public @interface ModifyVariable {
* An {@link At} annotation which describes the {@link InjectionPoint} in
* the target method.
*
* @return {@link At} which identifies the target method invocation
* @return {@link At} which identifies the location to inject inside the
* target method.
*/
public At at();
@@ -55,7 +55,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* int def = 1;
* Foo someObject = new Foo();
*
* // Hooking this method
* <del>// Hooking this method</del>
* boolean xyz = someObject.bar(abc, def);
*}</pre>
* </blockquote>
@@ -63,7 +63,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>The signature of the redirected method should be:</p>
*
* <blockquote>
* <pre>public boolean barProxy(Foo someObject, int abc, int def)</pre>
* <code>public boolean barProxy(Foo someObject, int abc, int def)</code>
* </blockquote>
*
* <p>For obvious reasons this does not apply for static methods, for static
@@ -77,8 +77,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* arguments) by appending the arguments to the method signature:</p>
*
* <blockquote>
* <pre>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</pre>
* <code>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</code>
* </blockquote>
*
* <p>All arguments of a method redirect handler, and the return type, can be
@@ -92,7 +92,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* 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%">
* <table width="100%" class="infoTable">
* <tr>
* <th width="25%">Operation (OPCODE)</th>
* <th>Handler signature</th>
@@ -148,7 +148,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <em>indices</em>, for multi-dimensional arrays) and returns <em>the element
* type</em> (in this case <tt>String</tt>) as follows:</p>
*
* <table width="100%">
* <table width="100%" class="infoTable">
* <tr>
* <th width="25%">Operation</th>
* <th>Handler signature</th>
@@ -177,16 +177,16 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <tt>array=length</tt> and configure your handler signature to return <tt>int
* </tt> and consume the array as an argument:</p>
*
* <blockquote><code>private int getLength(<b>ElementType</b>[] array)
* <blockquote><code>private int getLength(<ins>ElementType</ins>[] array)
* </code></blockquote>
*
* -
* <p>For multi-dimensional arrays, provide one <tt>int</tt> argument for each
* additional dimension of the array:</p>
*
* <blockquote><code>// Multidimensional array<br />
* private <b>ElementType</b>[][] array;<br /><br />
* // Handler signature:<br />
* private <b>int</b> getLength(<b>ElementType</b>[][] array, int baseDim)
* <blockquote><code><del>// Multidimensional array</del><br />
* private <ins>ElementType</ins>[][] array;<br /><br />
* <del>// Handler signature:</del><br /> private <ins>int</ins>
* getLength(<ins>ElementType</ins>[][] array, int baseDim)
* </code></blockquote>
*
* <h3>New Object Redirect Mode (Factory Mode)</h3>
@@ -211,7 +211,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*class Foo {
* private final int x, y;
*
* // ctor we wish to hook
* <del>// ctor we wish to hook</del>
* Foo(int x, int y) {
* this.x = x;
* this.y = y;
@@ -231,7 +231,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* example to redirect the following object creation call:</p>
*
* <blockquote><pre>public void exampleFunc(String someString, int dx, int dy) {
* // Hooking this constructor
* <del>// Hooking this constructor</del>
* Foo someFoo = new Foo(dx * 10, dy * 10);
*}</pre>
* </blockquote>
@@ -239,15 +239,15 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>The signature of the handler method should be:</p>
*
* <blockquote>
* <pre>public Foo constructFoo(int x, int y)</pre>
* <code>public Foo constructFoo(int x, int y)</code>
* </blockquote>
*
* <p>Note that like other redirectors, it is possible to capture the target
* method's arguments by appending them to the handler method's signature:</p>
*
* <blockquote>
* <tt>public Foo constructFoo(int x, int y, String someString, int dx,
* int dy)</tt>
* <code>public Foo constructFoo(int x, int y, String someString, int dx,
* int dy)</code>
* </blockquote>
*
* <h3><tt>instanceof</tt> Redirect Mode</h3>
@@ -277,8 +277,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*
* <p>Note that this results in the injected code being less efficient, because
* the <tt>instanceof</tt> opcode is replaced with discrete code similar to <tt>
* reference != null && yourClass.isAssignableFrom(reference.getClass())</tt> in
* the target method body.</p>
* reference != null &amp;&amp; yourClass.isAssignableFrom(reference.getClass())
* </tt> in the target method body.</p>
*
* <p>The arguments to an <tt>instanceof</tt> redirect handler <b>must always be
* <tt>Object, Class</tt> even if the variable type is known</b>. This is
@@ -298,7 +298,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*
* <blockquote><pre>class Foo : Bar {
* Foo(int arg) {
* super(<span style="background: #FF0">Foo.isEven(arg)</span>);
* super(<ins>Foo.isEven(arg)</ins>);
* }
*
* static int isEven(int arg) {
@@ -326,7 +326,15 @@ public @interface Redirect {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -85,7 +85,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
* thing.<b>processStuff</b>();
* }
*
* // A new call to processStuff, which now has the ordinal 1
* <del>// A new call to processStuff, which now has the ordinal 1</del>
* bar.getActiveThing().<b>processStuff</b>();
*
* Thing specialThing = bar.getSpecialThing();
@@ -34,13 +34,14 @@ import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Annotations;
@@ -53,7 +54,8 @@ import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Strings;
/**
* This class is responsible for generating the bytecode for injected callbacks
* This class is responsible for generating the bytecode for injected callbacks,
* for details of usage see {@link Inject &#64;Inject}.
*/
public class CallbackInjector extends Injector {
@@ -343,6 +345,11 @@ public class CallbackInjector extends Injector {
}
/**
* Decorator key for local variables decoration
*/
private static final String LOCALS_KEY = "locals";
/**
* True if cancellable
*/
@@ -444,6 +451,19 @@ public class CallbackInjector extends Injector {
myNodes.add(injectionNode);
this.totalInjections++;
}
@Override
protected void preInject(Target target, InjectionNode node) {
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
for (int j = 0; j < locals.length; j++) {
if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) {
locals[j] = null;
}
}
node.<LocalVariableNode[]>decorate(CallbackInjector.LOCALS_KEY, locals);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector
@@ -452,17 +472,7 @@ public class CallbackInjector extends Injector {
*/
@Override
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.getCurrentTarget());
for (int j = 0; j < locals.length; j++) {
if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) {
locals[j] = null;
}
}
}
LocalVariableNode[] locals = node.<LocalVariableNode[]>getDecoration(CallbackInjector.LOCALS_KEY);
this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals()));
}
@@ -484,7 +494,7 @@ public class CallbackInjector extends Injector {
MethodNode callbackMethod = this.methodNode;
if (!callback.checkDescriptor(this.methodNode.desc)) {
if (this.info.getTargets().size() > 1) {
if (this.info.getTargetCount() > 1) {
return; // Look for a match in other targets before failing
}
@@ -560,13 +570,15 @@ public class CallbackInjector extends Injector {
*/
private String generateBadLVTMessage(final Callback callback) {
int position = callback.target.indexOf(callback.node);
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0));
int targetArgc = callback.target.arguments.length + 1;
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, targetArgc, 255);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, expected.size());
if (expected.equals(found)) {
return String.format("Invalid descriptor on %s! Expected %s but found %s", this.info, callback.getDescriptor(), this.methodNode.desc);
}
return 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);
List<String> available = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, 255);
return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\n Expected: %s\n Found: %s\nAvailable: %s",
callback.target, position, this.info, expected, found, available);
}
/**
@@ -816,14 +828,14 @@ public class CallbackInjector extends Injector {
return this.isStatic;
}
private static List<String> summariseLocals(String desc, int pos) {
return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos);
private static List<String> summariseLocals(String desc, int pos, int count) {
return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos, count);
}
private static List<String> summariseLocals(Type[] locals, int pos) {
private static List<String> summariseLocals(Type[] locals, int pos, int count) {
List<String> list = new ArrayList<String>();
if (locals != null) {
for (; pos < locals.length; pos++) {
for (; pos < locals.length && list.size() < count; pos++) {
if (locals[pos] != null) {
list.add(locals[pos].toString());
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Implementation of callback injector functionality provided by
* {@link org.spongepowered.asm.mixin.injection.Inject @#64;Inject}.
*/
package org.spongepowered.asm.mixin.injection.callback;
@@ -247,6 +247,18 @@ public abstract class Injector {
myNodes.add(target.addInjectionNode(node));
}
/**
* Performs pre-injection checks and tasks on the specified target
*
* @param target target potentially being injected into
* @param nodes selected target nodes
*/
public final void preInject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
this.preInject(target, node);
}
}
/**
* Performs the injection on the specified target
*
@@ -256,7 +268,7 @@ public abstract class Injector {
public final void inject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
if (node.isRemoved()) {
if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target);
}
continue;
@@ -279,7 +291,7 @@ public abstract class Injector {
* @return Target insn nodes in the target method
*/
private Collection<TargetNode> findTargetNodes(InjectorTarget injectorTarget, List<InjectionPoint> injectionPoints) {
IMixinContext mixin = this.info.getContext();
IMixinContext mixin = this.info.getMixin();
MethodNode method = injectorTarget.getMethod();
Map<Integer, TargetNode> targetNodes = new TreeMap<Integer, TargetNode>();
Collection<AbstractInsnNode> nodes = new ArrayList<AbstractInsnNode>(32);
@@ -295,7 +307,7 @@ public abstract class Injector {
injectorTarget, injectorTarget.getMergedBy(), injectorTarget.getMergedPriority()));
}
if (this.findTargetNodes(method, injectionPoint, injectorTarget.getSlice(injectionPoint), nodes)) {
if (this.findTargetNodes(method, injectionPoint, injectorTarget, nodes)) {
for (AbstractInsnNode insn : nodes) {
Integer key = method.instructions.indexOf(insn);
TargetNode targetNode = targetNodes.get(key);
@@ -311,8 +323,9 @@ public abstract class Injector {
return targetNodes.values();
}
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, insns, nodes);
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget,
Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes);
}
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
@@ -380,6 +393,10 @@ public abstract class Injector {
this.checkTargetModifiers(target, true);
}
protected void preInject(Target target, InjectionNode node) {
// stub
}
protected abstract void inject(Target target, InjectionNode node);
protected void postInject(Target target, InjectionNode node) {
@@ -439,7 +456,7 @@ public abstract class Injector {
this.pushArgs(args, insns, argMap, startArg, endArg);
return this.invokeHandler(insns);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
@@ -451,8 +468,24 @@ public abstract class Injector {
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) {
return this.storeArgs(target, args, insns, start, null, null);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
*
* @param target target method
* @param args argument types
* @param insns instruction list to generate insns into
* @param start Starting index
* @param from The label marking the start of the region for the locals
* @param to The label marking the end of the region for the stored locals
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start, LabelNode from, LabelNode to) {
int[] argMap = target.generateArgMap(args, start);
this.storeArgs(args, insns, argMap, start, args.length);
this.storeArgs(target, args, insns, argMap, start, args.length, from, to);
return argMap;
}
@@ -465,9 +498,25 @@ public abstract class Injector {
* @param start Starting index
* @param end Ending index
*/
protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end) {
this.storeArgs(target, args, insns, argMap, start, end, null, null);
}
/**
* Store args on the stack to their positions allocated based on argMap
*
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
* @param from The label marking the start of the region for the locals
* @param to The label marking the end of the region for the stored locals
*/
protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end, LabelNode from, LabelNode to) {
for (int arg = end - 1; arg >= start; arg--) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg]));
target.addLocalVariable(argMap[arg], String.format("injectorAllocatedLocal%d", argMap[arg]), args[arg].getDescriptor(), from, to);
}
}
@@ -522,7 +571,7 @@ public abstract class Injector {
* @param args Array of handler args, must not be null
*/
protected final void validateParams(InjectorData injector, Type returnType, Type... args) {
String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext());
String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getMixin());
int argIndex = 0;
try {
injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs);
@@ -574,12 +623,13 @@ public abstract class Injector {
* if coercion is required for the argument
*/
protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) {
Type fromType = index < 0 ? this.returnType : this.methodArgs[index];
if (index >= this.methodArgs.length) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Not enough arguments: expected argument type %s at index %d",
description, SignaturePrinter.getTypeName(toType), index));
}
Type fromType = index < 0 ? this.returnType : this.methodArgs[index];
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
boolean isReturn = index < 0;
@@ -587,7 +637,7 @@ public abstract class Injector {
Object argIndex = isReturn ? "" : " at index " + index;
if (fromType.equals(toType)) {
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (coerce != null && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex,
SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType));
}
@@ -619,12 +669,13 @@ public abstract class Injector {
* @param exceptionType Type of exception to throw (binary name)
* @param message Message to pass to the exception constructor
*/
protected void throwException(InsnList insns, String exceptionType, String message) {
protected void throwException(InsnList insns, Extension extraStack, String exceptionType, String message) {
insns.add(new TypeInsnNode(Opcodes.NEW, exceptionType));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(message));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, exceptionType, "<init>", "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
extraStack.add(3);
}
/**
@@ -32,6 +32,7 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.util.Annotations;
@@ -50,15 +51,26 @@ public class InjectorTarget {
/**
* Cache of slices
*/
private final Map<String, ReadOnlyInsnList> cache = new HashMap<String, ReadOnlyInsnList>();
private final Map<String, InsnListReadOnly> cache = new HashMap<String, InsnListReadOnly>();
/**
* Target method data
*/
private final Target target;
/**
* Selector which selected this method
*/
private final ITargetSelector selector;
/**
* Name of the mixin which merged the target, if any
*/
private final String mergedBy;
/**
* Priority of the mixin which merged the target, if any
*/
private final int mergedPriority;
/**
@@ -67,9 +79,10 @@ public class InjectorTarget {
* @param context owner
* @param target target
*/
public InjectorTarget(ISliceContext context, Target target) {
public InjectorTarget(ISliceContext context, Target target, ITargetSelector selector) {
this.context = context;
this.target = target;
this.selector = selector;
AnnotationNode merged = Annotations.getVisible(target.method, MixinMerged.class);
this.mergedBy = Annotations.<String>getValue(merged, "mixin");
@@ -95,6 +108,13 @@ public class InjectorTarget {
return this.target.method;
}
/**
* Get the selector which selected this target
*/
public ITargetSelector getSelector() {
return this.selector;
}
/**
* Get whether this target method was merged by another mixin
*/
@@ -125,14 +145,14 @@ public class InjectorTarget {
* @return insn slice
*/
public InsnList getSlice(String id) {
ReadOnlyInsnList slice = this.cache.get(id);
InsnListReadOnly slice = this.cache.get(id);
if (slice == null) {
MethodSlice sliceInfo = this.context.getSlice(id);
if (sliceInfo != null) {
slice = sliceInfo.getSlice(this.target.method);
} else {
// No slice exists so just wrap the method insns
slice = new ReadOnlyInsnList(this.target.method.instructions);
slice = new InsnListReadOnly(this.target.method.instructions);
}
this.cache.put(id, slice);
}
@@ -154,7 +174,7 @@ public class InjectorTarget {
* Dispose all cached instruction lists
*/
public void dispose() {
for (ReadOnlyInsnList insns : this.cache.values()) {
for (InsnListReadOnly insns : this.cache.values()) {
insns.dispose();
}
@@ -34,11 +34,11 @@ import org.objectweb.asm.tree.InsnList;
* instances so that custom InjectionPoint implementations cannot modify the
* insn list whilst inspecting it.
*/
class ReadOnlyInsnList extends InsnList {
class InsnListReadOnly extends InsnList {
private InsnList insnList;
public ReadOnlyInsnList(InsnList insns) {
public InsnListReadOnly(InsnList insns) {
this.insnList = insns;
}
@@ -40,9 +40,9 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import com.google.common.base.Strings;
@@ -57,7 +57,7 @@ public final class MethodSlice {
* identified by <tt>start</tt> and <tt>end</tt> to be accessed. In essence
* this class provides a <em>view</em> of the underlying InsnList.
*/
static final class InsnListSlice extends ReadOnlyInsnList {
static final class InsnListSlice extends InsnListReadOnly {
/**
* ListIterator for the slice view, wraps an iterator returned by the
@@ -359,7 +359,7 @@ public final class MethodSlice {
* @param method method to slice
* @return read only slice
*/
public ReadOnlyInsnList getSlice(MethodNode method) {
public InsnListReadOnly getSlice(MethodNode method) {
int max = method.instructions.size() - 1;
int start = this.find(method, this.from, 0, 0, this.name + "(from)");
int end = this.find(method, this.to, max, start, this.name + "(to)");
@@ -373,7 +373,7 @@ public final class MethodSlice {
}
if (start == 0 && end == max) {
return new ReadOnlyInsnList(method.instructions);
return new InsnListReadOnly(method.instructions);
}
return new InsnListSlice(method.instructions, start, end);
@@ -398,7 +398,7 @@ public final class MethodSlice {
}
Deque<AbstractInsnNode> nodes = new LinkedList<AbstractInsnNode>();
ReadOnlyInsnList insns = new ReadOnlyInsnList(method.instructions);
InsnListReadOnly insns = new InsnListReadOnly(method.instructions);
boolean result = injectionPoint.find(method.desc, insns, nodes);
Selector select = injectionPoint.getSelector();
if (nodes.size() != 1 && select == Selector.ONE) {
@@ -406,7 +406,7 @@ public final class MethodSlice {
}
if (!result) {
if (this.owner.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) {
MethodSlice.logger.warn("{} did not match any instructions", this.describe(description));
}
return failValue;
@@ -432,9 +432,9 @@ public final class MethodSlice {
}
private static String describeSlice(String description, ISliceContext owner) {
String annotation = Bytecode.getSimpleName(owner.getAnnotation());
String annotation = Annotations.getSimpleName(owner.getAnnotationNode());
MethodNode method = owner.getMethod();
return String.format("%s->%s(%s)::%s%s", owner.getContext(), annotation, description, method.name, method.desc);
return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc);
}
private static String getSliceName(String id) {
@@ -469,12 +469,17 @@ public final class MethodSlice {
*/
public static MethodSlice parse(ISliceContext info, AnnotationNode node) {
String id = Annotations.<String>getValue(node, "id");
String coord = "slice";
if (!Strings.isNullOrEmpty(id)) {
coord += "." + id;
}
InjectionPointAnnotationContext sliceContext = new InjectionPointAnnotationContext(info, node, coord);
AnnotationNode from = Annotations.<AnnotationNode>getValue(node, "from");
AnnotationNode to = Annotations.<AnnotationNode>getValue(node, "to");
InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null;
InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null;
InjectionPoint fromPoint = from != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, from, "from"), from) : null;
InjectionPoint toPoint = to != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, to, "to"), to) : null;
return new MethodSlice(info, id, fromPoint, toPoint);
}
@@ -99,7 +99,7 @@ public final class MethodSlices {
public static MethodSlices parse(InjectionInfo info) {
MethodSlices slices = new MethodSlices(info);
AnnotationNode annotation = info.getAnnotation();
AnnotationNode annotation = info.getAnnotationNode();
if (annotation != null) {
for (AnnotationNode node : Annotations.<AnnotationNode>getValue(annotation, "slice", true)) {
MethodSlice slice = MethodSlice.parse(info, node);
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Common base classes for injector implementations.
*/
package org.spongepowered.asm.mixin.injection.code;
@@ -32,16 +32,17 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Bytecode;
/**
* A bytecode injector which allows a single argument of a chosen method call to
* be altered.
* be altered. For details see javadoc for {@link ModifyArg &#64;ModifyArg}.
*/
public class ModifyArgInjector extends InvokeInjector {
@@ -31,17 +31,18 @@ import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyArgs;
import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Bytecode;
/**
* A bytecode injector which allows a single argument of a chosen method call to
* be altered.
* be altered. For details see javadoc for {@link ModifyArgs &#64;ModifyArgs}.
*/
public class ModifyArgsInjector extends InvokeInjector {
@@ -53,7 +54,7 @@ public class ModifyArgsInjector extends InvokeInjector {
public ModifyArgsInjector(InjectionInfo info) {
super(info, "@ModifyArgs");
this.argsClassGenerator = info.getContext().getExtensions().<ArgsClassGenerator>getGenerator(ArgsClassGenerator.class);
this.argsClassGenerator = info.getMixin().getExtensions().<ArgsClassGenerator>getGenerator(ArgsClassGenerator.class);
}
/* (non-Javadoc)
@@ -84,7 +85,7 @@ public class ModifyArgsInjector extends InvokeInjector {
+ targetMethod.name + targetMethod.desc + " with no arguments!");
}
String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getContext().getMixin()).getName();
String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getMixin().getMixin()).getName();
boolean withArgs = this.verifyTarget(target);
InsnList insns = new InsnList();
@@ -36,6 +36,7 @@ import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.util.InsnFinder;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
@@ -49,7 +50,8 @@ import org.spongepowered.asm.util.SignaturePrinter;
/**
* A bytecode injector which allows a specific constant value to be identified
* and replaced with a callback
* and replaced with a callback. For details see javadoc for
* {@link ModifyConstant &#64;ModifyConstant}.
*/
public class ModifyConstantInjector extends RedirectInjector {
@@ -133,7 +135,7 @@ public class ModifyConstantInjector extends RedirectInjector {
private void injectConstantModifier(Target target, AbstractInsnNode constNode) {
final Type constantType = Bytecode.getConstantType(constNode);
if (constantType.getSort() <= Type.INT && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (constantType.getSort() <= Type.INT && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
this.checkNarrowing(target, constNode, constantType);
}
@@ -58,14 +58,17 @@ import com.google.common.primitives.Ints;
* 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 upon. For example when hooking the following call:</p>
* invoked upon. For more details see the javadoc for the {@link Redirect
* &#64;Redirect} annotation.</p>
*
* <p>For example when hooking the following call:</p>
*
* <blockquote><pre>
* int abc = 0;
* int def = 1;
* Foo someObject = new Foo();
*
* // Hooking this method
* <del>// Hooking this method</del>
* boolean xyz = someObject.bar(abc, def);</pre>
* </blockquote>
*
@@ -79,8 +82,8 @@ import com.google.common.primitives.Ints;
* 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>
* <p>For field redirections, see the details in {@link Redirect &#64;Redirect}
* for the required signature of the handler method.</p>
*
* <p>For constructor redirections, the signature of the handler method should
* match the constructor itself, return type should be of the type of object
@@ -234,7 +237,7 @@ public class RedirectInjector extends InvokeInjector {
protected RedirectInjector(InjectionInfo info, String annotationType) {
super(info, annotationType);
int priority = info.getContext().getPriority();
int priority = info.getMixin().getPriority();
boolean isFinal = Annotations.getVisible(this.methodNode, Final.class) != null;
this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc);
}
@@ -463,7 +466,7 @@ public class RedirectInjector extends InvokeInjector {
Type elementType = field.type.getElementType();
int valueArgIndex = field.getTotalDimensions();
if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s",
this.annotationType, this, this.info.getContext()), true)) {
this.annotationType, this, this.info.getMixin()), true)) {
elementType = this.methodArgs[valueArgIndex];
}
@@ -774,7 +777,7 @@ public class RedirectInjector extends InvokeInjector {
LabelNode nullCheckSucceeded = new LabelNode();
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded));
this.throwException(insns, RedirectInjector.NPE, String.format("%s %s %s returned null for %s",
this.throwException(insns, extraStack, RedirectInjector.NPE, String.format("%s %s %s returned null for %s",
this.annotationType, type, this, value));
insns.add(nullCheckSucceeded);
extraStack.add();
@@ -0,0 +1,32 @@
/*
* 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.
*/
/**
* Support classes for
* {@link org.spongepowered.asm.mixin.injection.ModifyArgs &#64;ModifyArgs}
* which handle argument bundles
* ({@link org.spongepowered.asm.mixin.injection.invoke.arg.Args}).
*/
package org.spongepowered.asm.mixin.injection.invoke.arg;
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Implementation of injectors which primarily mutate method invocations.
*/
package org.spongepowered.asm.mixin.injection.invoke;
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Utility classes for invoke injectors.
*/
package org.spongepowered.asm.mixin.injection.invoke.util;
@@ -30,6 +30,7 @@ import java.util.ListIterator;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
@@ -199,10 +200,10 @@ public class BeforeLoadLocal extends LocalVariableInjectionPoint {
}
@Override
boolean find(InjectionInfo info, Target target, Collection<AbstractInsnNode> nodes) {
boolean find(InjectionInfo info, InsnList insns, Collection<AbstractInsnNode> nodes, Target target) {
SearchState state = new SearchState();
ListIterator<AbstractInsnNode> iter = target.method.instructions.iterator();
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
@@ -145,13 +145,16 @@ public class LocalVariableDiscriminator {
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
Local[] lvt = new Local[this.baseArgIndex + Bytecode.getArgsSize(target.arguments)];
if (!this.isStatic) {
lvt[0] = new Local("this", Type.getObjectType(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);
for (int local = this.baseArgIndex, arg = 0; local < lvt.length; local++) {
Type argType = target.arguments[arg++];
lvt[local] = new Local("arg" + local, argType);
if (argType.getSize() == 2) {
lvt[++local] = null;
}
}
return lvt;
}
@@ -37,11 +37,13 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.code.InjectorTarget;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.Bytecode;
@@ -54,7 +56,7 @@ import org.spongepowered.asm.util.SignaturePrinter;
* {@link ModifyVariable}.
*/
public class ModifyVariableInjector extends Injector {
/**
* Target context information
*/
@@ -80,7 +82,7 @@ public class ModifyVariableInjector extends Injector {
LocalVariableInjectionPoint(InjectionPointData data) {
super(data);
this.mixin = data.getContext();
this.mixin = data.getMixin();
}
@Override
@@ -88,15 +90,20 @@ public class ModifyVariableInjector extends Injector {
throw new InvalidInjectionException(this.mixin, this.getAtCode() + " injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(InjectionInfo info, Target target, Collection<AbstractInsnNode> nodes);
abstract boolean find(InjectionInfo info, InsnList insns, Collection<AbstractInsnNode> nodes, Target target);
}
/**
* Decorator key for Context decoration
*/
private static final String LOCALS_CONTEXT_KEY = "localcontext";
/**
* True to consider only method args
*/
private final LocalVariableDiscriminator discriminator;
/**
* @param info Injection info
* @param discriminator discriminator
@@ -107,12 +114,13 @@ public class ModifyVariableInjector extends Injector {
}
@Override
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget,
Collection<AbstractInsnNode> nodes) {
if (injectionPoint instanceof LocalVariableInjectionPoint) {
Target target = this.info.getContext().getTargetMethod(into);
return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, target, nodes);
return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, injectorTarget.getSlice(injectionPoint), nodes,
injectorTarget.getTarget());
}
return injectionPoint.find(into.desc, insns, nodes);
return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes);
}
/* (non-Javadoc)
@@ -134,6 +142,12 @@ public class ModifyVariableInjector extends Injector {
}
}
@Override
protected void preInject(Target target, InjectionNode node) {
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
node.<Context>decorate(ModifyVariableInjector.LOCALS_CONTEXT_KEY, context);
}
/**
* Do the injection
*/
@@ -143,15 +157,27 @@ public class ModifyVariableInjector extends Injector {
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());
Context context = node.<Context>getDecoration(ModifyVariableInjector.LOCALS_CONTEXT_KEY);
if (context == null) {
throw new InjectionError(String.format(
"%s injector target is missing CONTEXT decoration for %s. PreInjection failure or illegal internal state change",
this.annotationType, this.info));
}
if (this.discriminator.printLVT()) {
this.printLocals(target, context);
}
this.checkTargetForNode(target, node, RestrictTargetLevel.ALLOW_ALL);
InjectorData handler = new InjectorData(target, "handler", false);
if (this.returnType == Type.VOID_TYPE) {
throw new InvalidInjectionException(this.info, String.format(
"%s %s method %s from %s has an invalid signature, cannot return a VOID type.",
this.annotationType, handler, this, this.info.getMixin()));
}
this.validateParams(handler, this.returnType, this.returnType);
Extension extraStack = target.extendStack();
@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* Implementation of variable modifier injector specified by
* {@link org.spongepowered.asm.mixin.injection.ModifyVariable
* &#64;ModifyVariable}
*/
package org.spongepowered.asm.mixin.injection.modify;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Injectors are class postprocessors which search for annotated methods merged
* by mixins and perform weaving operations as requested.
*/
package org.spongepowered.asm.mixin.injection;
@@ -71,41 +71,41 @@ import com.google.common.primitives.Longs;
* <dt>ordinal</dt>
* <dd>The ordinal position of the constant opcode to match. The default value
* is <b>-1</b> which supresses ordinal matching</dd>
* <dt><em>named argument</em> nullValue</dt>
* <dt><i>named argument:</i> nullValue</dt>
* <dd>To match <tt>null</tt> literals in the method body, set this to
* <tt>true</tt></dd>
* <dt><em>named argument</em> intValue</dt>
* <dt><i>named argument:</i> intValue</dt>
* <dd>To match <tt>int</tt> literals in the method body. See also the
* <em>expandZeroConditions</em> argument below for concerns when matching
* conditional zeroes.</dd>
* <dt><em>named argument</em> floatValue</dt>
* <dt><i>named argument:</i> floatValue</dt>
* <dd>To match <tt>float</tt> literals in the method body.</dd>
* <dt><em>named argument</em> longValue</dt>
* <dt><i>named argument:</i> longValue</dt>
* <dd>To match <tt>long</tt> literals in the method body.</dd>
* <dt><em>named argument</em> doubleValue</dt>
* <dt><i>named argument:</i> doubleValue</dt>
* <dd>To match <tt>double</tt> literals in the method body.</dd>
* <dt><em>named argument</em> stringValue</dt>
* <dt><i>named argument:</i> stringValue</dt>
* <dd>To match {@link String} literals in the method body.</dd>
* <dt><em>named argument</em> classValue</dt>
* <dt><i>named argument:</i> classValue</dt>
* <dd>To match {@link Class} literals in the method body.</dd>
* <dt><em>named argument</em> log</dt>
* <dt><i>named argument:</i> log</dt>
* <dd>Enable debug logging when searching for matching opcodes.</dd>
* <dt><em>named argument</em> expandZeroConditions</dt>
* <dt><i>named argument:</i> expandZeroConditions</dt>
* <dd>See the {@link Constant#expandZeroConditions} option, this argument
* should be a list of {@link Condition} names</dd>
* </dl>
*
* <p>Examples:</p>
* <blockquote><pre>
* // Find all integer constans with value 4
* <del>// Find all integer constans with value 4</del>
* &#064;At(value = "CONSTANT", args = "intValue=4")</pre>
* </blockquote>
* <blockquote><pre>
* // Find the String literal "foo"
* <del>// Find the String literal "foo"</del>
* &#064;At(value = "CONSTANT", args = "stringValue=foo"</pre>
* </blockquote>
* <blockquote><pre>
* // Find all integer constants with value 0 and expand conditionals
* <del>// Find integer constants with value 0 and expand conditionals</del>
* &#064;At(
* value = "CONSTANT",
* args = {
@@ -182,9 +182,9 @@ public class BeforeConstant extends InjectionPoint {
String strClassValue = data.get("classValue", null);
this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null;
this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args");
this.matchByType = this.validateDiscriminator(data.getMixin(), "V", empty, "in @At(\"CONSTANT\") args");
if ("V".equals(this.matchByType)) {
throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
throw new InvalidInjectionException(data.getMixin(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
}
List<Condition> conditions = new ArrayList<Condition>();
@@ -236,7 +236,7 @@ public class BeforeConstant extends InjectionPoint {
if (matchesInsn) {
this.log(" BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal);
if (this.ordinal == -1 || this.ordinal == ordinal) {
this.log(" BeforeConstant found {}", Bytecode.describeNode(insn).trim());
this.log(" BeforeConstant found {}", Bytecode.describeNode(insn, false));
nodes.add(insn);
found = true;
}
@@ -280,7 +280,7 @@ public class BeforeConstant extends InjectionPoint {
}
Object value = Bytecode.getConstant(insn);
if (value == null) {
if (value == Type.VOID_TYPE) {
this.log(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue);
return this.nullValue || Constants.OBJECT_DESC.equals(this.matchByType);
} else if (value instanceof Integer) {
@@ -49,21 +49,33 @@ import org.spongepowered.asm.util.Bytecode;
* <dl>
* <dt>target</dt>
* <dd>A {@link ITargetSelector Target Selector} which identifies the target
* field.</dd>
* field.</dd>
* <dt>opcode</dt>
* <dd>The {@link Opcodes opcode} of the field access, must be one of
* GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.</dd>
* GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.</dd>
* <dt>ordinal</dt>
* <dd>The ordinal position of the field access to match. For example if the
* field is referenced 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* field is referenced 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* <dt><i>named argument:</i> array</dt>
* <dd>For matching accesses to an array field element following a GETFIELD or
* GETSTATIC. Specify <tt>get</tt>, <tt>set</tt> or <tt>length</tt> to match
* the desired operation.</dd>
* <dt><i>named argument:</i> fuzz</dt>
* <dd>When matching array operations using <tt>array</tt> the injection point
* will by default search up to 8 instructions after the matched field insn.
* However in some cases the array operation may be further from the matched
* GETFIELD or GETSTATIC and the amount to search (the "fuzz factor" can be
* specified using this argument. Likewise to optimise the search against
* false positives, this value can be specified as a lower value if desired.
* Has no effect if <tt>array</tt> is not specified.</dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* <blockquote><code>
* &#064;At(value = "FIELD", target="field_59_z:I", opcode = Opcodes.GETFIELD)
* </pre>
* </code>
* </blockquote>
*
* <p>Matching array access:</p>
@@ -72,9 +84,10 @@ import org.spongepowered.asm.util.Bytecode;
* operation. To enable this behaviour specify the <tt>array</tt> named-argument
* with the desired operation:</p>
*
* <blockquote><pre>
* &#064;At(value = "FIELD", target="myIntArray:[I", args = "array=get")
* </pre>
* <blockquote><code>
* &#064;At(value = "FIELD", target="myIntArray:[I", opcode
* = Opcodes.GETFIELD, args = "array=get")
* </code>
* </blockquote>
*
* <p>See {@link Redirect} for information on array element redirection.</p>
@@ -64,7 +64,7 @@ public class BeforeFinalReturn extends InjectionPoint {
public BeforeFinalReturn(InjectionPointData data) {
super(data);
this.context = data.getContext();
this.context = data.getMixin();
}
@Override
@@ -35,10 +35,14 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
@@ -108,7 +112,12 @@ public class BeforeInvoke extends InjectionPoint {
/**
*
*/
protected final IMixinContext context;
protected final IInjectionPointContext context;
/**
*
*/
protected final IMixinContext mixin;
/**
* Logger reference
@@ -128,8 +137,9 @@ public class BeforeInvoke extends InjectionPoint {
this.log = data.get("log", false);
this.className = this.getClassName();
this.context = data.getContext();
this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE)
&& !this.context.getReferenceMapper().isDefault();
this.mixin = data.getMixin();
this.allowPermissive = this.mixin.getOption(Option.REFMAP_REMAP) && this.mixin.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE)
&& !this.mixin.getReferenceMapper().isDefault();
}
private String getClassName() {
@@ -155,14 +165,14 @@ public class BeforeInvoke extends InjectionPoint {
*/
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
this.log("{} is searching for an injection point in method with descriptor {}", this.className, desc);
this.log("{}->{} is searching for an injection point in method with descriptor {}", this.context, this.className, desc);
boolean hasDescriptor = this.target instanceof ITargetSelectorByName && ((ITargetSelectorByName)this.target).getDesc() == null;
boolean found = this.find(desc, insns, nodes, this.target, SearchType.STRICT);
if (!found && hasDescriptor && this.allowPermissive) {
this.logger.warn("STRICT match for {} using \"{}\" in {} returned 0 results, attempting permissive search. "
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.context);
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.mixin);
found = this.find(desc, insns, nodes, this.target, SearchType.PERMISSIVE);
}
@@ -174,10 +184,10 @@ public class BeforeInvoke extends InjectionPoint {
return false;
}
ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector;
ITargetSelector target = (searchType == SearchType.PERMISSIVE ? selector.configure(Configure.PERMISSIVE) : selector)
.configure(Configure.SELECT_INSTRUCTION);
int ordinal = 0;
int found = 0;
int ordinal = 0, found = 0, matchCount = 0;
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext()) {
@@ -185,23 +195,22 @@ public class BeforeInvoke extends InjectionPoint {
if (this.matchesInsn(insn)) {
MemberInfo nodeInfo = new MemberInfo(insn);
this.log("{} is considering insn {}", this.className, nodeInfo);
this.log("{}->{} is considering {}", this.context, this.className, nodeInfo);
if (target.match(insn).isExactMatch()) {
this.log("{} > found a matching insn, checking preconditions...", this.className);
if (target.match(ElementNode.<AbstractInsnNode>of(insn)).isExactMatch()) {
this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className);
if (++matchCount > target.getMaxMatchCount()) {
break;
}
if (this.matchesOrdinal(ordinal)) {
this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal);
this.log("{}->{} > > > found a matching insn at ordinal {}", this.context, this.className, ordinal);
if (this.addInsn(insns, nodes, insn)) {
found++;
}
if (this.ordinal == ordinal) {
break;
}
}
ordinal++;
}
}
@@ -211,7 +220,12 @@ public class BeforeInvoke extends InjectionPoint {
if (searchType == SearchType.PERMISSIVE && found > 1) {
this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. "
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found);
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.mixin, found);
}
if (matchCount < target.getMinMatchCount()) {
throw new SelectorConstraintException(target, String.format("%s did not match the required number of targets (required=%d, matched=%d)",
target, selector.getMinMatchCount(), matchCount));
}
return found > 0;
@@ -231,7 +245,7 @@ public class BeforeInvoke extends InjectionPoint {
}
protected boolean matchesOrdinal(int ordinal) {
this.log("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal);
this.log("{}->{} > > comparing target ordinal {} with current ordinal {}", this.context, this.className, this.ordinal, ordinal);
return this.ordinal == -1 || this.ordinal == ordinal;
}
@@ -52,7 +52,7 @@ import com.google.common.base.Strings;
* {@link org.spongepowered.asm.mixin.injection.At At}:</p>
*
* <dl>
* <dt><em>named argument</em> class (or specify using <tt>target</tt></dt>
* <dt><i>named argument:</i> class (or specify using <tt>target</tt></dt>
* <dd>The value of the NEW node to look for, the fully-qualified class name
* </dd>
* <dt>ordinal</dt>
@@ -70,16 +70,16 @@ import com.google.common.base.Strings;
*
* <p>Examples:</p>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt>
* <del>// Find all NEW opcodes for <tt>String</tt></del>
* &#064;At(value = "NEW", args = "class=java/lang/String")</pre>
* </blockquote>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt>
* <del>// Find all NEW opcodes for <tt>String</tt></del>
* &#064;At(value = "NEW", target = "java/lang/String"</pre>
* </blockquote>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt> which are constructed using the
* // ctor which takes an array of <tt>char</tt>
* <del>// Find all NEW opcodes for <tt>String</tt> which are constructed
* // using the ctor which takes an array of <tt>char</tt></del>
* &#064;At(value = "NEW", target = "([C)Ljava/lang/String;"</pre>
* </blockquote>
*
@@ -113,7 +113,7 @@ public class BeforeNew extends InjectionPoint {
String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/'));
ITargetSelector member = TargetSelector.parseAndValidate(target, data.getContext());
if (!(member instanceof ITargetSelectorConstructor)) {
throw new InvalidInjectionPointException(data.getContext(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s",
throw new InvalidInjectionPointException(data.getMixin(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s",
target, data.getDescription());
}
ITargetSelectorConstructor targetSelector = (ITargetSelectorConstructor)member;
@@ -64,7 +64,7 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
* the method is invoked 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* <dt><em>named argument</em> ldc</dt>
* <dt><i>named argument:</i> ldc</dt>
* <dd>The value of the LDC node to look for prior to the method invocation
* </dd>
* </dl>
@@ -122,7 +122,7 @@ public class BeforeStringInvoke extends BeforeInvoke {
if (insn instanceof LdcInsnNode) {
LdcInsnNode node = (LdcInsnNode) insn;
if (node.cst instanceof String && this.ldcValue.equals(node.cst)) {
this.log("{} > found a matching LDC with value {}", this.className, node.cst);
this.log("{}->{} > found a matching LDC with value {}", this.context, this.className, node.cst);
this.foundLdc = true;
return;
}
@@ -133,7 +133,7 @@ public class BeforeStringInvoke extends BeforeInvoke {
@Override
protected boolean matchesOrdinal(int ordinal) {
this.log("{} > > found LDC \"{}\" = {}", this.className, this.ldcValue, this.foundLdc);
this.log("{}->{} > > found LDC \"{}\" = {}", this.context, this.className, this.ldcValue, this.foundLdc);
return this.foundLdc && super.matchesOrdinal(ordinal);
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Built-in {@link org.spongepowered.asm.mixin.injection.InjectionPoint
* injection point} classes.
*/
package org.spongepowered.asm.mixin.injection.points;
@@ -0,0 +1,754 @@
/*
* 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.selectors;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.util.Handles;
import com.google.common.base.Strings;
/**
* Wrapper for all node types supported by {@link ITargetSelector target
* selectors} ({@link FieldNode}, {@link MethodNode}, {@link FieldInsnNode},
* {@link MethodInsnNode} and {@link InvokeDynamicInsnNode}) which allows access
* to common properties of things which are basically "arbitrary node with
* owner, name and descriptor"
*
* @param <TNode> node type
*/
public abstract class ElementNode<TNode> {
/**
* Element node type, returned by <tt>getType</tt> so consumers don't need
* to do instanceof checks, and allows switching on element type in a more
* expressive way
*/
public static enum NodeType {
/**
* None or unknown type
*/
UNDEFINED(false, false, false),
/**
* A method node
*/
METHOD(true, false, false),
/**
* A field node
*/
FIELD(false, true, false),
/**
* An invoke instruction
*/
METHOD_INSN(false, false, true),
/**
* A get or put field instruction
*/
FIELD_INSN(false, false, true),
/**
* An INVOKEDYNAMIC instruction
*/
INVOKEDYNAMIC_INSN(false, false, true);
/**
* Whether this node holds a method, implies that calling <tt>getMethod
* </tt> will return a value
*/
public final boolean hasMethod;
/**
* Whether this node holds a field, implies that calling <tt>getField
* </tt> will return a value
*/
public final boolean hasField;
/**
* Whether this node holds an insn, implies that calling <tt>getInsn
* </tt> will return a value
*/
public final boolean hasInsn;
private NodeType(boolean isMethod, boolean isField, boolean isInsn) {
this.hasMethod = isMethod;
this.hasField = isField;
this.hasInsn = isInsn;
}
}
/**
* ElementNode for MethodNode
*/
static class ElementNodeMethod extends ElementNode<MethodNode> {
private final ClassNode owner;
private final MethodNode method;
ElementNodeMethod(ClassNode owner, MethodNode method) {
this.owner = owner;
this.method = method;
}
@Override
public NodeType getType() {
return NodeType.METHOD;
}
@Override
public MethodNode getMethod() {
return this.method;
}
@Override
public String getOwner() {
return this.owner != null ? this.owner.name : null;
}
@Override
public String getName() {
return this.method.name;
}
@Override
public String getDesc() {
return this.method.desc;
}
@Override
public String getSignature() {
return this.method.signature;
}
@Override
public MethodNode get() {
return this.method;
}
@Override
public boolean equals(Object obj) {
return this.method.equals(obj);
}
@Override
public int hashCode() {
return this.method.hashCode();
}
}
/**
* ElementNode for FieldNode
*/
static class ElementNodeField extends ElementNode<FieldNode> {
private final ClassNode owner;
private final FieldNode field;
ElementNodeField(ClassNode owner, FieldNode field) {
this.owner = owner;
this.field = field;
}
@Override
public NodeType getType() {
return NodeType.FIELD;
}
@Override
public boolean isField() {
return true;
}
@Override
public FieldNode getField() {
return this.field;
}
@Override
public String getOwner() {
return this.owner != null ? this.owner.name : null;
}
@Override
public String getName() {
return this.field.name;
}
@Override
public String getDesc() {
return this.field.desc;
}
@Override
public String getSignature() {
return this.field.signature;
}
@Override
public FieldNode get() {
return this.field;
}
@Override
public boolean equals(Object obj) {
return this.field.equals(obj);
}
@Override
public int hashCode() {
return this.field.hashCode();
}
}
/**
* ElementNode for MethodInsnNode
*/
static class ElementNodeMethodInsn extends ElementNode<MethodInsnNode> {
private MethodInsnNode insn;
ElementNodeMethodInsn(MethodInsnNode method) {
this.insn = method;
}
@Override
public NodeType getType() {
return NodeType.METHOD_INSN;
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public String getSignature() {
return null;
}
@Override
public MethodInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* ElementNode for InvokeDynamicInsnNode
*/
static class ElementNodeInvokeDynamicInsn extends ElementNode<InvokeDynamicInsnNode> {
private InvokeDynamicInsnNode insn;
private Type samMethodType;
private Handle implMethod;
private Type instantiatedMethodType;
ElementNodeInvokeDynamicInsn(InvokeDynamicInsnNode invokeDynamic) {
this.insn = invokeDynamic;
if (invokeDynamic.bsmArgs != null && invokeDynamic.bsmArgs.length > 1) {
Object samMethodType = invokeDynamic.bsmArgs[0];
Object implMethod = invokeDynamic.bsmArgs[1];
Object instantiatedMethodType = invokeDynamic.bsmArgs[2];
if (samMethodType instanceof Type && implMethod instanceof Handle && instantiatedMethodType instanceof Type) {
this.samMethodType = (Type)samMethodType;
this.implMethod = (Handle)implMethod;
this.instantiatedMethodType = (Type)instantiatedMethodType;
}
}
}
@Override
public NodeType getType() {
return NodeType.INVOKEDYNAMIC_INSN;
}
@Override
public boolean isField() {
return this.implMethod != null && Handles.isField(this.implMethod);
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.implMethod != null ? this.implMethod.getOwner() : this.insn.name;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getSyntheticName() {
return this.implMethod != null ? this.implMethod.getName() : this.insn.name;
}
@Override
public String getDesc() {
return this.implMethod != null ? this.implMethod.getDesc() : this.insn.desc;
}
@Override
public String getDelegateDesc() {
return this.samMethodType != null ? this.samMethodType.getDescriptor() : this.getDesc();
}
@Override
public String getImplDesc() {
return this.instantiatedMethodType != null ? this.instantiatedMethodType.getDescriptor() : this.getDesc();
}
@Override
public String getSignature() {
return null;
}
@Override
public InvokeDynamicInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* ElementNode for FieldInsnNode
*/
static class ElementNodeFieldInsn extends ElementNode<FieldInsnNode> {
private FieldInsnNode insn;
ElementNodeFieldInsn(FieldInsnNode field) {
this.insn = field;
}
@Override
public NodeType getType() {
return NodeType.FIELD_INSN;
}
@Override
public boolean isField() {
return true;
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public String getSignature() {
return null;
}
@Override
public FieldInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* Wrapper iterator for method insns
*/
static class ElementNodeIterator implements Iterator<ElementNode<AbstractInsnNode>> {
private final Iterator<AbstractInsnNode> iter;
private final boolean filterDynamic;
ElementNodeIterator(Iterator<AbstractInsnNode> iter, boolean filterDynamic) {
this.iter = iter;
this.filterDynamic = filterDynamic;
}
@Override
public boolean hasNext() {
return this.iter.hasNext();
}
@Override
public ElementNode<AbstractInsnNode> next() {
AbstractInsnNode elem = this.iter.next();
return !this.filterDynamic || (elem != null && elem.getOpcode() == Opcodes.INVOKEDYNAMIC) ? ElementNode.of(elem) : null;
}
}
/**
* Wrapper for InsnList which returns node iterator
*/
static class ElementNodeIterable implements Iterable<ElementNode<AbstractInsnNode>> {
private final Iterable<AbstractInsnNode> iterable;
private final boolean filterDynamic;
public ElementNodeIterable(Iterable<AbstractInsnNode> iterable, boolean filterDynamic) {
this.iterable = iterable;
this.filterDynamic = filterDynamic;
}
@Override
public Iterator<ElementNode<AbstractInsnNode>> iterator() {
return new ElementNodeIterator(this.iterable.iterator(), this.filterDynamic);
}
}
/**
* Get whether this element is a field type and the descriptor is a bare
* type descriptor without arguments. Otherwise assumes the descriptor is a
* method descriptor.
*/
public boolean isField() {
return false;
}
/**
* Get the type of this ElementNode, the return value can be used to
* determine which accessor ({@link #getMethod}, {@link #getField}
*/
public abstract NodeType getType();
/**
* Get the {@link MethodNode} if this member is a method, otherwise returns
* <tt>null</tt>
*/
public MethodNode getMethod() {
return null;
}
/**
* Get the {@link FieldNode} if this member is a field, otherwise returns
* <tt>null</tt>
*/
public FieldNode getField() {
return null;
}
/**
* Get the {@link AbstractInsnNode instruction} if this member is an insn,
* otherwise returns <tt>null</tt>
*/
public AbstractInsnNode getInsn() {
return null;
}
/**
* Get the element owner's name, if this element has an owner, otherwise
* returns <tt>null</tt>
*/
public abstract String getOwner();
/**
* Get the element name
*/
public abstract String getName();
/**
* Get the synthetic element name. For INVOKEDYNAMIC elements this is the
* real name of the lambda method implementing the delegate.
*/
public String getSyntheticName() {
return this.getName();
}
/**
* Get the element descriptor. For INVOKEDYNAMIC this is the full descriptor
* of the lambda (including prepended captures).
*/
public abstract String getDesc();
/**
* For INVOKEDYNAMIC elements, returns original descriptor of the delegate.
*/
public String getDelegateDesc() {
return this.getDesc();
}
/**
* For INVOKEDYNAMIC elements, returns specialised descriptor of the
* delegate (lambda descriptor without prepended captures), can be the same
* as the delegate descriptor or more specialised.
*/
public String getImplDesc() {
return this.getDesc();
}
/**
* Get the element signature, can be <tt>null</tt>
*/
public abstract String getSignature();
/**
* Returns the node with horrible duck typing
*/
public abstract TNode get();
@Override
public String toString() {
String desc = Strings.nullToEmpty(this.getDesc());
if (!desc.isEmpty() && this.isField()) {
desc = ":" + desc;
}
String owner = Strings.nullToEmpty(this.getOwner());
if (!owner.isEmpty()) {
owner = "L" + owner + ";";
}
return String.format("%s%s%s", owner, Strings.nullToEmpty(this.getName()), desc);
}
/**
* Create an ElementNode wrapper for the supplied method node
*
* @param owner class which owns the method or <tt>null</tt>
* @param method Method node to wrap
* @return ElementNode
*/
public static ElementNode<MethodNode> of(ClassNode owner, MethodNode method) {
return new ElementNodeMethod(owner, method);
}
/**
* Create an ElementNode wrapper for the supplied field node
*
* @param owner class which owns the field or <tt>null</tt>
* @param field Field node to wrap
* @return ElementNode
*/
public static ElementNode<FieldNode> of(ClassNode owner, FieldNode field) {
return new ElementNodeField(owner, field);
}
/**
* Create an ElementNode wrapper for the supplied node object
*
* @param owner class which owns the node or <tt>null</tt>
* @param node Node to wrap
* @param <TNode> Node type
* @return ElementNode
* @throws IllegalArgumentException if the supplied argument is not a
* {@link MethodNode} or {@link FieldNode}
*/
@SuppressWarnings("unchecked")
public static <TNode> ElementNode<TNode> of(ClassNode owner, TNode node) {
if (node instanceof ElementNode) {
return (ElementNode<TNode>)node;
} else if (node instanceof MethodNode) {
return (ElementNode<TNode>)new ElementNodeMethod(owner, (MethodNode)node);
} else if (node instanceof FieldNode) {
return (ElementNode<TNode>)new ElementNodeField(owner, (FieldNode)node);
} else if (node instanceof MethodInsnNode) {
return (ElementNode<TNode>)new ElementNodeMethodInsn((MethodInsnNode)node);
} else if (node instanceof InvokeDynamicInsnNode) {
return (ElementNode<TNode>)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node);
} else if (node instanceof FieldInsnNode) {
return (ElementNode<TNode>)new ElementNodeFieldInsn((FieldInsnNode)node);
}
throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName());
}
/**
* Create an ElementNode wrapper for the supplied node object
*
* @param node Node to wrap
* @param <TNode> Node type
* @return ElementNode
* @throws IllegalArgumentException if the supplied argument is not a
* {@link MethodNode} or {@link FieldNode}
*/
@SuppressWarnings("unchecked")
public static <TNode extends AbstractInsnNode> ElementNode<TNode> of(TNode node) {
if (node instanceof MethodInsnNode) {
return (ElementNode<TNode>)new ElementNodeMethodInsn((MethodInsnNode)node);
} else if (node instanceof InvokeDynamicInsnNode) {
return (ElementNode<TNode>)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node);
} else if (node instanceof FieldInsnNode) {
return (ElementNode<TNode>)new ElementNodeFieldInsn((FieldInsnNode)node);
}
return null;
}
/**
* Convert the supplied list of nodes to a list of wrapped ElementNodes
*
* @param owner Owner of the supplied nodes, can be <tt>null</tt>
* @param list List of nodes
* @param <TNode> Node type
* @return List of wrapped nodes
*/
public static <TNode> List<ElementNode<TNode>> listOf(ClassNode owner, List<TNode> list) {
List<ElementNode<TNode>> nodes = new ArrayList<ElementNode<TNode>>();
for (TNode node : list) {
nodes.add(ElementNode.<TNode>of(owner, node));
}
return nodes;
}
/**
* Get a list of wrapped ElementNodes for the fields of the supplied owner
* class
*
* @param owner Class to get fields, must not be <tt>null</tt>
* @return List of wrapped nodes
*/
public static List<ElementNode<FieldNode>> fieldList(ClassNode owner) {
List<ElementNode<FieldNode>> fields = new ArrayList<ElementNode<FieldNode>>();
for (FieldNode field : owner.fields) {
fields.add(new ElementNodeField(owner, field));
}
return fields;
}
/**
* Get a list of wrapped ElementNodes for the methods of the supplied owner
* class
*
* @param owner Class to get methods, must not be <tt>null</tt>
* @return List of wrapped nodes
*/
public static List<ElementNode<MethodNode>> methodList(ClassNode owner) {
List<ElementNode<MethodNode>> methods = new ArrayList<ElementNode<MethodNode>>();
for (MethodNode method : owner.methods) {
methods.add(new ElementNodeMethod(owner, method));
}
return methods;
}
/**
* Get a wrapped version of the supplied insn list which returns element
* nodes for each (supported) instruction (FieldInsnNode, MethodInsnNode and
* InvokeDynamicInsnNode).
*
* @param insns Insn list to wrap
* @return Wrapper for insn list
*/
public static Iterable<ElementNode<AbstractInsnNode>> insnList(InsnList insns) {
return new ElementNodeIterable(insns, false);
}
/**
* Get a wrapped version of the supplied insn list which returns element
* nodes for every INVOKEDYNAMIC instruction only
*
* @param insns Insn list to wrap
* @return Wrapper for insn list
*/
public static Iterable<ElementNode<AbstractInsnNode>> dynamicInsnList(InsnList insns) {
return new ElementNodeIterable(insns, true);
}
}
@@ -0,0 +1,87 @@
/*
* 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.selectors;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Context passed to a {@link ITargetSelector Target Selector} in order to
* support context-sensitive behaviour for the selector. For example obtaining
* the name of the source mixin, or the element containing the selector itself.
*/
public interface ISelectorContext {
/**
* Get the parent (outer/containing) context. Can be null if this is a root
* element such as an injector method, in which case the parent is the mixin
* instead.
*/
public abstract ISelectorContext getParent();
/**
* Get the mixin containing this selector.
*/
public abstract IMixinContext getMixin();
/**
* Get the root method upon which this selector is operating, usually the
* injector method
*/
public abstract Object getMethod();
/**
* Get the root annotation for the selector, for example the injector or
* accessor annotation
*/
public abstract IAnnotationHandle getAnnotation();
/**
* Get the annotation for this selector, for example the &#064;At annotation
*/
public abstract IAnnotationHandle getSelectorAnnotation();
/**
* Get the coordinate for this selector. This is the local coordinate of the
* selector without any parent parts. Parent parts are prepended by
* consumers during the resolve process.
*
* @param leaf True if getting the coordinate when this element is a leaf,
* false if getting the coordinate when it is a parent
*/
public abstract String getSelectorCoordinate(boolean leaf);
/**
* Remap a reference in the context of this selector, usually via the local
* refmap of the mixin configuration but can be overridden as needed, for
* example to provide selector-local remap behaviour.
*
* @param reference Reference to remap
* @return Remapped reference or original reference if not remapped, must
* not return null!
*/
public abstract String remap(String reference);
}
@@ -24,10 +24,9 @@
*/
package org.spongepowered.asm.mixin.injection.selectors;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.ElementNode;
/**
* Target Selectors are used to identify target members in a class, with the
@@ -40,13 +39,137 @@ import org.spongepowered.asm.util.asm.ElementNode;
* <p><b>Explicit</b> Target Selectors are handled internally using
* {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the
* supported variants and examples.</p>
*
* <blockquote><code>
* <del>// An example explicit target selector</del><br />
* Lfully/qualified/OwnerClass;methodName*(III)V
* </code></blockquote>
*
* <h3>Pattern Target Selectors (Regex Selectors)</h3>
*
* <p><b>Pattern</b> Target Selectors are handled internally using
* {@link MemberMatcher}, see the javadoc for {@link MemberMatcher} for the
* supported variants and examples. Pattern Selectors always end with a forward
* slash character.</p>
*
* <blockquote><code>
* <del>// Matches candidates ending with "Bar" and which take a single int
* <br /></del>
* /bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// The same example but with "name" explicitly specified (optional)
* <br /></del>
* name=/bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// Matches candidates whose name contains "Entity"</del><br />
* /Entity/
* </code></blockquote>
*
* <h3>Dynamic Target Selectors</h3>
*
* <p><b>Dynamic</b> Target Selectors can be built-in or user-supplied types
* with their own specialised syntax or behaviour.</p>
*
* <h4>Built-in dynamic selectors:</h4>
*
* <ul>
* <li>{@link DynamicSelectorDesc &#64;Desc Selector}: Selector which uses
* descriptors defined in {@link Desc &#64;Desc} annotations</li>
* </ul>
*
* <p>Dynamic selectors are specified in the following format, and can be
* recognised by the fact that the selector string starts with "<tt>&#64;</tt>":
* </p>
*
* <blockquote><pre>
* <del>// Built-in dynamic selector without argument string</del>
* &#064;SelectorId
*
* <del>// Built-in dynamic selector with empty argument string</del>
* &#064;SelectorId()
*
* <del>// Built-in dynamic selector with argument</del>
* &#064;SelectorId(custom,argument,string,in,any,format)
*
* <del>// User-provided dynamic selector with argument. Note that
* // user-provided dynamic selectors are namespaced to avoid conflicts.</del>
* &#064;Namespace:SelectorId(some arguments)</pre>
* </blockquote>
*
* <p>The exact format of the argument string is specified by the dynamic
* selector itself, consult the documentation for the dynamic selector you are
* using for details on the required format.</p>
*
*/
public interface ITargetSelector {
/**
* Available selector reconfigurations
*/
public enum Configure {
/**
* Configure this selector for matching members in a class. Usually used
* to set defaults for match limits based on role.
*/
SELECT_MEMBER(0),
/**
* Configure this selector for matching field and method instructions in
* a method body. Usually used to set defaults for match limits.
*/
SELECT_INSTRUCTION(0),
/**
* Where supported, changes the owner selection to the specified value.
*/
MOVE(1),
/**
* Where supported, changes the owner selection to match all owners,
* retaining other properties.
*/
ORPHAN(0),
/**
* Where supported, changes the descriptor to the specified value.
*/
TRANSFORM(1),
/**
* Where supported, changes the descriptor to match all target
* descriptors, retaining other properties
*/
PERMISSIVE(0),
/**
* Where supported, removes the min and max limits for the selector,
* allowing it to return as many or as few matches as required.
*/
CLEAR_LIMITS(0);
private int requiredArgs;
private Configure(int requiredArgs) {
this.requiredArgs = requiredArgs;
}
public void checkArgs(String... args) throws IllegalArgumentException {
int argc = args == null ? 0 : args.length;
if (argc < this.requiredArgs) {
throw new IllegalArgumentException("Insufficient arguments for " + this.name() + " mutation. Required " + this.requiredArgs
+ " but received " + argc);
}
}
}
/**
* Get the next target selector in this path (or <tt>null</tt> if this
* selector is the last selector in the chain. Called at recurse points in
* the subject in order to match against the child subject.
* the subject in order to match against the child subject.
*
* <p>Can return null</p>
*/
public abstract ITargetSelector next();
@@ -55,17 +178,22 @@ public interface ITargetSelector {
* supplied arguments. Results from this method should be idempotent in
* terms of the configuration of the returned object, but do not have to
* necessarily return the same object if the callee already matches the
* supplied configuration, though this is generally the case.
* supplied configuration, or if the requested mutation is not supported by
* the selector, though this is generally the case.
*
* <p>In other words, calling <tt>configure("foo")</tt> when this object is
* <i>already</i> configured according to "foo" may simply return this
* object, or might return an identically-configured copy.</p>
* <p>In other words, calling <tt>configure(Configure.ORPHAN)</tt> when this
* object is <i>already</i> an orphan or does not support orphaning, may
* simply return this object, or might return an identically-configured
* copy.</p>
*
* <p>Must not return null, defaults to returning unmodified selector.</p>
*
* @param request Requested operation
* @param args Configuration arguments
* @return Configured selector, may return this selector if the specified
* condition is already satisfied
*/
public abstract ITargetSelector configure(String... args);
public abstract ITargetSelector configure(Configure request, String... args);
/**
* Perform basic sanity-check validation of the selector, checks that the
@@ -86,12 +214,17 @@ public interface ITargetSelector {
* @param context Context to attach to
* @return Attached selector
*/
public abstract ITargetSelector attach(IMixinContext context) throws InvalidSelectorException;
public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException;
/**
* Number of candidates which this selector should match
* Minimum number of candidates this selector must match
*/
public abstract int getMatchCount();
public abstract int getMinMatchCount();
/**
* Maximum number of candidates this selector can match
*/
public abstract int getMaxMatchCount();
/**
* Test whether this selector matches the supplied element node
@@ -101,13 +234,5 @@ public interface ITargetSelector {
* @return true if this selector can match the supplied field
*/
public abstract <TNode> MatchResult match(ElementNode<TNode> node);
/**
* Test whether this selector matches the supplied instruction node
*
* @param insn instruction node to test
* @return true if this selector can match the supplied instruction
*/
public abstract MatchResult match(AbstractInsnNode insn);
}
@@ -44,43 +44,6 @@ public interface ITargetSelectorByName extends ITargetSelector {
*/
public abstract String getDesc();
/**
* Get whether this reference is fully qualified
*
* @return true if all components of this reference are non-null
*/
public abstract boolean isFullyQualified();
/**
* Get whether this target selector is definitely a field, the output of
* this method is undefined if {@link #isFullyQualified} returns false.
*
* @return true if this is definitely a field
*/
public abstract boolean isField();
/**
* Get whether this member represents a constructor
*
* @return true if member name is <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Get a representation of this selector as a complete descriptor
*/
@@ -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.mixin.injection.selectors;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Decoration interface for dynamic target selectors
*/
public interface ITargetSelectorDynamic extends ITargetSelector {
/**
* Decoration for subclasses which indicates id used for a specific selector
* when specified, for example <tt>@MyNamespace:MySelector(argshere)</tt>
* would specify "MySelector"
*/
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.TYPE)
public @interface SelectorId {
/**
* Namespace for this code. Final selectors will be specified as
* <tt>&lt;namespace&gt;:&lt;id&gt;</tt> in order to avoid overlaps
* between consumer-provided selectors. If left blank defaults to the
* namespace specified in the configuration.
*/
public String namespace() default "";
/**
* The string code used to specify the selector selector strings,
* prefixed with namespace from the annotation or from the declaring
* configuration.
*/
public String value();
}
/**
* Decoration for subclasses which indicates an annotation type from which
* the selector can be parsed.
*/
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.TYPE)
public @interface SelectorAnnotation {
/**
* Annotation type for the selector
*/
public Class<? extends Annotation> value();
}
}
@@ -33,7 +33,44 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
* service
*/
public interface ITargetSelectorRemappable extends ITargetSelectorByName {
/**
* Get whether this reference is fully qualified
*
* @return true if all components of this reference are non-null
*/
public abstract boolean isFullyQualified();
/**
* Get whether this target selector is definitely a field, the output of
* this method is undefined if {@link #isFullyQualified} returns false.
*
* @return true if this is definitely a field
*/
public abstract boolean isField();
/**
* Get whether this member represents a constructor
*
* @return true if member name is <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Returns this selector as a {@link MappingField} or
* {@link MappingMethod}
@@ -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.injection.selectors;
/**
* Since the contract of {@link TargetSelector#parse} prohibits returing <tt>
* null</tt>, instances of this selector are returned when supplied arguments
* are unparseable in order to throw exceptions only during validation.
*/
public class InvalidSelector implements ITargetSelector {
/**
* The original input string, used in error messages
*/
private String input;
/**
* The cause of the parser failure, emitted from {@link #validate}
*/
private Throwable cause;
public InvalidSelector(Throwable cause) {
this(cause, null);
}
public InvalidSelector(String input) {
this(null, input);
}
public InvalidSelector(Throwable cause, String input) {
this.input = input;
this.cause = cause;
}
@Override
public String toString() {
if (this.cause != null) {
return String.format("%s: %s", this.cause.getClass().getName(), this.cause.getMessage());
}
return this.input;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #next()
*/
@Override
public ITargetSelector next() {
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #configure(ITargetSelector.Configure, java.lang.String[])
*/
@Override
public ITargetSelector configure(Configure request, String... args) {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #validate()
*/
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.cause instanceof InvalidSelectorException) {
throw (InvalidSelectorException)this.cause;
}
String message = "Error parsing target selector";
if (this.input != null) {
message += ", the input was in an unexpected format: " + this.input;
}
if (this.cause != null) {
throw new InvalidSelectorException(message, this.cause);
}
throw new InvalidSelectorException(message);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #attach(ISelectorContext)
*/
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMinMatchCount()
*/
@Override
public int getMinMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMaxMatchCount()
*/
@Override
public int getMaxMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
this.validate();
return MatchResult.NONE;
}
}
@@ -0,0 +1,257 @@
/*
* 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.selectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* A {@link ITargetSelector Target Selector} which matches an element of
* candidate members using a regular expression. This selector is not remappable
* and is not suitable for use in obfuscated environments.
*
* <p>Regular expressions for this selector should be enclosed in <tt>/</tt> as
* a delimiter character, and <tt>\</tt> characters must be escaped per normal
* Java conventions (eg. use <tt>\\s</tt> instead of <tt>\s</tt> since the
* backslash must be escaped). Forward slash (<tt>/</tt>) characters in the
* regex must be escaped as well to avoid being consumed as ending delimiters.
* </p>
*
* <p>By default the regex match is performed against the <tt>name</tt> of the
* candidate, to specify matching against <tt>owner</tt> or <tt>desc</tt>, each
* pattern should be prefixed with <tt>owner=</tt> or <tt>desc=</tt> <b>outside
* the delimiting <tt>/</tt></b>.
*
* <p>Some examples:</p>
* <blockquote><pre>
* <del>// Matches candidates starting with "foo"</del>
* /^foo/
*
* <del>// Matches candidates ending with "Bar" and which take a single int
*</del> /bar$/ desc=/^\\(I\\)/
*
* <del>// The same example but with "name" explicitly specified (optional)
*</del> name=/bar$/ desc=/^\\(I\\)/
*
* <del>// Matches candidates whose name contains "Entity"</del>
* /Entity/
*
* <del>// Matches candidates whose owner contains "/google/", note the
* // escaping of the forward slash symbols</del>
* owner=/\\/google\\//</pre>
* </blockquote>
*
* <p>The <tt>owner</tt>, <tt>name</tt> and <tt>desc</tt> expressions can be
* provided in any order.</p>
*/
public final class MemberMatcher implements ITargetSelector {
/**
* Regex selector, searches for targets using supplied regular expression
*/
private static final Pattern PATTERN = Pattern.compile("((owner|name|desc)\\s*=\\s*)?/(.*?)(?<!\\\\)/");
/**
* Names of the positional source elements, just used for error messages
*/
private static final String[] PATTERN_SOURCE_NAMES = { "owner", "name", "desc" };
// Positional source elements
private static final int SOURCE_OWNER = 0;
private static final int SOURCE_NAME = 1;
private static final int SOURCE_DESC = 2;
/**
* Positional patterns. The match sources are packed into 3-element arrays
* just to make the iteration for matching simpler
*/
private final Pattern[] patterns;
/**
* Stored exception during parse. The contract of parse prohibits us from
* emitting (intentional) exceptions. Any exceptions are stored here so they
* can be emitted in {@link #validate}.
*/
private final Exception parseException;
/**
* Input string, stored just so we can emit it along with the exception
* message if {@link #validate} needs to throw a parse exception
*/
private final String input;
private MemberMatcher(Pattern[] patterns, Exception parseException, String input) {
this.patterns = patterns;
this.parseException = parseException;
this.input = input;
}
/**
* Parse a MemberMatcher from the supplied input string.
*
* @param input Raw input string
* @param context selector context
* @return parsed MemberMatcher
*/
public static MemberMatcher parse(final String input, ISelectorContext context) {
Matcher matcher = MemberMatcher.PATTERN.matcher(input);
Pattern[] patterns = new Pattern[3];
Exception parseException = null;
while (matcher.find()) {
Pattern pattern;
try {
pattern = Pattern.compile(matcher.group(3));
} catch (PatternSyntaxException ex) {
parseException = ex;
pattern = Pattern.compile(".*");
ex.printStackTrace();
}
int patternId = "owner".equals(matcher.group(2)) ? MemberMatcher.SOURCE_OWNER : "desc".equals(matcher.group(2))
? MemberMatcher.SOURCE_DESC : MemberMatcher.SOURCE_NAME;
if (patterns[patternId] != null) {
parseException = new InvalidSelectorException("Pattern for '" + MemberMatcher.PATTERN_SOURCE_NAMES[patternId]
+ "' specified multiple times: Old=/" + patterns[patternId].pattern() + "/ New=/" + pattern.pattern() + "/");
}
patterns[patternId] = pattern;
}
return new MemberMatcher(patterns, parseException, input);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #validate()
*/
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.parseException != null) {
if (this.parseException instanceof InvalidSelectorException) {
throw (InvalidSelectorException)this.parseException;
}
throw new InvalidSelectorException("Error parsing regex selector", this.parseException);
}
boolean validPattern = false;
for (Pattern pattern : this.patterns) {
validPattern |= pattern != null;
}
if (!validPattern) {
throw new InvalidSelectorException("Error parsing regex selector, the input was in an unexpected format: " + this.input);
}
return this;
}
@Override
public String toString() {
return this.input;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #next()
*/
@Override
public ITargetSelector next() {
return this; // Regex matcher flows into targets
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #configure(java.lang.String[])
*/
@Override
public ITargetSelector configure(Configure request, String... args) {
request.checkArgs(args);
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #attach(org.spongepowered.asm.mixin.injection.selectors
* .ISelectorContext)
*/
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMinMatchCount()
*/
@Override
public int getMinMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMaxMatchCount()
*/
@Override
public int getMaxMatchCount() {
return Integer.MAX_VALUE;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc());
}
private MatchResult matches(String... args) {
MatchResult result = MatchResult.NONE;
// boolean exactOnly = true;
for (int i = 0; i < this.patterns.length; i++) {
if (this.patterns[i] == null || args[i] == null) {
continue;
}
if (this.patterns[i].matcher(args[i]).find()) {
// String pattern = this.patterns[i].pattern();
// if (pattern.startsWith("^") && pattern.endsWith("$") && exactOnly) {
result = MatchResult.EXACT_MATCH;
// } else {
// result = MatchResult.EXACT_MATCH;
// exactOnly = false;
// }
} else {
result = MatchResult.NONE;
}
}
return result;
}
}
@@ -24,14 +24,37 @@
*/
package org.spongepowered.asm.mixin.injection.selectors;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import javax.tools.Diagnostic.Kind;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.util.asm.ElementNode;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.asm.util.logging.MessageRouter;
import com.google.common.base.Strings;
/**
* Utility class for parsing selectors
@@ -48,14 +71,14 @@ public final class TargetSelector {
/**
* Any exact match returned by the query
*/
public final TNode exactMatch;
public final ElementNode<TNode> exactMatch;
/**
* All candidates returned by the query
*/
public final List<TNode> candidates;
public final List<ElementNode<TNode>> candidates;
Result(TNode exactMatch, List<TNode> candidates) {
Result(ElementNode<TNode> exactMatch, List<ElementNode<TNode>> candidates) {
this.exactMatch = exactMatch;
this.candidates = candidates;
}
@@ -75,27 +98,190 @@ public final class TargetSelector {
public TNode getSingleResult(boolean strict) {
int resultCount = this.candidates.size();
if (this.exactMatch != null) {
return this.exactMatch;
return this.exactMatch.get();
}
if (resultCount == 1 || !strict) {
return this.candidates.get(0);
return this.candidates.get(0).get();
}
throw new IllegalStateException((resultCount == 0 ? "No" : "Multiple") + " candidates were found");
}
}
/**
* A dynamic selector registration entry
*/
static class DynamicSelectorEntry {
final String namespace;
final String id;
final Class<? extends ITargetSelectorDynamic> type;
final Class<? extends Annotation> annotation;
final Method mdParseString, mdParseAnnotation;
DynamicSelectorEntry(String namespace, String id, Class<? extends ITargetSelectorDynamic> type) throws NoSuchMethodException {
this.namespace = namespace;
this.id = id;
this.type = type;
this.mdParseString = type.getDeclaredMethod("parse", String.class, ISelectorContext.class);
if (!Modifier.isStatic(this.mdParseString.getModifiers())) {
throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static");
}
if (!ITargetSelectorDynamic.class.isAssignableFrom(this.mdParseString.getReturnType())) {
throw new MixinError("parse(String) method for dynamic target selector [" + this.type.getName()
+ "] must return an ITargetSelectorDynamic subtype");
}
Class<? extends Annotation> annotation = null;
Method mdParseAnnotation = null;
SelectorAnnotation selectorAnnotation = type.<SelectorAnnotation>getAnnotation(SelectorAnnotation.class);
if (selectorAnnotation != null) {
annotation = selectorAnnotation.value();
mdParseAnnotation = type.getDeclaredMethod("parse", IAnnotationHandle.class, ISelectorContext.class);
if (!Modifier.isStatic(mdParseAnnotation.getModifiers())) {
throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static");
}
if (!ITargetSelectorDynamic.class.isAssignableFrom(mdParseAnnotation.getReturnType())) {
throw new MixinError("parse(Annotation) method for dynamic target selector [" + this.type.getName()
+ "] must return an ITargetSelectorDynamic subtype");
}
}
this.annotation = annotation;
this.mdParseAnnotation = mdParseAnnotation;
}
String getCode() {
return (this.namespace != null ? this.namespace + ":" : "") + this.id;
}
ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException {
return this.parse(input, context, this.mdParseString);
}
ITargetSelectorDynamic parse(IAnnotationHandle input, ISelectorContext context) throws ReflectiveOperationException {
return this.parse(input, context, this.mdParseAnnotation);
}
ITargetSelectorDynamic parse(Object input, ISelectorContext context, Method parseMethod) throws ReflectiveOperationException {
try {
return (ITargetSelectorDynamic)parseMethod.invoke(null, input, context);
} catch (InvocationTargetException itex) {
Throwable cause = itex.getCause();
if (cause instanceof MixinException) {
throw (MixinException)cause;
}
Throwable ex = cause != null ? cause : itex;
throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex);
}
}
}
/**
* Regex for dynamic selector ids
*/
private static final String DYNAMIC_SELECTOR_ID = "[a-z]+(:[a-z]+)?";
/**
* Pattern for matching dynamic selectors
*/
private static final Pattern PATTERN_DYNAMIC = Pattern.compile("(?i)^\\x40(" + TargetSelector.DYNAMIC_SELECTOR_ID + ")(\\((.*)\\))?$");
/**
* Registered dynamic selectors
*/
private static Map<String, DynamicSelectorEntry> dynamicSelectors = new LinkedHashMap<String, DynamicSelectorEntry>();
static {
TargetSelector.registerBuiltIn(DynamicSelectorDesc.class);
}
private TargetSelector() {
}
/**
* Parse a target selector from a string and perform validation
* Register a dynamic target selector class. The supplied class must be
* decorated with an {@link SelectorId} annotation for registration to
* succeed.
*
* @param string String to parse target selector from
* @param type ITargetSelectorDynamic to register
* @param namespace namespace for SelectorId
*/
public static void register(Class<? extends ITargetSelectorDynamic> type, String namespace) {
SelectorId selectorId = type.<SelectorId>getAnnotation(SelectorId.class);
if (selectorId == null) {
throw new IllegalArgumentException("Dynamic target selector class " + type + " is not annotated with @SelectorId");
}
String annotationNamespace = selectorId.namespace();
if (!Strings.isNullOrEmpty(annotationNamespace)) {
namespace = annotationNamespace;
}
if (Strings.isNullOrEmpty(namespace)) {
throw new IllegalArgumentException("Dynamic target selector class " + type
+ " has no namespace. Please specify namespace in SelectorId annotation or declaring configuration");
}
DynamicSelectorEntry entry;
try {
entry = new DynamicSelectorEntry(namespace.toLowerCase(Locale.ROOT), selectorId.value().toLowerCase(Locale.ROOT), type);
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
String code = entry.getCode();
if (!Pattern.matches(TargetSelector.DYNAMIC_SELECTOR_ID, code)) {
throw new IllegalArgumentException("Dynamic target selector class " + type
+ " has an invalid id. Only alpha characters can be used in selector ids and namespaces");
}
DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(code);
if (existing != null) { // && !existing.type.equals(type)) {
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)",
code, type.getName(), existing.type.getName()));
} else {
MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s",
code, type.getName()));
}
TargetSelector.dynamicSelectors.put(code, entry);
}
/**
* Register a built-in target selector class. Skips validation and
* namespacing checks
*
* @param type ITargetSelectorDynamic to register
*/
private static void registerBuiltIn(Class<? extends ITargetSelectorDynamic> type) {
SelectorId selectorId = type.<SelectorId>getAnnotation(SelectorId.class);
DynamicSelectorEntry entry;
try {
entry = new DynamicSelectorEntry(null, selectorId.value().toLowerCase(Locale.ROOT), type);
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
TargetSelector.dynamicSelectors.put(entry.id, entry);
TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry);
}
/**
* Parse a target selector from the supplied annotation and perform
* validation
*
* @param annotation Annotation to parse target selector from
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parseAndValidate(String string) throws InvalidMemberDescriptorException {
return TargetSelector.parse(string, null, null).validate();
public static ITargetSelector parseAndValidate(IAnnotationHandle annotation, ISelectorContext context) throws InvalidSelectorException {
return TargetSelector.parse(annotation, context).validate();
}
/**
@@ -105,18 +291,96 @@ public final class TargetSelector {
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException {
return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()).validate();
public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidSelectorException {
return TargetSelector.parse(string, context).validate();
}
/**
* Parse a target selector from a string
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors.
*
* @param string String to parse target selector from
* @param selectors Selectors to parse
* @param context Selection context
* @return parsed collection of selectors, uses LinkedHashSet to preserve
* parse ordering
*/
public static Set<ITargetSelector> parseAndValidate(Iterable<?> selectors, ISelectorContext context) throws InvalidSelectorException {
Set<ITargetSelector> parsed = TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
for (ITargetSelector selector : parsed) {
selector.validate();
}
return parsed;
}
/**
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors.
*
* @param selectors Selectors to parse
* @param context Selection context
* @return parsed collection of selectors, uses LinkedHashSet to preserve
* parse ordering
*/
public static Set<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context) {
return TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
}
/**
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors and store them in the
* provided collection.
*
* @param selectors Selectors to parse
* @param context Selection context
* @param parsed Collection to add parsed selectors to, initialised as a
* LinkedHashSet if null
* @return the same collection passed in via the <tt>parsed</tt> parameter,
* for convenience
*/
public static Set<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context, Set<ITargetSelector> parsed) {
if (parsed == null) {
parsed = new LinkedHashSet<ITargetSelector>();
}
if (selectors != null) {
for (Object selector : selectors) {
if (selector instanceof IAnnotationHandle) {
parsed.add(TargetSelector.parse((IAnnotationHandle)selector, context));
} else if (selector instanceof AnnotationNode) {
parsed.add(TargetSelector.parse(Annotations.handleOf(selector), context));
} else if (selector instanceof String) {
parsed.add(TargetSelector.parse((String)selector, context));
} else if (selector instanceof Class) {
String desc = Type.getType((Class<?>)selector).getDescriptor();
parsed.add(TargetSelector.parse(desc, context));
} else if (selector != null) {
parsed.add(TargetSelector.parse(selector.toString(), context));
}
}
}
return parsed;
}
/**
* Parse a target selector from the supplied annotation
*
* @param annotation String to parse target selector from
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parse(String string) {
return TargetSelector.parse(string, null, null);
public static ITargetSelector parse(IAnnotationHandle annotation, ISelectorContext context) {
for (DynamicSelectorEntry entry : TargetSelector.dynamicSelectors.values()) {
if (entry.annotation != null && Annotations.getDesc(entry.annotation).equals(annotation.getDesc())) {
try {
return entry.parse(annotation, context);
} catch (ReflectiveOperationException ex) {
return new InvalidSelector(ex.getCause());
} catch (Exception ex) {
return new InvalidSelector(ex);
}
}
}
return new InvalidSelector(new InvalidSelectorException("Dynamic selector for annotation " + annotation + " is not registered."));
}
/**
@@ -126,8 +390,42 @@ public final class TargetSelector {
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parse(String string, IMixinContext context) {
return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef());
public static ITargetSelector parse(String string, ISelectorContext context) {
string = string.trim();
// Ending with slash indicates a regex target, no other type of target
// selector can end (legally) with a forward slash
if (string.endsWith("/")) {
MemberMatcher regexMatcher = MemberMatcher.parse(string, context);
if (regexMatcher != null) {
return regexMatcher;
}
}
// Starting with @ indicates a dynamic target. Parse as a regular
// MemberInfo if the selector does not start with @
if (!string.startsWith("@")) {
return MemberInfo.parse(string, context);
}
Matcher dynamic = TargetSelector.PATTERN_DYNAMIC.matcher(string);
if (!dynamic.matches()) {
return new InvalidSelector(new InvalidSelectorException("Dynamic selector was in an unrecognised format. Parsing selector: " + string));
}
String selectorId = dynamic.group(1).toLowerCase(Locale.ROOT);
if (!TargetSelector.dynamicSelectors.containsKey(selectorId)) {
return new InvalidSelector(new InvalidSelectorException("Dynamic selector with id '@" + dynamic.group(1)
+ "' is not registered. Parsing selector: " + string));
}
try {
return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)).trim(), context);
} catch (ReflectiveOperationException ex) {
return new InvalidSelector(ex.getCause(), string);
} catch (Exception ex) {
return new InvalidSelector(ex);
}
}
/**
@@ -141,7 +439,7 @@ public final class TargetSelector {
* @param context Mixin context
* @return remapped name or original name
*/
public static String parseName(String name, IMixinContext context) {
public static String parseName(String name, ISelectorContext context) {
ITargetSelector selector = TargetSelector.parse(name, context);
if (!(selector instanceof ITargetSelectorByName)) {
return name;
@@ -150,38 +448,34 @@ public final class TargetSelector {
return mappedName != null ? mappedName : name;
}
private static ITargetSelector parse(String input, IReferenceMapper refMapper, String mixinClass) {
return MemberInfo.parse(input, refMapper, mixinClass);
}
/**
* Run query on supplied target nodes
*
* @param target Target selector
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(ITargetSelector target, List<ElementNode<TNode>> nodes) {
List<TNode> candidates = new ArrayList<TNode>();
TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates);
public static <TNode> Result<TNode> run(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes) {
List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>();
ElementNode<TNode> exactMatch = TargetSelector.runSelector(selector, nodes, candidates);
return new Result<TNode>(exactMatch, candidates);
}
/**
* Run query on supplied target nodes
*
* @param targets Target selector
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> targets, List<ElementNode<TNode>> nodes) {
TNode exactMatch = null;
List<TNode> candidates = new ArrayList<TNode>();
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> selector, Iterable<ElementNode<TNode>> nodes) {
ElementNode<TNode> exactMatch = null;
List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>();
for (ITargetSelector target : targets) {
TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates);
for (ITargetSelector target : selector) {
ElementNode<TNode> selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates);
if (exactMatch == null) {
exactMatch = selectorExactMatch;
}
@@ -190,20 +484,32 @@ public final class TargetSelector {
return new Result<TNode>(exactMatch, candidates);
}
private static <TNode> TNode runSelector(ITargetSelector target, List<ElementNode<TNode>> nodes, List<TNode> candidates) {
TNode exactMatch = null;
for (ElementNode<TNode> element : nodes) {
MatchResult match = target.match(element);
private static <TNode> ElementNode<TNode> runSelector(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes,
List<ElementNode<TNode>> candidates) {
int matchCount = 0;
ElementNode<TNode> exactMatch = null;
for (Iterator<ElementNode<TNode>> iterator = nodes.iterator(); iterator.hasNext();) {
ElementNode<TNode> element = iterator.next();
MatchResult match = selector.match(element);
if (match.isMatch()) {
TNode node = element.get();
if (!candidates.contains(node)) {
candidates.add(node);
matchCount++;
if (matchCount > selector.getMaxMatchCount()) {
break;
}
if (!candidates.contains(element)) {
candidates.add(element);
}
if (exactMatch == null && match.isExactMatch()) {
exactMatch = node;
exactMatch = element;
}
}
}
if (matchCount < selector.getMinMatchCount()) {
throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)",
selector, selector.getMinMatchCount(), matchCount));
}
return exactMatch;
}
@@ -0,0 +1,426 @@
/*
* 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.selectors.dynamic;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.Descriptors;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.asm.IAnnotatedElement;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
/**
* Utility class which contains the logic for resolving descriptors
* ({@link Desc} annotations) starting from an element and recursing up the tree
* of parent elements looking for a matching descriptor
*/
public final class DescriptorResolver {
/**
* Resolution result
*/
static final class Descriptor implements IResolvedDescriptor {
/**
* The set of coordinates which were searched, stored here so they can
* be included in error messages if resolution fails
*/
private final Set<String> searched;
/**
* The resolved descriptor
*/
private final IAnnotationHandle desc;
/**
* Selector context
*/
private final ISelectorContext context;
Descriptor(Set<String> searched, IAnnotationHandle desc, ISelectorContext context) {
this.searched = searched;
this.desc = desc;
this.context = context;
}
/**
* True if the resolution process was successful
*/
@Override
public boolean isResolved() {
return this.desc != null;
}
/**
* Get information about the resolution of this descriptor, for
* inclusion in error messages when isResolved is false
*
*/
@Override
public String getResolutionInfo() {
if (this.searched == null) {
return "";
}
return String.format("Searched coordinates [ \"%s\" ]", Joiner.on("\", \"").join(this.searched));
}
/**
* Gets the resolved descriptor annotation if successful, otherwise
* returns null
*/
@Override
public IAnnotationHandle getAnnotation() {
return this.desc;
}
@Override
public String getId() {
return this.desc != null ? this.desc.<String>getValue("id", "") : "";
}
@Override
public Type getOwner() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
Type ownerClass = this.desc.getTypeValue("owner");
if (ownerClass != Type.VOID_TYPE) {
return ownerClass;
}
return this.context != null ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass;
}
@Override
public String getName() {
if (this.desc == null) {
return "";
}
String value = this.desc.<String>getValue("value", "");
if (!value.isEmpty()) {
return value;
}
return this.desc.<String>getValue("name", "");
}
@Override
public Type[] getArgs() {
if (this.desc == null) {
return new Type[0];
}
List<Type> args = this.desc.getTypeList("args");
return args.toArray(new Type[args.size()]);
}
@Override
public Type getReturnType() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
return this.desc.getTypeValue("ret");
}
@Override
public Quantifier getMatches() {
if (this.desc == null) {
return Quantifier.DEFAULT;
}
int min = Math.max(0, this.desc != null ? this.desc.<Integer>getValue("min", 0) : 0);
Integer max = this.desc != null ? this.desc.<Integer>getValue("max", null) : null;
return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1);
}
@Override
public List<IAnnotationHandle> getNext() {
return this.desc != null ? this.desc.getAnnotationList("next") : Collections.<IAnnotationHandle>emptyList();
}
}
/**
* Observer for the resolution process, used to support printing resolution
* path during debug or collecting resolution info for inclusion in error
* messages
*/
interface IResolverObserver {
/**
* Called when the resolver visits a coordinate on the specified member
*
* @param coordinate coordinate being visited
* @param element element being visited
* @param detail diagnostic detail
*/
public abstract void visit(String coordinate, Object element, String detail);
/**
* Get all of the searched coordinates, for inclusion in error messages
*/
public abstract Set<String> getSearched();
/**
* Called after resolution completes
*/
public abstract void postResolve();
}
/**
* Basic resolver observer which just collects searched coordinates
*/
static class ResolverObserverBasic implements IResolverObserver {
private final Set<String> searched = new LinkedHashSet<String>();
@Override
public void visit(String coordinate, Object element, String detail) {
this.searched.add(coordinate);
}
@Override
public Set<String> getSearched() {
return this.searched;
}
@Override
public void postResolve() {
}
}
/**
* Debug resolver observer which prints resolution debug info after
* resolution is complete
*/
static class ResolverObserverDebug extends ResolverObserverBasic {
private final PrettyPrinter printer = new PrettyPrinter();
ResolverObserverDebug(ISelectorContext context) {
this.printer.add("Searching for implicit descriptor").add(context).hr().table();
this.printer.tr("Context Coordinate:", context.getSelectorCoordinate(true) + " (" + context.getSelectorCoordinate(false) + ")");
this.printer.tr("Selector Annotation:", context.getSelectorAnnotation());
this.printer.tr("Root Annotation:", context.getAnnotation());
this.printer.tr("Method:", context.getMethod()).hr();
this.printer.table("Search Coordinate", "Search Element", "Detail").th().hr();
}
@Override
public void visit(String coordinate, Object element, String detail) {
super.visit(coordinate, element, detail);
this.printer.tr(coordinate, element, detail);
}
@Override
public void postResolve() {
this.printer.print();
}
}
/**
* Special ID used to instruct the resolver to print its progress.
*/
public static String PRINT_ID = "?";
// No
private DescriptorResolver() {
}
public static IResolvedDescriptor resolve(IAnnotationHandle desc, ISelectorContext context) {
return new Descriptor(Collections.emptySet(), desc, context);
}
/**
* Resolve the specified descriptor id starting at the specified context
*
* @param id Id to resolve, can be empty if resolving by coordinate
* @param context Selector context, usually from the source annotation
* @return Resolution result
*/
public static IResolvedDescriptor resolve(String id, ISelectorContext context) {
IResolverObserver observer = new ResolverObserverBasic();
if (!Strings.isNullOrEmpty(id)) {
if (DescriptorResolver.PRINT_ID.equals(id)) {
observer = new ResolverObserverDebug(context);
id = "";
} else {
observer.visit(id, "", "");
}
}
IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true));
observer.postResolve();
return new Descriptor(observer.getSearched(), desc, context);
}
/**
* Recursive function which checks an element and then recurses to parent
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate) {
IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation());
observer.visit(coordinate, annotation, annotation.toString() + ".desc");
// First check if there's a "desc" value on the current annotation
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, annotation.getAnnotationList("desc"));
if (resolved != null) {
return resolved;
}
// Next check with the current coordinates on the owning method
resolved = DescriptorResolver.resolve(id, context, observer, coordinate, context.getMethod(), "method");
if (resolved != null) {
return resolved;
}
ISelectorContext root = DescriptorResolver.getRoot(context);
String rootCoordinate = root.getSelectorCoordinate(false);
String mixinCoordinate = (root != context || !coordinate.contains(".")) && !rootCoordinate.equals(coordinate)
? rootCoordinate + "." + coordinate : coordinate;
// Next check with the current coordinates on the mixin
resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin");
if (resolved != null) {
return resolved;
}
// Otherwise compute the parent coordinates and then recurse into the parent
ISelectorContext parent = context.getParent();
if (parent != null) {
String parentCoordinate = parent.getSelectorCoordinate(false) + "." + coordinate;
return DescriptorResolver.resolve(id, parent, observer, parentCoordinate);
}
// If all else fails, return failure
return null;
}
/**
* Attempt to resolve on an element
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, Object element,
String detail) {
observer.visit(coordinate, element, detail);
IAnnotationHandle descriptors = DescriptorResolver.getVisibleAnnotation(element, Descriptors.class);
if (descriptors != null) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptors.getAnnotationList("value"));
if (resolved != null) {
return resolved;
}
}
IAnnotationHandle descriptor = DescriptorResolver.getVisibleAnnotation(element, Desc.class);
if (descriptor != null) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptor);
if (resolved != null) {
return resolved;
}
}
return null;
}
/**
* Attempt resolution using annotations from a particular element
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
List<IAnnotationHandle> availableDescriptors) {
if (availableDescriptors != null) {
for (IAnnotationHandle desc : availableDescriptors) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, desc);
if (resolved != null) {
return resolved;
}
}
}
return null;
}
/**
* Attempt resolution using an actual annotation
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
IAnnotationHandle desc) {
if (desc != null) {
String descriptorId = desc.getValue("id", coordinate);
boolean implicit = Strings.isNullOrEmpty(id);
if ((implicit && descriptorId.equalsIgnoreCase(coordinate)) || (!implicit && descriptorId.equalsIgnoreCase(id))) {
return desc;
}
}
return null;
}
/**
* Utility function, gets an annotation handle from the candidate elements
* we are able to process
*
* @param element Element to fetch annotations for
* @param annotationClass Annotation we're searching for
* @return Annotation handle or null if the source is null
* @throws IllegalStateException if element is of an unsupported type
*/
private static IAnnotationHandle getVisibleAnnotation(Object element, Class<? extends Annotation> annotationClass) {
if (element instanceof MethodNode) {
return Annotations.handleOf(Annotations.getVisible((MethodNode)element, annotationClass));
} else if (element instanceof ClassNode) {
return Annotations.handleOf(Annotations.getVisible((ClassNode)element, annotationClass));
} else if (element instanceof MixinTargetContext) {
return Annotations.handleOf(Annotations.getVisible(((MixinTargetContext)element).getClassNode(), annotationClass));
} else if (element instanceof IAnnotatedElement) {
IAnnotationHandle annotation = ((IAnnotatedElement)element).getAnnotation(annotationClass);
return annotation != null && annotation.exists() ? annotation : null;
} else if (element == null) {
return null;
}
throw new IllegalStateException("Cannot read visible annotations from element with unknown type: " + element.getClass().getName());
}
private static ISelectorContext getRoot(ISelectorContext context) {
ISelectorContext parent = context.getParent();
while (parent != null) {
context = parent;
parent = context.getParent();
}
return context;
}
}
@@ -0,0 +1,521 @@
/*
* 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.selectors.dynamic;
import java.util.List;
import org.objectweb.asm.Type;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.MatchResult;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.SignaturePrinter;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Strings;
/**
* A {@link ITargetSelector Target Selector} which matches candidates using
* descriptors contained in {@link Desc &#064;Desc} annotations. The descriptor
* annotations may be local, or may be applied to the method or even the owning
* mixin using user-specified ids, or implicit coordinates based on the relative
* location of the consumer. eg. an &#064;At annotation and the &#064;Desc
* annotation itself, which might be on a parent element for convenience.
*
* <p>See {@link Desc &#064;Desc} for the specific syntax of descriptor
* annotations.</p>
*
* <h3>Local Descriptors</h3>
*
* <p>Some annotations can use {@link Desc &#064;Desc} selectors directly,
* namely {@link At &#064;At} (specified in {@link At#desc &#064;At.desc}) and
* all <b>Injector</b> annotations (specified in <tt>target</tt> - for example
* {@link Inject#target &#064;Inject.target}). In these cases it is not
* necessary to specify an {@link Desc#id id} for the descriptor since the usage
* is inferred from context.</p>
*
* <h3>Resolved Descriptors</h3>
*
* <p>Descriptors can also be placed as annotations on the mixin method or the
* mixin class, thus allowing descriptors to be re-used by multiple consumers.
* For example where several injectors target the same method, the descriptor
* can be placed on the mixin itself and consumed by id. In this situation it is
* necessary to specify an {@link Desc#id id} for the descriptor and specify the
* chosen id as a selector string:</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>foo</ins>", value = "getFoo", args = { int.class })
* <br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(target = "<ins>&#064;Desc(foo)</ins>", at =
* &#064;At("RETURN"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }<br />
* <br />
* }</code></blockquote>
*
* <p>Note that the id string can be anything you wish, but is matched
* case-insensitively and must be non-empty, so feel free to be as descriptive
* as you wish.</p>
*
* <h4>Implicit coordinates</h4>
*
* <p>As an alternative to specifying an <em>explicit</em> descriptor id for
* descriptors, it is also possible to use implicit coordinates generated using
* the location of the consumer. To do so, use the selector <tt>"&#064;Desc"
* </tt> with no arguments and give the descriptor an {@link Desc#id id} which
* corresponds to the coordinate of the consumer:</p>
*
* <p>In this example, the coordinate of the {@link At &#064;At} annotation,
* <tt>"at"</tt> is used as the descriptor id.</p>
*
* <blockquote><code>
* &nbsp; &nbsp; &#064;Desc(id = "<ins>at</ins>",
* value = "theMethodName", args = { String.class }, ret = boolean.class)<br />
* &nbsp; &nbsp; &#064;Inject(method = "targetMethod()V", at =
* &#064;At(value = "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>As the resolver widens its search it adds new components to the start of
* the implicit coordinate which match the element, separated by dots. For
* example {@link At &#064;At} annotations inside a {@link Slice &#064;Slice}
* will first resolve as (local coordinate) <tt>from</tt>, followed by
* <tt>slice.from</tt>, and finally <tt>handlerMethodName.slice.from</tt>. This
* allows implicit coordinates to be used up to the mixin level as in the first
* example.</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.at</ins>", value = "theMethodName",
* args = { String.class }, ret = boolean.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.method</ins>", value = "getFoo", args =
* { int.class })<br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(method = "<ins>@Desc</ins>", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>To view the coordinates used to resolve the descriptor for a particular
* element, use the special id "?" in the selector:</p>
*
* <blockquote><code>
* &nbsp; &nbsp; &#064;Inject(method = "&#064;Desc", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc(?)</ins>"))
* <br />
* &nbsp; &nbsp; void myHandler(int arg, CallbackInfo ci) {
* </code></blockquote>
*
* <p>This will cause the resolver to pretty-print the considered coordinates
* and elements into the console:</p>
*
* <blockquote><pre>/*****************************************************&#47;
*&#47;* Coordinate Search Element Detail *&#47;
*&#47;*****************************************************&#47;
*&#47;* at &#64;At &#64;At.desc *&#47;
*&#47;* at myHandler method *&#47;
*&#47;* myhandler.at mixins.json:MyMixin mixin *&#47;
*&#47;* myhandler.at &#64;Redirect &#64;Redirect.desc *&#47;
*&#47;* myhandler.at myhandler method *&#47;
*&#47;*****************************************************&#47;</pre>
*</blockquote>
*
* <p>Don't worry that some combinations of coordinate and element are not
* possible (for example there is no member <tt>desc</tt> on <tt>&#64;At</tt>).
* The resolver doesn't know that and scans each visited element for members it
* supports.</p>
*/
@SelectorId("Desc")
@SelectorAnnotation(Desc.class)
public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName {
/**
* Next selector
*/
final class Next extends DynamicSelectorDesc {
private final int index;
Next(int index, IResolvedDescriptor next) {
super(null, null, next.getOwner(), next.getName(), next.getArgs(), next.getReturnType(), next.getMatches(), null);
this.index = index;
}
@Override
public ITargetSelector next() {
return DynamicSelectorDesc.this.next(this.index + 1);
}
}
/**
* Parser/resolver error mesage, only stored if the descriptor is invalid so
* we can emit it when {@link #validate} is called
*/
private final InvalidSelectorException parseException;
/**
* Resolved id
*/
private final String id;
/**
* The owner specified in the resolved {@link Desc} annotation, or null if
* resolution failed
*/
private final Type owner;
/**
* The name specified in the resolved {@link Desc} annotation, or null if
* resolution failed
*/
private final String name;
/**
* The arguments specified in the resolved {@link Desc} annotation, or null
* if resolution failed
*/
private final Type[] args;
/**
* The return type specified in the resolved {@link Desc} annotation, or
* null if resolution failed
*/
private final Type returnType;
/**
* Method descriptor, used for matching against methods. Computed from
* argument types and return type
*/
private final String methodDesc;
/**
* Required matches
*/
private final Quantifier matches;
/**
* Annotation for next, parsed on demand
*/
private final List<IAnnotationHandle> next;
private DynamicSelectorDesc(IResolvedDescriptor desc) {
this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches(),
desc.getNext());
}
private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) {
this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier, desc.next);
}
private DynamicSelectorDesc(DynamicSelectorDesc desc, Type owner) {
this(desc.parseException, desc.id, owner, desc.name, desc.args, desc.returnType, desc.matches, desc.next);
}
private DynamicSelectorDesc(InvalidSelectorException ex) {
this(ex, null, null, null, null, null, Quantifier.NONE, null);
}
protected DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches,
List<IAnnotationHandle> then) {
this.parseException = ex;
this.id = id;
this.owner = owner;
this.name = Strings.emptyToNull(name);
this.args = args;
this.returnType = returnType;
this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null;
this.matches = matches;
this.next = then;
}
/**
* Parse a descriptor selector from the supplied input. The input is treated
* as a descriptor id to be resolved, or if empty uses implicit coordinates
* from the selection context
*
* @param input ID string, can be empty
* @param context Selector context
* @return parsed selector
*/
public static DynamicSelectorDesc parse(String input, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context);
if (!descriptor.isResolved()) {
String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : "";
return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra));
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param context Selector context
* @param desc Annotation to parse
* @return selector
*/
public static DynamicSelectorDesc parse(IAnnotationHandle desc, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context);
if (!descriptor.isResolved()) {
return new DynamicSelectorDesc(new InvalidSelectorException("Invalid descriptor"));
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Resolve a descriptor selector from the supplied context only, implicit
* coordinates are used.
*
* @param context Selector context
* @return parsed selector
*/
public static DynamicSelectorDesc resolve(ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param desc Annotation to parse
* @param context Selector context
* @return selector
*/
public static DynamicSelectorDesc of(IAnnotationHandle desc, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param desc Resolved descriptor
* @return selector
*/
public static DynamicSelectorDesc of(IResolvedDescriptor desc) {
return new DynamicSelectorDesc(desc);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("@Desc(");
boolean started = false;
if (!Strings.isNullOrEmpty(this.id)) {
sb.append("id = \"").append(this.id).append("\"");
started = true;
}
if (this.owner != Type.VOID_TYPE) {
if (started) {
sb.append(", ");
}
sb.append("owner = ").append(SignaturePrinter.getTypeName(this.owner, false, false)).append(".class");
started = true;
}
if (started) {
sb.append(", ");
}
if (this.name != null) {
sb.append("value = \"").append(this.name).append("\"");
}
if (this.args.length > 0) {
sb.append(", args = { ");
for (int i = 0; i < this.args.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(SignaturePrinter.getTypeName(this.args[i], false, false)).append(".class");
}
sb.append(" }");
}
if (this.returnType != Type.VOID_TYPE) {
sb.append(", ret = ").append(SignaturePrinter.getTypeName(this.returnType, false, false)).append(".class");
}
sb.append(")");
return sb.toString();
}
public String getId() {
return this.id;
}
@Override
public String getOwner() {
return this.owner.getInternalName();
}
@Override
public String getName() {
return this.name;
}
public Type[] getArgs() {
return this.args;
}
public Type getReturnType() {
return this.returnType;
}
@Override
public String getDesc() {
return this.methodDesc;
}
@Override
public String toDescriptor() {
return new SignaturePrinter(this).setFullyQualified(true).toDescriptor();
}
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.parseException != null) {
throw this.parseException;
}
return this;
}
@Override
public ITargetSelector next() {
return this.next(0);
}
protected ITargetSelector next(int index) {
if (index >= 0 && index < this.next.size()) {
IAnnotationHandle nextAnnotation = this.next.get(index);
IResolvedDescriptor descriptor = DescriptorResolver.resolve(nextAnnotation, null);
return new Next(index, descriptor);
}
return null;
}
@Override
public ITargetSelector configure(Configure request, String... args) {
request.checkArgs(args);
switch (request) {
case SELECT_MEMBER:
if (this.matches.isDefault()) {
return new DynamicSelectorDesc(this, Quantifier.SINGLE);
}
break;
case SELECT_INSTRUCTION:
if (this.matches.isDefault()) {
return new DynamicSelectorDesc(this, Quantifier.ANY);
}
break;
case MOVE:
return new DynamicSelectorDesc(this, Type.getObjectType(args[0]));
case CLEAR_LIMITS:
if (this.getMinMatchCount() != 0 || this.getMaxMatchCount() < Integer.MAX_VALUE) {
return new DynamicSelectorDesc(this, Quantifier.ANY);
}
break;
default:
break;
}
return this;
}
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
@Override
public int getMinMatchCount() {
return this.matches.getClampedMin();
}
@Override
public int getMaxMatchCount() {
return this.matches.getClampedMax();
}
@Override
public MatchResult matches(String owner, String name, String desc) {
return this.matches(owner, name, desc, this.methodDesc);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
if (node == null) {
return MatchResult.NONE;
} else if (node.isField()) {
return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.returnType.getInternalName());
} else {
return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.methodDesc);
}
}
private MatchResult matches(String owner, String name, String desc, String compareWithDesc) {
if (!compareWithDesc.equals(desc)) {
return MatchResult.NONE;
} else if (this.owner != Type.VOID_TYPE && !this.owner.getInternalName().equals(owner)) {
return MatchResult.NONE;
} else if (this.name != null && this.name.equals(name)) {
return MatchResult.EXACT_MATCH;
} else if (this.name != null && this.name.equalsIgnoreCase(name)) {
return MatchResult.MATCH;
} else if (this.name == null) {
return MatchResult.EXACT_MATCH;
}
return MatchResult.NONE;
}
}
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more