diff --git a/README.MD b/README.MD index 6c5b29bb..aaf554e8 100644 --- a/README.MD +++ b/README.MD @@ -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. + @@ -67,13 +92,28 @@ plugin developed by [DemonWav](https://github.com/demonwav). - + + + + + + diff --git a/build.gradle b/build.gradle index f9d60fbd..7db3627d 100644 --- a/build.gradle +++ b/build.gradle @@ -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'] diff --git a/checkstyle.xml b/checkstyle.xml index ea6a9e1d..fd6970e0 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -92,9 +92,7 @@ - - @@ -104,9 +102,7 @@ - - diff --git a/docs/javadoc/mixin.css b/docs/javadoc/mixin.css new file mode 100644 index 00000000..87631c8f --- /dev/null +++ b/docs/javadoc/mixin.css @@ -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; +} diff --git a/docs/javadoc/overview.html b/docs/javadoc/overview.html new file mode 100644 index 00000000..8d52d610 --- /dev/null +++ b/docs/javadoc/overview.html @@ -0,0 +1,37 @@ + +

+ Mixin is a trait/mixin framework for Java using + ASM and hooking into + the runtime class-loading process via Mojang's + + LegacyLauncher system. The main documentation for Mixin can + be found in the + + Wiki. +

+ +

+ This Javadoc contains documentation for individual features and + annotations. For additional help use the channel + #mixin + on the Sponge Discord Server. +

+ + + diff --git a/docs/javadoc/resources/jdk8_stylesheet.css b/docs/javadoc/resources/jdk8_stylesheet.css new file mode 100644 index 00000000..98055b22 --- /dev/null +++ b/docs/javadoc/resources/jdk8_stylesheet.css @@ -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; +} diff --git a/docs/logo.png b/docs/javadoc/resources/logo.png similarity index 100% rename from docs/logo.png rename to docs/javadoc/resources/logo.png diff --git a/gradle.properties b/gradle.properties index 9a69ddc7..a947e287 100644 --- a/gradle.properties +++ b/gradle.properties @@ -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 diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 367d02e3..e06e39f2 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -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 targets = this.reloadMixin(className, classNode); diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java index d93d575a..2fd768cb 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -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 diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 09fcc44f..901047fa 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -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 ats = inject.getAnnotationList("at"); - for (AnnotationHandle at : ats) { - this.registerInjectionPoint(method, inject, at, remap, "@At(%s)"); + List ats = inject.getAnnotationList("at"); + for (IAnnotationHandle at : ats) { + this.registerInjectionPoint(method, inject, "at", (AnnotationHandle)at, remap, "@At(%s)"); } - List slices = inject.getAnnotationList("slice"); - for (AnnotationHandle slice : slices) { + List slices = inject.getAnnotationList("slice"); + for (IAnnotationHandle slice : slices) { String id = slice.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 annotationClass) { + return AnnotationHandle.of(this.mixin, annotationClass); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 6517e6c1..cd24aad5 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -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 type of inner element */ - abstract static class AnnotatedElement { + abstract static class AnnotatedElement 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 annotationClass) { + return AnnotationHandle.of(this.element, annotationClass); + } + } + abstract static class AnnotatedElementExecutable extends AnnotatedElement 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 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); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index dce6143c..8f1b3af6 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -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 { + 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); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 382a797a..4a96a44e 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -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 { + 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 { + 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(); @@ -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().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.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().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().getValue("value")); - String target = elem.getAt().getValue("target"); + String type = InjectionPointData.parseType(elem.getAt().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, elem); - this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem); - } else { - this.remapReference(String.format(format, type + "."), target, elem); + if (elem.shouldRemap()) { + if ("NEW".equals(type)) { + this.remapNewTarget(String.format(format, type + "."), targetReference, targetSelector, elem); + this.remapNewTarget(String.format(format, type + ".args[class]"), classReference, classSelector, elem); + } else { + this.remapReference(String.format(format, type + "."), 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 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 mappings = new ObfuscationData(); - 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 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 mappings = new ObfuscationData(); + 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 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; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java index 537da970..0efaef38 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java @@ -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 interfaces = implementsAnnotation.getAnnotationList("value"); + List 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.getValue("remap", Remap.ALL); if (remap == Remap.NONE) { continue; @@ -82,8 +83,8 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl String prefix = interfaceAnnotation.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()); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index d4b859b1..1ff1537c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -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 */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java index b19e6b07..44192441 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessor.java @@ -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 diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java index a5850350..d119041f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java @@ -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; } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java index 7369df7f..dbe88ca2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -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() diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java index 022c63e7..c8c50547 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -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 + *
Usage: + * @SuppressWarnings('constraints') + *
*/ CONSTRAINTS("constraints"), /** * Suppress warnings about overwrite visibility upgrading/downgrading target * visibility + *
Usage: + * @SuppressWarnings('visibility') + *
*/ VISIBILITY("visibility"), /** * Suppress warnings when an injector target cannot be found + *
Usage: + * @SuppressWarnings('target') + *
*/ TARGET("target"), /** * Suppress warnings when a class, method or field mapping cannot be located + *
Usage: + * @SuppressWarnings('mapping') + *
*/ MAPPING("mapping"), /** - * Suppress warnings for when an @Overwrite method is missing - * javadoc, or author or reason tags + * Suppress warnings for when an {@link Overwrite @Overwrite} method is + * missing javadoc, or author or reason tags + *
Usage: + * @SuppressWarnings('overwrite') + *
*/ OVERWRITE("overwrite"), /** * Suppress warnings when a mixin target specified by name is located in the * default package + *
Usage: + * @SuppressWarnings('default-package') + *
*/ 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 + *
Usage: + * @SuppressWarnings('public-target') + *
*/ 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 + *
Usage: + * @SuppressWarnings('unresolvable-target') + *
+ */ + UNRESOLVABLE_TARGET("unresolvable-target"), + /** * The default java "raw types" suppressions + *
Usage: + * @SuppressWarnings('rawtypes') + *
*/ RAW_TYPES("rawtypes"); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java index 3d35f99e..2ebd14a2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java @@ -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; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index 71afb97d..638c0ad2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -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 duck type */ + @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T getValue(String key, T defaultValue) { if (this.annotation == null) { @@ -120,6 +138,7 @@ public final class AnnotationHandle { * @param duck type * @return value or null if not present or not set */ + @Override public T getValue() { return this.getValue("value", null); } @@ -132,6 +151,7 @@ public final class AnnotationHandle { * @param duck type * @return value or null if not present or not set */ + @Override public 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 null 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 list element duck type * @return list of values */ + @Override public List getList(String key) { List list = this.>getValue(key, Collections.emptyList()); return AnnotationHandle.unwrapAnnotationValueList(list); @@ -198,15 +220,16 @@ public final class AnnotationHandle { * @param key key to fetch * @return list of annotations */ - public List getAnnotationList(String key) { + @Override + public List getAnnotationList(String key) { Object val = this.getValue(key, null); if (val == null) { - return Collections.emptyList(); + return Collections.emptyList(); } // Fix for JDT, single values are just returned as a bare AnnotationMirror if (val instanceof AnnotationMirror) { - return ImmutableList.of(AnnotationHandle.of((AnnotationMirror)val)); + return ImmutableList.of(AnnotationHandle.of((AnnotationMirror)val)); } @SuppressWarnings("unchecked") List list = (List)val; @@ -214,7 +237,25 @@ public final class AnnotationHandle { for (AnnotationValue value : list) { annotations.add(new AnnotationHandle((AnnotationMirror)value.getValue())); } - return Collections.unmodifiableList(annotations); + return Collections.unmodifiableList(annotations); + } + + @Override + public Type getTypeValue(String key) { + TypeMirror typeMirror = this.getValue(key); + return typeMirror == null ? Type.VOID_TYPE : Type.getType(TypeUtils.getInternalName(typeMirror)); + } + + @Override + public List getTypeList(String key) { + List list = this.getList(key); + for (ListIterator 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) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java b/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java new file mode 100644 index 00000000..cf2d2f33 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java b/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java index df4c1594..d2f5713e 100644 --- a/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java +++ b/src/example/java/org/spongepowered/tools/obfuscation/json/MappingWriterJson.java @@ -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(); diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java index ca195b70..56a34f45 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java @@ -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 tweakName 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 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) diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java index 82a11fb5..40035886 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -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; } - + } diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java index 0b1aaaf4..bdb726ce 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java @@ -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); diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index d8be34b1..4f671910 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -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 getInternals() throws MixinError { + List internals = new ArrayList(); + try { + Class clTransformerFactory = (Class)Class.forName(MixinBootstrap.MIXIN_TRANSFORMER_FACTORY_CLASS); + Constructor ctor = clTransformerFactory.getDeclaredConstructor(); + ctor.setAccessible(true); + internals.add(ctor.newInstance()); + } catch (ReflectiveOperationException ex) { + throw new MixinError(ex); + } + return internals; + } + } diff --git a/src/main/java/org/spongepowered/asm/launch/package-info.java b/src/main/java/org/spongepowered/asm/launch/package-info.java new file mode 100644 index 00000000..9fd94a8e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java index 36a26c5b..01973cb6 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinConnectorManager.java @@ -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) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 4e6491ad..91e10f22 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -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) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java index 2bb0634c..b4e327eb 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java @@ -297,7 +297,6 @@ public class MixinPlatformManager { */ final void addConnector(String connectorClass) { this.connectors.addConnector(connectorClass); - } } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java b/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java new file mode 100644 index 00000000..b3adc6e7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/container/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/launch/platform/package-info.java b/src/main/java/org/spongepowered/asm/launch/platform/package-info.java new file mode 100644 index 00000000..df016e33 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/Implements.java b/src/main/java/org/spongepowered/asm/mixin/Implements.java index 0547eaf9..1820ad9a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Implements.java +++ b/src/main/java/org/spongepowered/asm/mixin/Implements.java @@ -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. + * + *

See Introduction to Mixins - Resolving + * Method Signature Conflicts for details on soft implementation of + * interfaces.

*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) diff --git a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java index 721e513b..1896b7db 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java +++ b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java @@ -46,10 +46,10 @@ import java.lang.annotation.Target; *

Consider the following code:

* *
@Shadow public int getSomething();
- * 
- * public int soft$getSomething() {
- *     return this.getSomething();
- * }
+ * + *public int soft$getSomething() { + * return this.getSomething(); + *} * *

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; * *

@Shadow private int something;
  * 
- * public int soft$getSomething() {
- *     return this.something;
- * }
+ *public int soft$getSomething() { + * return this.something; + *} * *

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 @Intrinsic}:

* *
@Shadow public int getSomething();
- * 
- * @Intrinsic // don't merge the method if the target already exists
- * public int soft$getSomething() {
- *     return this.getSomething();
- * }
+ * + *@Intrinsic // don't merge the method if the target already exists + *public int soft$getSomething() { + * return this.getSomething(); + *} * *

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:

* *
@Shadow public int getSomething();
- * 
- * public int soft$getSomething() {
- *     return this.someCondition ? this.someOtherValue : this.getSomething();
- * }
+ * + *public int soft$getSomething() { + * return this.someCondition ? this.someOtherValue : this.getSomething(); + *} * *

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.

* *
@Shadow public int getSomething();
- * 
- * @Intrinsic(displace = true) // if the target already exists, displace it
- * public int soft$getSomething() {
- *     return this.someCondition ? this.someOtherValue : this.getSomething();
- * }
+ * + *@Intrinsic(displace = true) // if the target already exists, displace it + *public int soft$getSomething() { + * return this.someCondition ? this.someOtherValue : this.getSomething(); + *} * */ @Target({ ElementType.METHOD }) diff --git a/src/main/java/org/spongepowered/asm/mixin/Mixin.java b/src/main/java/org/spongepowered/asm/mixin/Mixin.java index 3d490711..bd071095 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Mixin.java +++ b/src/main/java/org/spongepowered/asm/mixin/Mixin.java @@ -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: + * + *
+ *
The target classes
+ *
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 @Pseudo}, the targets should be + * specified via the {@link #targets} instead.
+ *
The priority
+ *
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.
+ *
*/ @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 + * @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. + * + *

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.

* - * @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. + * + *

Priorities sort mixins into natural order 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.

* * @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; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 1355d049..a1476034 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -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 null 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 providerClass = (Class)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); diff --git a/src/main/java/org/spongepowered/asm/mixin/Pseudo.java b/src/main/java/org/spongepowered/asm/mixin/Pseudo.java index fc6c394a..335304f4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Pseudo.java +++ b/src/main/java/org/spongepowered/asm/mixin/Pseudo.java @@ -30,23 +30,38 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * A Mixin marked as Pseudo 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 @Pseudo is allowed to target classes which are + * not available at compile time 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 available known + * superclass of the target. This means that certain restrictions apply: * - *

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 SomeCustomScreen from - * another party which extends GuiScreen which is obfuscated. - * Attempting to inject into initGui 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 - * initGui to be resolved in the superclass hierarchy (this is not the - * case for normal mixins).

+ *

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 CustomGuiScreen from + * another party which extends GuiScreen, where GuiScreen is + * an obfuscated class. GuiScreen contains an obfuscated method + * initGui which the (@Pseudo) target class overrides. Attempting + * to inject into initGui 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 initGui + * 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.

* - *

{@link Overwrite} methods which are not inherited from a superclass - * (if the target is obfuscated) must be decorated manually with aliases. - *

+ *

If the target class contains obfuscated methods which the mixin needs to + * {@link Overwrite} or {@link Shadow} which are not inherited from a + * superclass (eg. the target is obfuscated), the {@link Overwrite} or + * {@link Shadow} must be decorated manually with aliases since + * there is no mechanism for the AP to resolve the mappings automatically.

*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) diff --git a/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java b/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java new file mode 100644 index 00000000..0a71a362 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/connect/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java new file mode 100644 index 00000000..79f0a47d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java index d6b9aa29..a33488d8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -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(); - accessor.visibleAnnotations.add(this.info.getAnnotation()); + accessor.visibleAnnotations.add(this.info.getAnnotationNode()); accessor.maxLocals = maxLocals; accessor.maxStack = maxStack; return accessor; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java index f10c65ff..f249c0c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java @@ -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); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java index 34dd8196..4295f518 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java @@ -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); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java index 5c09ad4f..bcbc16ff 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java @@ -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)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index fd650c01..52672d85 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -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 { * foo 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 null 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 null 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 findTarget(List> nodes) { - Result result = TargetSelector.run(this.target.configure("orphan"), nodes); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), nodes); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java index cde243e7..b65d0c15 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -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 result = TargetSelector.run(this.target.configure("orphan"), ElementNode.methodList(this.classNode)); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), + ElementNode.methodList(this.classNode)); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java b/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java new file mode 100644 index 00000000..8b740b19 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/package-info.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 @Accessor} and + * {@link org.spongepowered.asm.mixin.gen.Invoker @Invoker}. + */ +package org.spongepowered.asm.mixin.gen; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java index 85d48c85..e7541e74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java @@ -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; } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java new file mode 100644 index 00000000..49468b98 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 789843a5..6136d580 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -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 ordinal allows a particular opcode to diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java new file mode 100644 index 00000000..97ec046b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -0,0 +1,150 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; + +/** + *

A descriptor for matching a target element, for details of usage see + * {@link DynamicSelectorDesc}.

+ * + *

Unlike {@link MemberInfo Explicit Target Selectors} which can match any + * element of a candidate member, @Desc descriptors always match + * all elements of a target explicitly. Element defaults are as follows:

+ * + *
+ *
{@link #owner}
+ *
Defaults to the current target of the mixin if not specified
+ *
{@link #ret}
+ *
Defaults to void
+ *
{@link #args}
+ *
Defaults to an empty array matching a target with no arguments, + * omitting this value does not mean "match any" signature and + * will explicitly match targets with no arguments. This value is ignored + * for fields.
+ *
+ * + *

Notes

+ * + *
    + *
  • 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.
  • + * + *
  • Note that when matching fields the value of {@link #args} is ignored. + *
  • + *
+ */ +@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 or, ocasionally the type of class upon which a virtual + * call is being made. For example if a class SuperType defines a + * method doSomething, usually owner will be + * SuperType. However note that where a method retrieves a + * reference to a derived type DerivedType which overrides + * doSomething, 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. + * + *

When owner is not specified, it defaults to the current + * target of the mixin.

+ */ + 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 void. + */ + public Class ret() default void.class; + + /** + * The argument types of a method to match, ignored for fields. Note that + * failing to specify this value matches a target with no arguments. + */ + 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 + * calls or field accesses (eg. when using this value inside + * {@link At#desc @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 min. 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 calls or field accesses (eg. when + * using this value inside {@link At#desc @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 max to the same value as {@link #min min}. + * Values less than 1 are treated as Integer.MAX_VALUE (the + * default) since setting a value of 0 or less has no meaning. + */ + public int max() default Integer.MAX_VALUE; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java b/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java new file mode 100644 index 00000000..6bb3a8fc --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Descriptors.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java index b98dcad7..cb02eb59 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java @@ -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 @Inject annotation) */ - public abstract AnnotationNode getAnnotation(); - + public abstract AnnotationNode getAnnotationNode(); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index 1fcaf47a..d3122829 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -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 @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 diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 62878768..db042b08 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -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; /** *

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.

+ * with the {@link #find find} method populating a collection with insn nodes + * from the supplied list which satisfy its strategy.

* *

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.

+ * {@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.

* - *

You are free to create your own injection point subclasses, but take note - * that it is allowed 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 - * stateless.

+ *

Built-in Injection Points

+ * + *

The following built-in Injection Points are available:

+ * + *
    + *
  • {@link MethodHead HEAD} - Selects the first insn
  • + *
  • {@link BeforeReturn RETURN} - Selects RETURN insns
  • + *
  • {@link BeforeFinalReturn TAIL} - Selects the last RETURN insn
  • + *
  • {@link BeforeInvoke INVOKE} - Selects method invocations
  • + *
  • {@link AfterInvoke INVOKE_ASSIGN} - Selects STORE insns after method + * invocations which return a value
  • + *
  • {@link BeforeFieldAccess FIELD} - Selects field access insns
  • + *
  • {@link BeforeNew NEW} - Selects object constructions
  • + *
  • {@link BeforeStringInvoke INVOKE_STRING} - Selects method invocations + * where a specific string is passed to the invocation.
  • + *
  • {@link JumpInsnPoint JUMP} - Selects branching (jump) instructions
  • + *
  • {@link BeforeConstant CONSTANT} - Selects constant values
  • + *
+ * + *

Additionally, the two special injection points are available which are + * only supported for use with {@link ModifyVariable @ModifyVariable}:

+ * + *
    + *
  • {@link BeforeLoadLocal LOAD} - Selects xLOAD insns matching the + * ModifyVariable discriminators.
  • + *
  • {@link AfterStoreLocal STORE} - Selects xSTORE insns matching the + * ModifyVariable discriminators.
  • + *
+ * + *

See the javadoc for each type for more details on the scheme used by each + * injection point.

+ * + *

Custom Injection Points

+ * + *

You are free to create your own injection point subclasses. Once defined, + * they can be used by your mixins in one of two ways:

+ * + *
    + *
  1. Specify the fully-qualified name of the injection point class in the + * {@link At#value @At.value}.
  2. + *
  3. Decorate your injection point class with {@link AtCode @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. MYMOD:CUSTOMPOINT) in {@link At#value + * @At.value}.
  4. + *
+ * + *

When writing custom injection points, note that the general contract of + * injection points is that they be entirely - or at least behaviourally - + * stateless. It is allowed for a single InjectionPoint instance to be + * used by the mixin processor for multiple injections and thus implementing + * classes MUST NOT 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.

*/ 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 + * <namespace>:<code> 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 list = (nodes instanceof List) ? (List) nodes : new ArrayList(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 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 parse(IInjectionPointContext context, List ats) { Builder injectionPoints = ImmutableList.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 args, String target, String slice, int ordinal, int opcode, String id) { InjectionPointData data = new InjectionPointData(context, at, args, target, slice, ordinal, opcode, id); - Class ipClass = findClass(context.getContext(), data); - InjectionPoint point = InjectionPoint.create(context.getContext(), data, ipClass); + Class 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 findClass(IMixinContext context, InjectionPointData data) { String type = data.getType(); - Class ipClass = InjectionPoint.types.get(type); + Class 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)Class.forName(type); + ipClass = (Class)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().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 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 type, String namespace) { AtCode code = type.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 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 type) { + String code = type.getAnnotation(AtCode.class).value().toUpperCase(Locale.ROOT); + InjectionPoint.types.put(code, type); + InjectionPoint.types.put("MIXIN:" + code, type); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index 645a60bf..048b8238 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -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. * - *

Consider the following method call:

+ *

Use this injector when a method contains an method invocation and you wish + * to change a single value being passed to that method. If you need to + * alter an argument received by a target method, use {@link + * ModifyVariable} instead.

* - *
// x, y and z are of type float
- *someObject.setLocation(x, y, z, true);
+ *

Consider the following method:

* - *

Let us assume that we wish to modify the y value in the method - * call. We know that the arguments are floats and that the y - * value is the second (index = 1) float argument. Thus our - * injector requires the following signature: + *

private void targetMethod() {
+ *    Entity someEntity = this.obtainEntity();
+ *    float x = 1.0F, y = 3.0F, z = 0.1F;
+ *    someEntity.setLocation(x, y, z, true);
+ *}
+ *
+ * + *

Let us assume that we wish to modify the y value when + * calling the setLocation method. We know that the + * arguments are floats and that the y value is the second + * (index = 1) float argument. Thus our injector requires the + * following signature: * - *

@ModifyArg(method = "...", at = ..., index = 1)
- *private float adjustYCoord(float y) {
- *    return y + 64.0F;
- *}
+ *
@ModifyArg(method = "targetMethod", at = @At(value + * = "INVOKE", target = "setLocation(FFFZ)V"), index = 1)
+ * private float adjustYCoord(float y) {
+ *     return y + 64.0F;
+ * }
* *

The callback consumes the original value of y and returns the * adjusted value.

@@ -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:

* - *
@ModifyArg(method = "...", at = ..., index = 1)
- *private float adjustYCoord(float x, float y, float z, boolean interpolate) {
- *    return (x == 0 && y == 0) ? 0 : y;
- *}
+ *
@ModifyArg(method = "targetMethod", at = @At(value + * = "INVOKE", target = "setLocation(FFFZ)V"), index = 1)
+ * private float adjustYCoord(float x, float y, float z, boolean interpolate) { + *
    return (x == 0 && y == 0) ? 0 : y;
+ * }
*/ @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 @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 diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java index 69018c32..bb702003 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java @@ -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 @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 diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java index 6e7ba332..9870a40e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -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 @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 diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 83acc4fe..a525f02a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -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. + * + *

If the variable being modified is a method argument, specifying the + * {@link #argsOnly argsOnly=true} reduces the overhead of calculating + * the local variable table for the method.

* *

ModifyVariable callbacks should always take one argument of the * type to capture and return the same type. For example a ModifyVariable - * for a local of type {@link String} should have the signature:

+ * for a local of type {@link String} should have the + * signature:

* - * private String methodName(String variable) { ... + *
private String myHandlerMethod(String + * variable) {
    ...
* *

The callback receives the current value of the local variable, and should * return the new value.

* *

The injector has two operating modes, explicit and implicit - * , and can operate either on the entire LVT or on the method arguments - * only

. + * , and can operate either on the entire LVT or on the {@link #argsOnly + * method arguments only}.

+ * + *

Explicit mode

* *

In explicit 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.

* + *

Implicit mode

+ * *

If no values for the capture discrimiators are specified, the injector * operates in implicit 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.

* + *

Context-sensitive injection points

+ * + *

Normally the {@link InjectionPoint injection points} specified by {@link + * #at} are independent of the injector being used. With ModifyVariable + * there are two special injection points which consume the discriminator from + * the annotation:

+ * + *
    + *
  • {@link BeforeLoadLocal LOAD} - matches xLOAD insns for + * the variable matched by the discriminator in the target method.
  • + *
  • {@link AfterStoreLocal STORE} - matches xSTORE insns for + * the variable matched by the discriminator in the target method.
  • + *
+ * + *

See the javadoc for each injection point for details.

+ * + *

Notes

+ * *

Like other injectors, the callback signature can optionally include the * target method arguments by simply appending them to the handler method * signature.

@@ -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 @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(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 6df4b87f..b72f5fdc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -55,7 +55,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * int def = 1; * Foo someObject = new Foo(); * - * // Hooking this method + * // Hooking this method * boolean xyz = someObject.bar(abc, def); *} * @@ -63,7 +63,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *

The signature of the redirected method should be:

* *
- *
public boolean barProxy(Foo someObject, int abc, int def)
+ * public boolean barProxy(Foo someObject, int abc, int def) *
* *

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:

* *
- *
public boolean barProxy(Foo someObject, int abc, int def,
- *    int someInt, String someString)
+ * public boolean barProxy(Foo someObject, int abc, int def, + * int someInt, String someString) *
* *

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 write (PUTFIELD, PUTSTATIC) or a * field read (GETFIELD, GETSTATIC).

* - *
0.8.10.8.3February 2021 +
    +
  • Added dynamic target selector support and @Desc + target selector
  • +
  • Added pattern target selector
  • +
  • Added more expressive quantifier support to explicit target + selectors
  • +
  • Facelift and overall improvements to javadoc
  • +
+
0.8.1 (0.8.2) September 2020
  • Hotfix for supporting ModLauncher 7.0
  • Fix critical issue with resolving obfuscated members in inherited interfaces
  • +
  • Updated to ASM 7.2
+ *
* * * @@ -148,7 +148,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * indices, for multi-dimensional arrays) and returns the element * type (in this case String) as follows:

* - *
Operation (OPCODE)Handler signature
+ *
* * * @@ -177,16 +177,16 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * array=length and configure your handler signature to return int * and consume the array as an argument:

* - *
private int getLength(ElementType[] array) + *
private int getLength(ElementType[] array) *
- * + * - *

For multi-dimensional arrays, provide one int argument for each * additional dimension of the array:

* - *
// Multidimensional array
- * private ElementType[][] array;

- * // Handler signature:
- * private int getLength(ElementType[][] array, int baseDim) + *
// Multidimensional array
+ * private ElementType[][] array;

+ * // Handler signature:
private int + * getLength(ElementType[][] array, int baseDim) *
* *

New Object Redirect Mode (Factory Mode)

@@ -211,7 +211,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *class Foo { * private final int x, y; * - * // ctor we wish to hook + * // ctor we wish to hook * 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:

* *
public void exampleFunc(String someString, int dx, int dy) {
- *    // Hooking this constructor
+ *    // Hooking this constructor
  *    Foo someFoo = new Foo(dx * 10, dy * 10);
  *}
*
@@ -239,15 +239,15 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; *

The signature of the handler method should be:

* *
- *
public Foo constructFoo(int x, int y)
+ * public Foo constructFoo(int x, int y) *
* *

Note that like other redirectors, it is possible to capture the target * method's arguments by appending them to the handler method's signature:

* *
- * public Foo constructFoo(int x, int y, String someString, int dx, - * int dy) + * public Foo constructFoo(int x, int y, String someString, int dx, + * int dy) *
* *

instanceof Redirect Mode

@@ -277,8 +277,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * *

Note that this results in the injected code being less efficient, because * the instanceof opcode is replaced with discrete code similar to - * reference != null && yourClass.isAssignableFrom(reference.getClass()) in - * the target method body.

+ * reference != null && yourClass.isAssignableFrom(reference.getClass()) + * in the target method body.

* *

The arguments to an instanceof redirect handler must always be * Object, Class even if the variable type is known. This is @@ -298,7 +298,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * *

class Foo : Bar {
  *    Foo(int arg) {
- *        super(Foo.isEven(arg));
+ *        super(Foo.isEven(arg));
  *    }
  *    
  *    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 @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
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
index 769b1555..857432db 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java
@@ -85,7 +85,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
  *         thing.processStuff();
  *     }
  *     
- *     // A new call to processStuff, which now has the ordinal 1
+ *     // A new call to processStuff, which now has the ordinal 1
  *     bar.getActiveThing().processStuff();
  *     
  *     Thing specialThing = bar.getSpecialThing();
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
index 5009a231..79188adf 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
@@ -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 @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.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.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 expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
-        List found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0));
+        int targetArgc = callback.target.arguments.length + 1;
+        List expected = CallbackInjector.summariseLocals(this.methodNode.desc, targetArgc, 255);
+        List 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 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 summariseLocals(String desc, int pos) {
-        return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos);
+    private static List summariseLocals(String desc, int pos, int count) {
+        return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos, count);
     }
 
-    private static List summariseLocals(Type[] locals, int pos) {
+    private static List summariseLocals(Type[] locals, int pos, int count) {
         List list = new ArrayList();
         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());
                 }
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java
new file mode 100644
index 00000000..39952e3a
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/package-info.java
@@ -0,0 +1,30 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered 
+ * 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;
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java
index d985037a..9f7b07c7 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java
@@ -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 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 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 findTargetNodes(InjectorTarget injectorTarget, List injectionPoints) {
-        IMixinContext mixin = this.info.getContext();
+        IMixinContext mixin = this.info.getMixin();
         MethodNode method = injectorTarget.getMethod();
         Map targetNodes = new TreeMap();
         Collection nodes = new ArrayList(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 nodes) {
-        return injectionPoint.find(into.desc, insns, nodes);
+    protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget,
+            Collection nodes) {
+        return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes);
     }
 
     protected void sanityCheck(Target target, List 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, "", "(Ljava/lang/String;)V", false));
         insns.add(new InsnNode(Opcodes.ATHROW));
+        extraStack.add(3);
     }
     
     /**
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java
index 23c053c7..9347f3a7 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java
@@ -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 cache = new HashMap();
+    private final Map cache = new HashMap();
 
     /**
      * 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.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();
         }
         
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java
similarity index 98%
rename from src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java
rename to src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java
index 528ebac6..70c86574 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InsnListReadOnly.java
@@ -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;
     }
 
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java
index 85ac3af6..77b28703 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java
@@ -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 start and end to be accessed. In essence
      * this class provides a view 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 nodes = new LinkedList();
-        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.getValue(node, "id");
+        String coord = "slice";
+        if (!Strings.isNullOrEmpty(id)) {
+            coord += "." + id;
+        }
+        InjectionPointAnnotationContext sliceContext = new InjectionPointAnnotationContext(info, node, coord);
         
         AnnotationNode from = Annotations.getValue(node, "from");
         AnnotationNode to = Annotations.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);
     }
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java
index 3681ed5a..fb9979aa 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java
@@ -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.getValue(annotation, "slice", true)) {
                 MethodSlice slice = MethodSlice.parse(info, node);
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java
new file mode 100644
index 00000000..1a505452
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/package-info.java
@@ -0,0 +1,29 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered 
+ * 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;
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java
index 95a046b9..30a29cee 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java
@@ -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 @ModifyArg}.
  */
 public class ModifyArgInjector extends InvokeInjector {
 
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java
index b722d806..051831a0 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java
@@ -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 @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().getGenerator(ArgsClassGenerator.class);
+        this.argsClassGenerator = info.getMixin().getExtensions().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();
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java
index 3f60bb30..3ef551e6 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java
@@ -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 @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);
         }
         
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
index a8aa0f47..3a5b5fc7 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
@@ -58,14 +58,17 @@ import com.google.common.primitives.Ints;
  * method. For method redirects, the handler method signature must match the
  * hooked method precisely but 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:

+ * invoked upon. For more details see the javadoc for the {@link Redirect + * @Redirect} annotation.

+ * + *

For example when hooking the following call:

* *
  *   int abc = 0;
  *   int def = 1;
  *   Foo someObject = new Foo();
  *   
- *   // Hooking this method
+ *   // Hooking this method
  *   boolean xyz = someObject.bar(abc, def);
*
* @@ -79,8 +82,8 @@ import com.google.common.primitives.Ints; * methods it is sufficient that the signature simply match the hooked method. *

* - *

For field redirections, see the details in {@link Redirect} for the - * required signature of the handler method.

+ *

For field redirections, see the details in {@link Redirect @Redirect} + * for the required signature of the handler method.

* *

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(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java new file mode 100644 index 00000000..e0a1adc5 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/package-info.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 @ModifyArgs} + * which handle argument bundles + * ({@link org.spongepowered.asm.mixin.injection.invoke.arg.Args}). + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java new file mode 100644 index 00000000..cbfaf69d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java new file mode 100644 index 00000000..3dd49622 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java index 1d2156ff..609fb55c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java @@ -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 nodes) { + boolean find(InjectionInfo info, InsnList insns, Collection nodes, Target target) { SearchState state = new SearchState(); - ListIterator iter = target.method.instructions.iterator(); + ListIterator iter = insns.iterator(); while (iter.hasNext()) { AbstractInsnNode insn = iter.next(); if (state.isPendingCheck()) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java index b5c5ad87..544e5184 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -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; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 7e2916af..147d9076 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -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 nodes); + abstract boolean find(InjectionInfo info, InsnList insns, Collection 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 nodes) { + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget, + Collection 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.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.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(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java new file mode 100644 index 00000000..20ceda6c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 + * @ModifyVariable} + */ +package org.spongepowered.asm.mixin.injection.modify; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java new file mode 100644 index 00000000..c1190db2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index 8354bb58..1036cdc5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -71,41 +71,41 @@ import com.google.common.primitives.Longs; *

ordinal
*
The ordinal position of the constant opcode to match. The default value * is -1 which supresses ordinal matching
- *
named argument nullValue
+ *
named argument: nullValue
*
To match null literals in the method body, set this to * true
- *
named argument intValue
+ *
named argument: intValue
*
To match int literals in the method body. See also the * expandZeroConditions argument below for concerns when matching * conditional zeroes.
- *
named argument floatValue
+ *
named argument: floatValue
*
To match float literals in the method body.
- *
named argument longValue
+ *
named argument: longValue
*
To match long literals in the method body.
- *
named argument doubleValue
+ *
named argument: doubleValue
*
To match double literals in the method body.
- *
named argument stringValue
+ *
named argument: stringValue
*
To match {@link String} literals in the method body.
- *
named argument classValue
+ *
named argument: classValue
*
To match {@link Class} literals in the method body.
- *
named argument log
+ *
named argument: log
*
Enable debug logging when searching for matching opcodes.
- *
named argument expandZeroConditions
+ *
named argument: expandZeroConditions
*
See the {@link Constant#expandZeroConditions} option, this argument * should be a list of {@link Condition} names
* * *

Examples:

*
- *   // Find all integer constans with value 4
+ *   // Find all integer constans with value 4
  *   @At(value = "CONSTANT", args = "intValue=4")
*
*
- *   // Find the String literal "foo"
+ *   // Find the String literal "foo"
  *   @At(value = "CONSTANT", args = "stringValue=foo"
*
*
- *   // Find all integer constants with value 0 and expand conditionals
+ *   // Find integer constants with value 0 and expand conditionals
  *   @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 conditions = new ArrayList();
@@ -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) {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
index 0cc4b05d..5d3de468 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
@@ -49,21 +49,33 @@ import org.spongepowered.asm.util.Bytecode;
  * 
*
target
*
A {@link ITargetSelector Target Selector} which identifies the target - * field.
+ * field. *
opcode
*
The {@link Opcodes opcode} of the field access, must be one of - * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
+ * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. *
ordinal
*
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 ordinal of 2 (ordinals are zero-indexed). The - * default value is -1 which supresses ordinal matching
+ * field is referenced 3 times and you want to match the 3rd then you can + * specify an ordinal of 2 (ordinals are zero-indexed). The + * default value is -1 which supresses ordinal matching + *
named argument: array
+ *
For matching accesses to an array field element following a GETFIELD or + * GETSTATIC. Specify get, set or length to match + * the desired operation.
+ *
named argument: fuzz
+ *
When matching array operations using array 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 array is not specified.
*
* *

Example:

- *
+ * 
* @At(value = "FIELD", target="field_59_z:I", opcode = Opcodes.GETFIELD) - *
+ * *
* *

Matching array access:

@@ -72,9 +84,10 @@ import org.spongepowered.asm.util.Bytecode; * operation. To enable this behaviour specify the array named-argument * with the desired operation:

* - *
- *   @At(value = "FIELD", target="myIntArray:[I", args = "array=get")
- * 
+ *
+ * @At(value = "FIELD", target="myIntArray:[I", opcode + * = Opcodes.GETFIELD, args = "array=get") + * *
* *

See {@link Redirect} for information on array element redirection.

diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java index 053fb872..f34f7c65 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java @@ -64,7 +64,7 @@ public class BeforeFinalReturn extends InjectionPoint { public BeforeFinalReturn(InjectionPointData data) { super(data); - this.context = data.getContext(); + this.context = data.getMixin(); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index d58c273a..d531fec0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -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 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 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.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; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java index 7b0df8ce..72249325 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java @@ -52,7 +52,7 @@ import com.google.common.base.Strings; * {@link org.spongepowered.asm.mixin.injection.At At}:

* *
- *
named argument class (or specify using target
+ *
named argument: class (or specify using target
*
The value of the NEW node to look for, the fully-qualified class name *
*
ordinal
@@ -70,16 +70,16 @@ import com.google.common.base.Strings; * *

Examples:

*
- *   // Find all NEW opcodes for String
+ *   // Find all NEW opcodes for String
  *   @At(value = "NEW", args = "class=java/lang/String")
*
*
- *   // Find all NEW opcodes for String
+ *   // Find all NEW opcodes for String
  *   @At(value = "NEW", target = "java/lang/String"
*
*
- *   // Find all NEW opcodes for String which are constructed using the
- *   // ctor which takes an array of char
+ *   // Find all NEW opcodes for String which are constructed
+ *   // using the ctor which takes an array of char
  *   @At(value = "NEW", target = "([C)Ljava/lang/String;"
*
* @@ -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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java index fe02f649..3f6373d8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java @@ -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 ordinal of 2 (ordinals are zero-indexed). The * default value is -1 which supresses ordinal matching - *
named argument ldc
+ *
named argument: ldc
*
The value of the LDC node to look for prior to the method invocation *
*
@@ -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); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java new file mode 100644 index 00000000..d84bf042 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java new file mode 100644 index 00000000..e72ea285 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ElementNode.java @@ -0,0 +1,754 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 node type + */ +public abstract class ElementNode { + + /** + * Element node type, returned by getType 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 getMethod + * will return a value + */ + public final boolean hasMethod; + + /** + * Whether this node holds a field, implies that calling getField + * will return a value + */ + public final boolean hasField; + + /** + * Whether this node holds an insn, implies that calling getInsn + * 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 { + + 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 { + + 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 { + + 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 { + + 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 { + + 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> { + + private final Iterator iter; + + private final boolean filterDynamic; + + ElementNodeIterator(Iterator iter, boolean filterDynamic) { + this.iter = iter; + this.filterDynamic = filterDynamic; + } + + @Override + public boolean hasNext() { + return this.iter.hasNext(); + } + + @Override + public ElementNode 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> { + + private final Iterable iterable; + + private final boolean filterDynamic; + + public ElementNodeIterable(Iterable iterable, boolean filterDynamic) { + this.iterable = iterable; + this.filterDynamic = filterDynamic; +} + + @Override + public Iterator> 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 + * null + */ + public MethodNode getMethod() { + return null; + } + + /** + * Get the {@link FieldNode} if this member is a field, otherwise returns + * null + */ + public FieldNode getField() { + return null; + } + + /** + * Get the {@link AbstractInsnNode instruction} if this member is an insn, + * otherwise returns null + */ + public AbstractInsnNode getInsn() { + return null; + } + + /** + * Get the element owner's name, if this element has an owner, otherwise + * returns null + */ + 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 null + */ + 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 null + * @param method Method node to wrap + * @return ElementNode + */ + public static ElementNode 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 null + * @param field Field node to wrap + * @return ElementNode + */ + public static ElementNode 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 null + * @param node Node to wrap + * @param Node type + * @return ElementNode + * @throws IllegalArgumentException if the supplied argument is not a + * {@link MethodNode} or {@link FieldNode} + */ + @SuppressWarnings("unchecked") + public static ElementNode of(ClassNode owner, TNode node) { + if (node instanceof ElementNode) { + return (ElementNode)node; + } else if (node instanceof MethodNode) { + return (ElementNode)new ElementNodeMethod(owner, (MethodNode)node); + } else if (node instanceof FieldNode) { + return (ElementNode)new ElementNodeField(owner, (FieldNode)node); + } else if (node instanceof MethodInsnNode) { + return (ElementNode)new ElementNodeMethodInsn((MethodInsnNode)node); + } else if (node instanceof InvokeDynamicInsnNode) { + return (ElementNode)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node); + } else if (node instanceof FieldInsnNode) { + return (ElementNode)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 Node type + * @return ElementNode + * @throws IllegalArgumentException if the supplied argument is not a + * {@link MethodNode} or {@link FieldNode} + */ + @SuppressWarnings("unchecked") + public static ElementNode of(TNode node) { + if (node instanceof MethodInsnNode) { + return (ElementNode)new ElementNodeMethodInsn((MethodInsnNode)node); + } else if (node instanceof InvokeDynamicInsnNode) { + return (ElementNode)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node); + } else if (node instanceof FieldInsnNode) { + return (ElementNode)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 null + * @param list List of nodes + * @param Node type + * @return List of wrapped nodes + */ + public static List> listOf(ClassNode owner, List list) { + List> nodes = new ArrayList>(); + for (TNode node : list) { + nodes.add(ElementNode.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 null + * @return List of wrapped nodes + */ + public static List> fieldList(ClassNode owner) { + List> fields = new ArrayList>(); + 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 null + * @return List of wrapped nodes + */ + public static List> methodList(ClassNode owner) { + List> methods = new ArrayList>(); + 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> 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> dynamicInsnList(InsnList insns) { + return new ElementNodeIterable(insns, true); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java new file mode 100644 index 00000000..763bfee4 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java @@ -0,0 +1,87 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 @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); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 1dffd05b..20212a7e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -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; *

Explicit Target Selectors are handled internally using * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the * supported variants and examples.

+ * + *
+ * // An example explicit target selector
+ * Lfully/qualified/OwnerClass;methodName*(III)V + *
+ * + *

Pattern Target Selectors (Regex Selectors)

+ * + *

Pattern 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.

+ * + *
+ * // Matches candidates ending with "Bar" and which take a single int + *
+ * /bar$/ desc=/^\\(I\\)/
+ *
+ * // The same example but with "name" explicitly specified (optional) + *
+ * name=/bar$/ desc=/^\\(I\\)/
+ *
+ * // Matches candidates whose name contains "Entity"
+ * /Entity/ + *
+ * + *

Dynamic Target Selectors

+ * + *

Dynamic Target Selectors can be built-in or user-supplied types + * with their own specialised syntax or behaviour.

+ * + *

Built-in dynamic selectors:

+ * + *
    + *
  • {@link DynamicSelectorDesc @Desc Selector}: Selector which uses + * descriptors defined in {@link Desc @Desc} annotations
  • + *
+ * + *

Dynamic selectors are specified in the following format, and can be + * recognised by the fact that the selector string starts with "@": + *

+ * + *
+ * // Built-in dynamic selector without argument string
+ * @SelectorId
+ *   
+ * // Built-in dynamic selector with empty argument string
+ * @SelectorId()
+ *   
+ * // Built-in dynamic selector with argument
+ * @SelectorId(custom,argument,string,in,any,format)
+ *   
+ * // User-provided dynamic selector with argument. Note that
+ * // user-provided dynamic selectors are namespaced to avoid conflicts.
+ * @Namespace:SelectorId(some arguments)
+ *
+ * + *

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.

+ * */ 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 null 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. + * + *

Can return null

*/ 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. * - *

In other words, calling configure("foo") when this object is - * already configured according to "foo" may simply return this - * object, or might return an identically-configured copy.

+ *

In other words, calling configure(Configure.ORPHAN) when this + * object is already an orphan or does not support orphaning, may + * simply return this object, or might return an identically-configured + * copy.

* + *

Must not return null, defaults to returning unmodified selector.

+ * + * @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 MatchResult match(ElementNode 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); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java index c1c9d803..ccfb1299 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java @@ -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 <init> - */ - public abstract boolean isConstructor(); - - /** - * Get whether this selector represents a class initialiser - * - * @return true if member name is <clinit> - */ - public abstract boolean isClassInitialiser(); - - /** - * Get whether this selector represents a constructor or class initialiser - * - * @return true if member name is <init> or - * <clinit> - */ - public abstract boolean isInitialiser(); - /** * Get a representation of this selector as a complete descriptor */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java new file mode 100644 index 00000000..e9ffee8e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java @@ -0,0 +1,78 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 @MyNamespace:MySelector(argshere) + * 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 + * <namespace>:<id> 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 value(); + + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java index 55780b59..9cc3253d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java @@ -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 <init> + */ + public abstract boolean isConstructor(); + /** + * Get whether this selector represents a class initialiser + * + * @return true if member name is <clinit> + */ + public abstract boolean isClassInitialiser(); + + /** + * Get whether this selector represents a constructor or class initialiser + * + * @return true if member name is <init> or + * <clinit> + */ + public abstract boolean isInitialiser(); + /** * Returns this selector as a {@link MappingField} or * {@link MappingMethod} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java new file mode 100644 index 00000000..6d7fb435 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -0,0 +1,139 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 + * null, 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 MatchResult match(ElementNode node) { + this.validate(); + return MatchResult.NONE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java new file mode 100644 index 00000000..2ab8dd4f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -0,0 +1,257 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + * + *

Regular expressions for this selector should be enclosed in / as + * a delimiter character, and \ characters must be escaped per normal + * Java conventions (eg. use \\s instead of \s since the + * backslash must be escaped). Forward slash (/) characters in the + * regex must be escaped as well to avoid being consumed as ending delimiters. + *

+ * + *

By default the regex match is performed against the name of the + * candidate, to specify matching against owner or desc, each + * pattern should be prefixed with owner= or desc= outside + * the delimiting /. + * + *

Some examples:

+ *
+ *   // Matches candidates starting with "foo"
+ *   /^foo/
+ *   
+ *   // Matches candidates ending with "Bar" and which take a single int
+ *   /bar$/ desc=/^\\(I\\)/
+ *   
+ *   // The same example but with "name" explicitly specified (optional)
+ *   name=/bar$/ desc=/^\\(I\\)/
+ *   
+ *   // Matches candidates whose name contains "Entity"
+ *   /Entity/
+ *   
+ *   // Matches candidates whose owner contains "/google/", note the
+ *   // escaping of the forward slash symbols
+ *   owner=/\\/google\\//
+ *
+ * + *

The owner, name and desc expressions can be + * provided in any order.

+ */ +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*)?/(.*?)(? MatchResult match(ElementNode 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; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index f3ed43cb..2d7e61ce 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -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 exactMatch; /** * All candidates returned by the query */ - public final List candidates; + public final List> candidates; - Result(TNode exactMatch, List candidates) { + Result(ElementNode exactMatch, List> 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 type; + + final Class annotation; + + final Method mdParseString, mdParseAnnotation; + + DynamicSelectorEntry(String namespace, String id, Class 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 annotation = null; + Method mdParseAnnotation = null; + + SelectorAnnotation selectorAnnotation = type.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 dynamicSelectors = new LinkedHashMap(); + + 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 type, String namespace) { + SelectorId selectorId = type.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 type) { + SelectorId selectorId = type.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 parseAndValidate(Iterable selectors, ISelectorContext context) throws InvalidSelectorException { + Set parsed = TargetSelector.parse(selectors, context, new LinkedHashSet()); + 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 parse(Iterable selectors, ISelectorContext context) { + return TargetSelector.parse(selectors, context, new LinkedHashSet()); + } + + /** + * 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 parsed parameter, + * for convenience + */ + public static Set parse(Iterable selectors, ISelectorContext context, Set parsed) { + if (parsed == null) { + parsed = new LinkedHashSet(); + } + 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 Node type * @return query result */ - public static Result run(ITargetSelector target, List> nodes) { - List candidates = new ArrayList(); - TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates); + public static Result run(ITargetSelector selector, Iterable> nodes) { + List> candidates = new ArrayList>(); + ElementNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates); return new Result(exactMatch, candidates); } /** * Run query on supplied target nodes * - * @param targets Target selector + * @param selector Target selector * @param nodes Node collection to enumerate * @param Node type * @return query result */ - public static Result run(Iterable targets, List> nodes) { - TNode exactMatch = null; - List candidates = new ArrayList(); + public static Result run(Iterable selector, Iterable> nodes) { + ElementNode exactMatch = null; + List> candidates = new ArrayList>(); - for (ITargetSelector target : targets) { - TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); + for (ITargetSelector target : selector) { + ElementNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); if (exactMatch == null) { exactMatch = selectorExactMatch; } @@ -190,20 +484,32 @@ public final class TargetSelector { return new Result(exactMatch, candidates); } - private static TNode runSelector(ITargetSelector target, List> nodes, List candidates) { - TNode exactMatch = null; - for (ElementNode element : nodes) { - MatchResult match = target.match(element); + private static ElementNode runSelector(ITargetSelector selector, Iterable> nodes, + List> candidates) { + int matchCount = 0; + ElementNode exactMatch = null; + for (Iterator> iterator = nodes.iterator(); iterator.hasNext();) { + ElementNode 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; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java new file mode 100644 index 00000000..cd8ff753 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -0,0 +1,426 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 searched; + + /** + * The resolved descriptor + */ + private final IAnnotationHandle desc; + + /** + * Selector context + */ + private final ISelectorContext context; + + Descriptor(Set 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.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.getValue("value", ""); + if (!value.isEmpty()) { + return value; + } + return this.desc.getValue("name", ""); + } + + @Override + public Type[] getArgs() { + if (this.desc == null) { + return new Type[0]; + } + List 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.getValue("min", 0) : 0); + Integer max = this.desc != null ? this.desc.getValue("max", null) : null; + return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1); + } + + @Override + public List getNext() { + return this.desc != null ? this.desc.getAnnotationList("next") : Collections.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 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 searched = new LinkedHashSet(); + + @Override + public void visit(String coordinate, Object element, String detail) { + this.searched.add(coordinate); + } + + @Override + public Set 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 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 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; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java new file mode 100644 index 00000000..a1315850 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -0,0 +1,521 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 @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 @At annotation and the @Desc + * annotation itself, which might be on a parent element for convenience. + * + *

See {@link Desc @Desc} for the specific syntax of descriptor + * annotations.

+ * + *

Local Descriptors

+ * + *

Some annotations can use {@link Desc @Desc} selectors directly, + * namely {@link At @At} (specified in {@link At#desc @At.desc}) and + * all Injector annotations (specified in target - for example + * {@link Inject#target @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.

+ * + *

Resolved Descriptors

+ * + *

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:

+ * + *
@Mixin(TargetClass.class)
+ * @Desc(id = "foo", value = "getFoo", args = { int.class }) + *
+ * abstract class MyMixin {
+ *
+ *     @Inject(target = "@Desc(foo)", at = + * @At("RETURN"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     }
+ *
+ * }
+ * + *

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.

+ * + *

Implicit coordinates

+ * + *

As an alternative to specifying an explicit 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 "@Desc" + * with no arguments and give the descriptor an {@link Desc#id id} which + * corresponds to the coordinate of the consumer:

+ * + *

In this example, the coordinate of the {@link At @At} annotation, + * "at" is used as the descriptor id.

+ * + *
+ *     @Desc(id = "at", + * value = "theMethodName", args = { String.class }, ret = boolean.class)
+ *     @Inject(method = "targetMethod()V", at = + * @At(value = "INVOKE" target = "@Desc"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     } + *
+ * + *

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 @At} annotations inside a {@link Slice @Slice} + * will first resolve as (local coordinate) from, followed by + * slice.from, and finally handlerMethodName.slice.from. This + * allows implicit coordinates to be used up to the mixin level as in the first + * example.

+ * + *
@Mixin(TargetClass.class)
+ * @Desc(id = "myHandlerMethod.at", value = "theMethodName", + * args = { String.class }, ret = boolean.class)
+ * @Desc(id = "myHandlerMethod.method", value = "getFoo", args = + * { int.class })
+ * abstract class MyMixin {
+ *
+ *     @Inject(method = "@Desc", at = @At(value = + * "INVOKE" target = "@Desc"))
+ *     void myHandlerMethod(int arg, CallbackInfo ci) {
+ *       ...
+ *     } + *
+ * + *

To view the coordinates used to resolve the descriptor for a particular + * element, use the special id "?" in the selector:

+ * + *
+ *     @Inject(method = "@Desc", at = @At(value = + * "INVOKE" target = "@Desc(?)")) + *
+ *     void myHandler(int arg, CallbackInfo ci) { + *
+ * + *

This will cause the resolver to pretty-print the considered coordinates + * and elements into the console:

+ * + *
/*****************************************************/
+ */* Coordinate    Search Element       Detail         */
+ */*****************************************************/
+ */* at            @At                  @At.desc       */
+ */* at            myHandler            method         */
+ */* myhandler.at  mixins.json:MyMixin  mixin          */
+ */* myhandler.at  @Redirect            @Redirect.desc */
+ */* myhandler.at  myhandler            method         */
+ */*****************************************************/
+ *
+ * + *

Don't worry that some combinations of coordinate and element are not + * possible (for example there is no member desc on @At). + * The resolver doesn't know that and scans each visited element for members it + * supports.

+ */ +@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 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 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 MatchResult match(ElementNode 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; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java new file mode 100644 index 00000000..39a0860f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java @@ -0,0 +1,94 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.util.Quantifier; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +/** + * A resolved descriptor, or rather the result of resolving a descriptor. If the + * descriptor was not resolved then {@link #isResolved} returns false. + */ +public interface IResolvedDescriptor { + + /** + * Get whether the descriptor was successfully resolved + */ + public abstract boolean isResolved(); + + /** + * Get the resolved descriptor, or null if the descriptor was not resolved + */ + public abstract IAnnotationHandle getAnnotation(); + + /** + * Get information about the resolution process (eg. visited implicit + * coordinates) as a human-readable string for inclusion in error messages. + */ + public abstract String getResolutionInfo(); + + /** + * Get the ID of the resolved descriptor, should match the query + */ + public abstract String getId(); + + /** + * Get the owner from the resolved descriptor, returns void if the + * descriptor was not resolved. + */ + public abstract Type getOwner(); + + /** + * Get the name from the resolved descriptor, returns an empty string if the + * descriptor was not resolved. + */ + public abstract String getName(); + + /** + * Get the arguments from the resolved descriptor, returns an empty array if + * the descriptor was not resolved. + */ + public abstract Type[] getArgs(); + + /** + * Get the return type from the resolved descriptor, returns void + * if the descriptor was not resolved. + */ + public abstract Type getReturnType(); + + /** + * Get the specified matches values from the resolved descriptor. + */ + public abstract Quantifier getMatches(); + + /** + * Get the values specified for next, if any + */ + public abstract List getNext(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java new file mode 100644 index 00000000..c126bc42 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Dynamic target selectors provide custom logic for selecting injector targets. + */ +package org.spongepowered.asm.mixin.injection.selectors.dynamic; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java new file mode 100644 index 00000000..d50ea83a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Target selectors are consumed by injectors and injection points when + * identifying target members in a class or inside a method, see {@link + * org.spongepowered.asm.mixin.injection.selectors.ITargetSelector}. + */ +package org.spongepowered.asm.mixin.injection.selectors; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java new file mode 100644 index 00000000..7b3e5079 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.throwables; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; + +/** + * Exception to be thrown when a {@link ITargetSelector target selector} + * {@link ITargetSelector#getMinMatchCount min} or + * {@link ITargetSelector#getMaxMatchCount max} constraint is not met when + * running the selector + */ +public class SelectorConstraintException extends SelectorException { + + private static final long serialVersionUID = 1L; + + public SelectorConstraintException(ITargetSelector selector, String message) { + super(selector, message); + } + + public SelectorConstraintException(ITargetSelector selector, Throwable cause) { + super(selector, cause); + } + + public SelectorConstraintException(ITargetSelector selector, String message, Throwable cause) { + super(selector, message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java new file mode 100644 index 00000000..f681e05f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java @@ -0,0 +1,59 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.throwables; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Exception to be thrown for error conditions raised by {@link ITargetSelector + * target selectors} + */ +public class SelectorException extends MixinException { + + private static final long serialVersionUID = 1L; + + private final ITargetSelector selector; + + public SelectorException(ITargetSelector selector, String message) { + super(message); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, Throwable cause) { + super(cause); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, String message, Throwable cause) { + super(message, cause); + this.selector = selector; + } + + public ITargetSelector getSelector() { + return this.selector; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java new file mode 100644 index 00000000..5227389e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 selectors. + */ +package org.spongepowered.asm.mixin.injection.selectors.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 7fea5525..bb686fb5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -30,8 +30,14 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import javax.tools.Diagnostic.Kind; @@ -50,9 +56,13 @@ import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.code.MethodSlice; import org.spongepowered.asm.mixin.injection.code.MethodSlices; +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.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorException; 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; @@ -66,7 +76,6 @@ import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.ASM; -import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.logging.MessageRouter; @@ -117,19 +126,19 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC final Class annotationType; - final Class type; + final Class injectorType; final Constructor ctor; - final String simpleName; + final String annotationDesc; final String prefix; InjectorEntry(Class annotationType, Class type) throws NoSuchMethodException { this.annotationType = annotationType; - this.type = type; + this.injectorType = type; this.ctor = type.getDeclaredConstructor(MixinTargetContext.class, MethodNode.class, AnnotationNode.class); - this.simpleName = annotationType.getSimpleName() + ";"; + this.annotationDesc = Type.getDescriptor(annotationType); HandlerPrefix handlerPrefix = type.getAnnotation(HandlerPrefix.class); this.prefix = handlerPrefix != null ? handlerPrefix.value() : InjectionInfo.DEFAULT_PREFIX; @@ -144,13 +153,40 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC throw (MixinException)cause; } Throwable ex = cause != null ? cause : itex; - throw new MixinError("Error initialising injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex); + throw new MixinError("Error initialising injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex); } catch (ReflectiveOperationException ex) { - throw new MixinError("Failed to instantiate injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex); + throw new MixinError("Failed to instantiate injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex); } } } + /** + * Selected target, paired with the selector which identified it + */ + static class SelectedTarget { + + private final ITargetSelector root; + + final ITargetSelector selector; + + final MethodNode method; + + SelectedTarget(ITargetSelector root, ITargetSelector selector, MethodNode method) { + this.root = root; + this.selector = selector; + this.method = method; + } + + SelectedTarget(ITargetSelector selector, MethodNode method) { + this(null, selector, method); + } + + ITargetSelector getRoot() { + return this.root != null ? this.root : this.selector; + } + + } + /** * Default conform prefix for handler methods */ @@ -183,10 +219,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC */ protected final boolean isStatic; + /** + * Target selector(s) + */ + protected final Set selectors = new LinkedHashSet(); + /** * Target method(s) */ - protected final Deque targets = new ArrayDeque(); + protected final List targets = new ArrayList(); /** * Method slice descriptors parsed from the annotation @@ -285,25 +326,30 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC List injectionPoints = this.readInjectionPoints(); this.parseRequirements(); - this.findMethods(this.parseTargets()); + this.parseSelectors(); + this.findTargets(); this.parseInjectionPoints(injectionPoints); this.injector = this.parseInjector(this.annotation); } - protected Set parseTargets() { - List methods = Annotations.getValue(this.annotation, "method", false); - if (methods == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", + protected void parseSelectors() { + Set selectors = new LinkedHashSet(); + TargetSelector.parse(Annotations.getValue(this.annotation, "method", false), this, selectors); + TargetSelector.parse(Annotations.getValue(this.annotation, "target", false), this, selectors); + + // Raise an error if we have no selectors + if (selectors.size() == 0) { + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", this.annotationType, this.methodName)); } - Set selectors = new LinkedHashSet(); - for (String method : methods) { + // Validate and attach the parsed selectors + for (ITargetSelector selector : selectors) { try { - selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin)); + this.selectors.add(selector.validate().attach(this)); } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", - this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus())); + throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: %s. %s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus())); } catch (TargetNotSupportedException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s specifies a target class '%s', which is not supported", @@ -314,7 +360,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC ex.getMessage())); } } - return selectors; } protected List readInjectionPoints() { @@ -369,11 +414,26 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC */ public void prepare() { this.targetNodes.clear(); - for (MethodNode targetMethod : this.targets) { - Target target = this.mixin.getTargetMethod(targetMethod); - InjectorTarget injectorTarget = new InjectorTarget(this, target); - this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); - injectorTarget.dispose(); + for (SelectedTarget targetMethod : this.targets) { + Target target = this.mixin.getTargetMethod(targetMethod.method); + InjectorTarget injectorTarget = new InjectorTarget(this, target, targetMethod.selector); + try { + this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); + } catch (SelectorException ex) { + throw new InvalidInjectionException(this, String.format("Injection validation failed: %s on %s: %s. %s%s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); + } finally { + injectorTarget.dispose(); + } + } + } + + /** + * Perform pre-injection checks and tasks + */ + public void preInject() { + for (Entry> entry : this.targetNodes.entrySet()) { + this.injector.preInject(entry.getKey(), entry.getValue()); } } @@ -435,12 +495,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } /** - * Get methods being injected into + * Get number of methods being injected into * - * @return methods being injected into + * @return count of methods being injected into */ - public Collection getTargets() { - return this.targets; + public int getTargetCount() { + return this.targets.size(); } /** @@ -519,44 +579,68 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } /** - * Finds methods in the target class which match searchFor - * - * @param selectors members to search for + * Find methods in the target class which match the parsed selectors */ - private void findMethods(Set selectors) { + protected void findTargets() { this.targets.clear(); + this.findRootTargets(); + this.validateTargets(); + } + /** + * Evaluate the root selectors parsed from this injector, find the root + * targets and store them in the {@link #targets} collection. + */ + private void findRootTargets() { // When remapping refmap is enabled this implies we are in a development // environment. In certain circumstances including the descriptor for // the method may actually fail, so we will do a second pass without the // descriptor if this happens. int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1; - for (ITargetSelector selector : selectors) { - int matchCount = selector.getMatchCount(); - for (int count = 0, pass = 0; pass < passes && count < 1; pass++) { + for (ITargetSelector selector : this.selectors) { + selector = selector.configure(Configure.SELECT_MEMBER); + + int matchCount = 0; + int maxCount = selector.getMaxMatchCount(); + + // Second pass ignores descriptor + ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); + int selectorPasses = (permissiveSelector == selector) ? 1 : passes; + + scan: for (int pass = 0; pass < selectorPasses && matchCount < 1; pass++) { + ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector; for (MethodNode target : this.classNode.methods) { - if (selector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + if (passSelector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + matchCount++; + boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null; - if (matchCount > 1 && (Bytecode.isStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { - continue; + if (maxCount <= 1 || ((this.isStatic || !Bytecode.isStatic(target)) && target != this.method && !isMixinMethod)) { + this.checkTarget(target); + this.targets.add(new SelectedTarget(passSelector, target)); } - - this.checkTarget(target); - this.targets.add(target); - count++; - - if (count >= matchCount) { - break; + + if (matchCount >= maxCount) { + break scan; } } } - - // Second pass ignores descriptor - selector = selector.configure("permissive"); + } + + if (matchCount < selector.getMinMatchCount()) { + throw new InvalidInjectionException(this, new SelectorConstraintException(selector, String.format( + "Injection validation failed: %s for %s on %s did not match the required number of targets (required=%d, matched=%d). %s%s", + selector, this.annotationType, this.methodName, selector.getMinMatchCount(), matchCount, + this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()))); } } - + } + + /** + * Post-search validation that some targets were found, we can fail-fast if + * no targets were actually identified + */ + protected void validateTargets() { this.targetCount = this.targets.size(); if (this.targetCount > 0) { return; @@ -565,17 +649,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if ((this.mixin.getOption(Option.DEBUG_INJECTORS) && this.expectedCallbackCount > 0)) { throw new InvalidInjectionException(this, String.format("Injection validation failed: %s annotation on %s could not find any targets matching %s in %s. %s%s", - this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } else if (this.requiredCallbackCount > 0) { throw new InvalidInjectionException(this, String.format("Critical injection failure: %s annotation on %s could not find any targets matching %s in %s. %s%s", - this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } } - private void checkTarget(MethodNode target) { + protected void checkTarget(MethodNode target) { AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class); if (merged == null) { return; @@ -602,7 +686,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : ""; } - + /** * Parse an injector from the specified method (if an injector annotation is * present). If no injector annotation is present then null is @@ -620,7 +704,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } for (InjectorEntry injector : InjectionInfo.registry.values()) { - if (annotation.desc.endsWith(injector.simpleName)) { + if (annotation.desc.equals(injector.annotationDesc)) { return injector.create(mixin, method, annotation); } } @@ -660,7 +744,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } for (InjectorEntry injector : InjectionInfo.registry.values()) { - if (annotation.desc.endsWith(injector.simpleName)) { + if (annotation.desc.endsWith(injector.annotationDesc)) { return injector.prefix; } } @@ -669,7 +753,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) { - return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); + return String.format("%s->@%s::%s%s", mixin.toString(), Annotations.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); } /** @@ -694,7 +778,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } return sb.toString(); } - + /** * Register an injector info class. The supplied class must be decorated * with an {@link AnnotationType} annotation for registration purposes. @@ -713,16 +797,16 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } catch (NoSuchMethodException ex) { throw new MixinError("InjectionInfo class " + type.getName() + " is missing a valid constructor"); } - InjectorEntry existing = InjectionInfo.registry.get(entry.simpleName); + InjectorEntry existing = InjectionInfo.registry.get(entry.annotationDesc); if (existing != null) { // && !existing.type.equals(type)) { MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding InjectionInfo for @%s with %s (previously %s)", - annotationType.value().getSimpleName(), type.getName(), existing.type.getName())); + annotationType.value().getSimpleName(), type.getName(), existing.injectorType.getName())); } else { MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new injector for @%s with %s", annotationType.value().getSimpleName(), type.getName())); } - InjectionInfo.registry.put(entry.simpleName, entry); + InjectionInfo.registry.put(entry.annotationDesc, entry); ArrayList> annotations = new ArrayList>(); for (InjectorEntry injector : InjectionInfo.registry.values()) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java index 52c13081..f0a1fb7f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java @@ -206,7 +206,7 @@ public class InjectionNodes extends ArrayList { */ @Override public String toString() { - return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget).replaceAll("\\s+", " ")); + return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget, false)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java new file mode 100644 index 00000000..ff2fa85f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java @@ -0,0 +1,95 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +/** + * Specialised SelectorAnnotationContext for injection points + */ +public class InjectionPointAnnotationContext extends SelectorAnnotationContext implements IInjectionPointContext { + + /** + * Parent context + */ + private IInjectionPointContext parentContext; + + public InjectionPointAnnotationContext(IInjectionPointContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) { + super(parent, selectorAnnotation, selectorCoordinate); + this.parentContext = parent; + } + + public InjectionPointAnnotationContext(IInjectionPointContext parent, AnnotationNode selectorAnnotation, String selectorCoordinate) { + super(parent, Annotations.handleOf(selectorAnnotation), selectorCoordinate); + this.parentContext = parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.util.IMessageSink + * #addMessage(java.lang.String, java.lang.Object[]) + */ + @Override + public void addMessage(String format, Object... args) { + this.parentContext.addMessage(format, args); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getMethod() + */ + @Override + public MethodNode getMethod() { + return this.parentContext.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.IInjectionPointContext + * #getAnnotationNode() + */ + @Override + public AnnotationNode getAnnotationNode() { + return this.parentContext.getAnnotationNode(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getAnnotation() + */ + @Override + public IAnnotationHandle getAnnotation() { + return this.parentContext.getAnnotation(); + } + + @Override + public String toString() { + return String.format("%s->%s(%s)", this.parentContext, this.getSelectorAnnotation(), + this.getSelectorCoordinate(false)); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index f970537e..cb4290a9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -39,10 +39,15 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Annotations.Handle; import org.spongepowered.asm.util.IMessageSink; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.base.Joiner; import com.google.common.base.Strings; @@ -174,10 +179,17 @@ public class InjectionPointData { } /** - * Get the context + * Get the injection point context */ - public IMixinContext getContext() { - return this.context.getContext(); + public IInjectionPointContext getContext() { + return this.context; + } + + /** + * Get the mixin context + */ + public IMixinContext getMixin() { + return this.context.getMixin(); } /** @@ -198,7 +210,7 @@ public class InjectionPointData { * Get the root annotation (eg. {@link Inject}) */ public AnnotationNode getParent() { - return this.context.getAnnotation(); + return this.context.getAnnotationNode(); } /** @@ -258,9 +270,9 @@ public class InjectionPointData { */ public ITargetSelector get(String key) { try { - return TargetSelector.parseAndValidate(this.get(key, ""), this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s", + return TargetSelector.parseAndValidate(this.get(key, ""), this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").%s \"%s\" on %s", this.at, key, this.target, this.getDescription()); } } @@ -270,9 +282,19 @@ public class InjectionPointData { */ public ITargetSelector getTarget() { try { - return TargetSelector.parseAndValidate(this.target, this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").target descriptor \"%s\" on %s", + if (Strings.isNullOrEmpty(this.target)) { + IAnnotationHandle selectorAnnotation = this.context.getSelectorAnnotation(); + AnnotationNode desc = Annotations.getValue(((Handle)selectorAnnotation).getNode(), "desc"); + if (desc != null) { + String id = Annotations.getValue(desc, "id", "at"); + if ("at".equalsIgnoreCase(id)) { + return DynamicSelectorDesc.of(Annotations.handleOf(desc), this.context); + } + } + } + return TargetSelector.parseAndValidate(this.target, this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed validating @At(\"%s\").target \"%s\" on %s", this.at, this.target, this.getDescription()); } } @@ -281,7 +303,7 @@ public class InjectionPointData { * Get a description of this injector for use in error messages */ public String getDescription() { - return InjectionInfo.describeInjector(this.getContext(), this.getParent(), this.getMethod()); + return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotationNode(), this.context.getMethod()); } /** @@ -340,7 +362,7 @@ public class InjectionPointData { } private static Pattern createPattern() { - return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values()))); + return Pattern.compile(String.format("^(.+?)(:(%s))?$", Joiner.on('|').join(Selector.values()))); } /** @@ -359,7 +381,7 @@ public class InjectionPointData { } private static Selector parseSelector(Matcher matcher) { - return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT; + return matcher.matches() && matcher.group(3) != null ? Selector.valueOf(matcher.group(3)) : Selector.DEFAULT; } private static int parseInt(String string, int defaultValue) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java index 0871898d..e65384b3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java @@ -264,7 +264,8 @@ public class InjectorGroupInfo { int min = this.getMinRequired(); int max = this.getMaxAllowed(); if (total < min) { - throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total)); + String only = total > 0 ? "only " : ""; + throw new InjectionValidationException(this, String.format("expected %d invocation(s) but %s%d succeeded", min, only, total)); } else if (total > max) { throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java index 82ffd7ee..c8320813 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java @@ -32,17 +32,25 @@ import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; public class InvalidMemberDescriptorException extends InvalidSelectorException { private static final long serialVersionUID = 1L; + private final String input; - public InvalidMemberDescriptorException(String message) { + public InvalidMemberDescriptorException(String input, String message) { super(message); + this.input = input; } - public InvalidMemberDescriptorException(Throwable cause) { + public InvalidMemberDescriptorException(String input, Throwable cause) { super(cause); + this.input = input; } - public InvalidMemberDescriptorException(String message, Throwable cause) { + public InvalidMemberDescriptorException(String input, String message, Throwable cause) { super(message, cause); + this.input = input; + } + + public String getInput() { + return this.input; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index e4a932fb..dcbdecf0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -28,69 +28,200 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; +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.ITargetSelectorConstructor; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; -import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.throwables.MixinException; 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.Bytecode; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; -import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.asm.ASM; import com.google.common.base.Objects; import com.google.common.base.Strings; /** - *

Target selector, also used as a general-purpose information bundle about a - * member (method or field) parsed from a String token in another annotation, - * this is used where target members need to be specified as Strings in order to - * parse the String representation to something useful. See - * {@link ITargetSelector} for other supported selector types.

+ *

Struct which defines an Explcit Target selector, See + * {@link ITargetSelector} for other supported selector types. This struct is + * also used as a general-purpose information bundle about a member (method or + * field) parsed from a String token in another annotation, this is used where + * target members need to be specified as Strings in order to parse the String + * representation to something useful.

* - *

Some examples:

- *
- *   // references a method or field called func_1234_a, if there are multiple
- *   // members with the same signature, matches the first occurrence
- *   func_1234_a
- *   
- *   // references a method or field called func_1234_a, if there are multiple
- *   // members with the same signature, matches all occurrences
- *   func_1234_a*
- *   
- *   // references a method called func_1234_a which takes 3 ints and returns
- *   // a bool
- *   func_1234_a(III)Z
- *   
- *   // references a field called field_5678_z which is a String
- *   field_5678_z:Ljava/lang/String;
- *   
- *   // references a ctor which takes a single String argument 
- *   <init>(Ljava/lang/String;)V
- *   
- *   // references a method called func_1234_a in class foo.bar.Baz
- *   Lfoo/bar/Baz;func_1234_a
- *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   Lcom/example/Dave;field_5678_z
- *  
- *   // references a method called func_1234_a in class foo.bar.Baz which takes
- *   // three doubles and returns void
- *   Lfoo/bar/Baz;func_1234_a(DDD)V
- *   
- *   // alternate syntax for the same
- *   foo.bar.Baz.func_1234_a(DDD)V
- *
+ *

In general a MemberInfo consists of 4 parts, + * owner, name, quantifier + * and descriptor, all of which are optional: + *

+ * + *
OperationHandler signature
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
 OwnerNameQuantifier DescriptorResulting selector string
MethodLfully/qualified/OwnerClass;methodName{1,3} (III)VLfully/qualified/OwnerClass;methodName{1,3}(III)V
FieldLfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;Lfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;
+ * + *

Any part of the selector can be omitted, though they must appear in the + * correct order. Some examples:

+ * + *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with the same signature, matches the first occurrence
+ * func_1234_a
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences

+ * func_1234_a*
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences, matching less than 1 + *
+ * // occurrence is an error condition

+ * func_1234_a+
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches up to 3 occurrences

+ * func_1234_a{,3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches exactly 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches at least 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3,}
+ *
+ * // selects all members of any type and descriptor
+ * *
+ *
+ * // selects the first member of any type and descriptor
+ * {1}
+ *
+ * // selects all methods which take 3 ints and return a bool
+ * *(III)Z
+ *
+ * // selects the first 2 methods which take a bool and return void + *
+ * {2}(Z)V
+ *
+ * // selects a method called func_1234_a which takes 3 ints and returns a + * bool
+ * func_1234_a(III)Z
+ *
+ * // selects a field called field_5678_z which is a String
+ * field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a ctor which takes a single String argument
+ * <init>(Ljava/lang/String;)V
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz
+ * Lfoo/bar/Baz;func_1234_a + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave + *
+ * Lcom/example/Dave;field_5678_z + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave
+ * // which is of type String

+ * Lcom/example/Dave;field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz which
+ * // takes three doubles and returns void

+ * Lfoo/bar/Baz;func_1234_a(DDD)V
+ *
+ * // alternate syntax for the same
+ * foo.bar.Baz.func_1234_a(DDD)V + *
+ * + *

Notes

+ * + * */ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor { + /** + * Separator for elements in the path + */ + private static final String ARROW = "->"; + /** * Member owner in internal form but without L;, can be null */ @@ -107,9 +238,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec private final String desc; /** - * True to match all matching members, not just the first + * Required matches */ - private final boolean matchAll; + private final Quantifier matches; /** * Force this member to report as a field @@ -119,17 +250,21 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec /** * The actual String value passed into the {@link #parse} method */ - private final String unparsed; - + private final String input; + + /** + * The actual String value passed into the {@link #parse} method + */ + private final String tail; + /** * ctor * * @param name Member name, must not be null - * @param matchAll true if this info should match all matching references, - * or only the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, boolean matchAll) { - this(name, null, null, matchAll); + public MemberInfo(String name, Quantifier matches) { + this(name, null, null, matches, null, null); } /** @@ -138,11 +273,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param name Member name, must not be null * @param owner Member owner, can be null otherwise must be in internal form * without L; - * @param matchAll true if this info should match all matching references, - * or only the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, boolean matchAll) { - this(name, owner, null, matchAll); + public MemberInfo(String name, String owner, Quantifier matches) { + this(name, owner, null, matches, null, null); } /** @@ -154,7 +288,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param desc Member descriptor, can be null */ public MemberInfo(String name, String owner, String desc) { - this(name, owner, desc, false); + this(name, owner, desc, Quantifier.DEFAULT, null, null); } /** @@ -164,10 +298,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, String desc, boolean matchAll) { - this(name, owner, desc, matchAll, null); + public MemberInfo(String name, String owner, String desc, Quantifier matches) { + this(name, owner, desc, matches, null, null); } /** @@ -177,9 +311,22 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, String desc, boolean matchAll, String unparsed) { + public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail) { + this(name, owner, desc, matches, tail, null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail, String input) { if (owner != null && owner.contains(".")) { throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format"); } @@ -187,9 +334,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = name; this.desc = desc; - this.matchAll = matchAll; + this.matches = matches; this.forceField = false; - this.unparsed = unparsed; + this.tail = tail; + this.input = input; } /** @@ -199,9 +347,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param insn instruction node to copy values from */ public MemberInfo(AbstractInsnNode insn) { - this.matchAll = false; + this.matches = Quantifier.DEFAULT; this.forceField = false; - this.unparsed = null; + this.input = null; + this.tail = null; if (insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; @@ -227,9 +376,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = mapping.getOwner(); this.name = mapping.getSimpleName(); this.desc = mapping.getDesc(); - this.matchAll = false; + this.matches = Quantifier.SINGLE; this.forceField = mapping.getType() == IMapping.Type.FIELD; - this.unparsed = null; + this.tail = null; + this.input = null; } /** @@ -241,9 +391,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = setOwner ? method.getOwner() : remapped.owner; this.name = method.getSimpleName(); this.desc = method.getDesc(); - this.matchAll = remapped.matchAll; + this.matches = remapped.matches; this.forceField = false; - this.unparsed = null; + this.tail = null; + this.input = null; } /** @@ -256,14 +407,15 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = original.name; this.desc = original.desc; - this.matchAll = original.matchAll; + this.matches = original.matches; this.forceField = original.forceField; - this.unparsed = null; + this.tail = original.tail; + this.input = null; } @Override public ITargetSelector next() { - return null; // Not supported yet + return Strings.isNullOrEmpty(this.tail) ? null : MemberInfo.parse(this.tail, null); } @Override @@ -282,8 +434,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } @Override - public int getMatchCount() { - return this.matchAll ? Integer.MAX_VALUE : 1; + public int getMinMatchCount() { + return this.matches.getClampedMin(); + } + + @Override + public int getMaxMatchCount() { + return this.matches.getClampedMax(); } /* (non-Javadoc) @@ -293,12 +450,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec public String toString() { String owner = this.owner != null ? "L" + this.owner + ";" : ""; String name = this.name != null ? this.name : ""; - String qualifier = this.matchAll ? "*" : ""; + String quantifier = this.matches.toString(); String desc = this.desc != null ? this.desc : ""; String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : ""); - return owner + name + qualifier + separator + desc; + String tail = this.tail != null ? " " + MemberInfo.ARROW + " " + this.tail : ""; + return owner + name + quantifier + separator + desc + tail; } - + /** * Return this MemberInfo as an SRG mapping * @@ -335,7 +493,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ @Override public String toCtorType() { - if (this.unparsed == null) { + if (this.input == null) { return null; } @@ -352,7 +510,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec return this.name; } - return this.desc != null ? this.desc : this.unparsed; + return this.desc != null ? this.desc : this.input; } /** @@ -471,52 +629,74 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * * @return fluent * - * @throws InvalidMemberDescriptorException if any validation check fails + * @throws InvalidSelectorException if any validation check fails */ @Override - public MemberInfo validate() throws InvalidMemberDescriptorException { + public MemberInfo validate() throws InvalidSelectorException { + // Parse emits a match count of 0 if the quantifier is incorrectly specified + if (this.getMaxMatchCount() == 0) { + throw new InvalidMemberDescriptorException(this.input, "Malformed quantifier in selector: " + this.input); + } + // Extremely naive class name validation, just to spot really egregious errors if (this.owner != null) { if (!this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) { - throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner); + throw new InvalidMemberDescriptorException(this.input, "Invalid owner: " + this.owner); } // We can't detect this situation 100% reliably, but we can take a // decent stab at it in order to detect really obvious cases where // the user types a dot instead of a semicolon - if (this.unparsed != null && this.unparsed.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { - throw new InvalidMemberDescriptorException("Malformed owner: " + this.owner + " If you are seeing this message unexpectedly and the" - + " owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + "; to suppress this error"); + if (this.input != null && this.input.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { + throw new InvalidMemberDescriptorException(this.input, "Malformed owner: " + this.owner + " If you are seeing this message" + + "unexpectedly and the owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + + "; to suppress this error"); } } // Also naive validation, we're looking for stupid errors here if (this.name != null && !this.name.matches("(?i)^?$")) { - throw new InvalidMemberDescriptorException("Invalid name: " + this.name); + throw new InvalidMemberDescriptorException(this.input, "Invalid name: " + this.name); } if (this.desc != null) { if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[*[\\w\\p{Sc}/;]+$")) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } if (this.isField()) { if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid field type in descriptor: " + this.desc); } } else { try { - Type.getArgumentTypes(this.desc); + // getArgumentTypes can choke on some invalid descriptors + Type[] argTypes = Type.getArgumentTypes(this.desc); + // getInternalName is a useful litmus test for improperly-formatted types which parse out of + // the descriptor correctly but are actually invalid, for example unterminated class names. + // However it doesn't support primitive types properly in ASM versions before 6 so don't run + // the test unless running ASM 6 or later + if (ASM.isAtLeastVersion(6)) { + for (Type argType : argTypes) { + argType.getInternalName(); + } + } } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } String retString = this.desc.substring(this.desc.indexOf(')') + 1); try { Type retType = Type.getType(retString); + int sort = retType.getSort(); + if (sort >= Type.ARRAY) { + retType.getInternalName(); // sanity check + } if (!retString.equals(retType.getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } } @@ -530,23 +710,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ @Override public MatchResult match(ElementNode node) { - return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #matches(org.objectweb.asm.tree.AbstractInsnNode) - */ - @Override - public MatchResult match(AbstractInsnNode insn) { - if (insn instanceof MethodInsnNode) { - MethodInsnNode method = (MethodInsnNode)insn; - return this.matches(method.owner, method.name, method.desc); - } else if (insn instanceof FieldInsnNode) { - FieldInsnNode field = (FieldInsnNode)insn; - return this.matches(field.owner, field.name, field.desc); - } - return MatchResult.NONE; + return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc()); } /* (non-Javadoc) @@ -583,46 +747,68 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } ITargetSelectorByName other = (ITargetSelectorByName)obj; - boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField : other.isField(); - boolean otherMatchAll = other.getMatchCount() == Integer.MAX_VALUE; + boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField + : other instanceof ITargetSelectorRemappable ? ((ITargetSelectorRemappable)other).isField() : false; - return this.matchAll == otherMatchAll && this.forceField == otherForceField + return this.compareMatches(other) && this.forceField == otherForceField && Objects.equal(this.owner, other.getOwner()) && Objects.equal(this.name, other.getName()) && Objects.equal(this.desc, other.getDesc()); } + /** + * Compare local match count with match count of other selector + */ + private boolean compareMatches(ITargetSelectorByName other) { + if (other instanceof MemberInfo) { + return ((MemberInfo)other).matches.equals(this.matches); + } + return this.getMinMatchCount() == other.getMinMatchCount() && this.getMaxMatchCount() == other.getMaxMatchCount(); + } + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { - return Objects.hashCode(this.matchAll, this.owner, this.name, this.desc); + return Objects.hashCode(this.matches, this.owner, this.name, this.desc); } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #configure(java.lang.String[]) + * #mutate(java.lang.String[]) */ @Override - public ITargetSelector configure(String... args) { - ITargetSelectorRemappable configured = this; - for (String arg : args) { - if (arg == null) { - continue; - } - - if (arg.startsWith("move:")) { - configured = configured.move(Strings.emptyToNull(arg.substring(5))); - } else if (arg.startsWith("transform:")) { - configured = configured.transform(Strings.emptyToNull(arg.substring(10))); - } else if ("permissive".equals(arg)) { - configured = configured.transform(null); - } else if ("orphan".equals(arg)) { - configured = configured.move(null); - } + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); + switch (request) { + case SELECT_MEMBER: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE, this.tail); + } + break; + case SELECT_INSTRUCTION: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail); + } + break; + case MOVE: + return this.move(Strings.emptyToNull(args[0])); + case ORPHAN: + return this.move(null); + case TRANSFORM: + return this.transform(Strings.emptyToNull(args[0])); + case PERMISSIVE: + return this.transform(null); + case CLEAR_LIMITS: + if (this.matches.getMin() != 0 || this.matches.getMax() < Integer.MAX_VALUE) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail); + } + break; + default: + break; } - return configured; + return this; } /* (non-Javadoc) @@ -630,8 +816,8 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * #attach(org.spongepowered.asm.mixin.refmap.IMixinContext) */ @Override - public ITargetSelector attach(IMixinContext context) throws InvalidSelectorException { - if (this.owner != null && !this.owner.equals(context.getTargetClassRef())) { + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + if (this.owner != null && !this.owner.equals(context.getMixin().getTargetClassRef())) { throw new TargetNotSupportedException(this.owner); } return this; @@ -660,7 +846,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec if ((newDesc == null && this.desc == null) || (newDesc != null && newDesc.equals(this.desc))) { return this; } - return new MemberInfo(this.name, this.owner, newDesc, this.matchAll); + return new MemberInfo(this.name, this.owner, newDesc, this.matches); } /** @@ -679,17 +865,23 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * Parse a MemberInfo from a string * * @param input String to parse MemberInfo from - * @param refMapper Reference mapper to use - * @param className Class context to use for remapping + * @param context Selector context for this parse request * @return parsed MemberInfo */ - public static MemberInfo parse(String input, IReferenceMapper refMapper, String className) { + public static MemberInfo parse(final String input, final ISelectorContext context) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); + String tail = null; + + int arrowPos = name.indexOf(MemberInfo.ARROW); + if (arrowPos > -1) { + tail = name.substring(arrowPos + 2); + name = name.substring(0, arrowPos); + } - if (refMapper != null) { - name = refMapper.remap(className, name); + if (context != null) { + name = context.remap(name); } int lastDotPos = name.lastIndexOf('.'); @@ -717,16 +909,40 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec name = ""; } - boolean matchAll = name.endsWith("*"); - if (matchAll) { + // Use default quantifier with negative max value. Used to indicate that + // an explicit quantifier was not parsed from the selector string, this + // allows us to provide backward-compatible behaviour for injection + // points vs. selecting target members which have different default + // semantics when omitting the quantifier. This is handled by consumers + // calling configure() with SELECT_MEMBER or SELECT_INSTRUCTION to + // promote the default case to a concrete case. + Quantifier quantifier = Quantifier.DEFAULT; + if (name.endsWith("*")) { + quantifier = Quantifier.ANY; name = name.substring(0, name.length() - 1); + } else if (name.endsWith("+")) { + quantifier = Quantifier.PLUS; + name = name.substring(0, name.length() - 1); + } else if (name.endsWith("}")) { + quantifier = Quantifier.NONE; // Assume invalid until quantifier is parsed + int bracePos = name.indexOf("{"); + if (bracePos >= 0) { + try { + quantifier = Quantifier.parse(name.substring(bracePos, name.length())); + name = name.substring(0, bracePos); + } catch (Exception ex) { + // Handled later in validate since matchCount will be 0 + } + } + } else if (name.indexOf("{") >= 0) { + quantifier = Quantifier.NONE; // Probably incomplete quantifier } if (name.isEmpty()) { name = null; } - return new MemberInfo(name, owner, desc, matchAll, input); + return new MemberInfo(name, owner, desc, quantifier, tail, input); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java index 818b76ef..ad184f18 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -70,7 +70,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo { Type returnType = Type.getReturnType(this.method.desc); for (AnnotationNode at : ats) { - this.injectionPoints.add(new BeforeConstant(this.getContext(), at, returnType.getDescriptor())); + this.injectionPoints.add(new BeforeConstant(this.getMixin(), at, returnType.getDescriptor())); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java new file mode 100644 index 00000000..605d0b08 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java @@ -0,0 +1,131 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + +/** + * Narrowed context for selectors in annotations which are themselves inside + * a parent annotation, for example @At annotations within a parent + * @Inject annotation. + */ +public class SelectorAnnotationContext implements ISelectorContext { + + /** + * The selector context of the parent, eg. the @Inject context + */ + private final ISelectorContext parent; + + /** + * The annotation for this selector + */ + private final IAnnotationHandle selectorAnnotation; + + /** + * The coordinate for this selector + */ + private final String selectorCoordinate; + + /** + * Create a specialised context for a child annotation + * + * @param parent Parent selector context, eg. context of the outer element + * such as @Inject + * @param selectorAnnotation Annotation for this selector, eg. @At + * @param selectorCoordinate Coordinate for this selector + */ + public SelectorAnnotationContext(ISelectorContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) { + this.parent = parent; + this.selectorAnnotation = selectorAnnotation; + this.selectorCoordinate = selectorCoordinate; + } + + /** + * Get the parent of this selector, must not return null + * + * @return parent context + */ + @Override + public ISelectorContext getParent() { + return this.parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMixin() + */ + @Override + public IMixinContext getMixin() { + return this.parent.getMixin(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMethod() + */ + @Override + public Object getMethod() { + return this.parent.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getAnnotation() + */ + @Override + public IAnnotationHandle getAnnotation() { + return this.parent.getAnnotation(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorAnnotation() + */ + @Override + public IAnnotationHandle getSelectorAnnotation() { + return this.selectorAnnotation; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorCoordinate() + */ + @Override + public String getSelectorCoordinate(boolean leaf) { + return this.selectorCoordinate; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #remap(java.lang.String) + */ + @Override + public String remap(String reference) { + return this.parent.remap(reference); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java index aa1b27e9..971a8d59 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; @@ -45,6 +44,7 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.Locals.SyntheticLocalVariableNode; /** * Information about the current injection target, mainly just convenience @@ -751,13 +751,7 @@ public class Target implements Comparable, Iterable { * @param desc local variable type */ public void addLocalVariable(int index, String name, String desc) { - if (this.start == null) { - this.start = new LabelNode(new Label()); - this.end = new LabelNode(new Label()); - this.insns.insert(this.start); - this.insns.add(this.end); - } - this.addLocalVariable(index, name, desc, this.start, this.end); + this.addLocalVariable(index, name, desc, null, null); } /** @@ -766,14 +760,50 @@ public class Target implements Comparable, Iterable { * @param index local variable index * @param name local variable name * @param desc local variable type - * @param start start of range - * @param end end of range + * @param from start of range + * @param to end of range */ - private void addLocalVariable(int index, String name, String desc, LabelNode start, LabelNode end) { + public void addLocalVariable(int index, String name, String desc, LabelNode from, LabelNode to) { + if (from == null) { + from = this.getStartLabel(); + } + + if (to == null) { + to = this.getEndLabel(); + } + if (this.method.localVariables == null) { this.method.localVariables = new ArrayList(); } - this.method.localVariables.add(new LocalVariableNode(name, desc, null, start, end, index)); + + for (Iterator iter = this.method.localVariables.iterator(); iter.hasNext();) { + LocalVariableNode local = iter.next(); + if (local != null && local.index == index && from == local.start && to == local.end) { + iter.remove(); + } + } + + this.method.localVariables.add(new SyntheticLocalVariableNode(name, desc, null, from, to, index)); } - + + /** + * Get a label which marks the very start of the method + */ + private LabelNode getStartLabel() { + if (this.start == null) { + this.insns.insert(this.start = new LabelNode()); + } + return this.start; + } + + /** + * Get a label which marks the very end of the method + */ + private LabelNode getEndLabel() { + if (this.end == null) { + this.insns.add(this.end = new LabelNode()); + } + return this.end; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java new file mode 100644 index 00000000..e4138056 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal data bundles used by injectors during application. + */ +package org.spongepowered.asm.mixin.injection.struct; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java index b80ddb07..5131e261 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java @@ -50,12 +50,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message) { - super(info.getContext(), message); + super(info.getMixin(), message); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) { - super(info.getContext(), message, activityContext); + super(info.getMixin(), message, activityContext); this.info = info; } @@ -70,12 +70,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, Throwable cause) { - super(info.getContext(), cause); + super(info.getMixin(), cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), cause, activityContext); + super(info.getMixin(), cause, activityContext); this.info = info; } @@ -90,12 +90,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) { - super(info.getContext(), message, cause); + super(info.getMixin(), message, cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), message, cause, activityContext); + super(info.getMixin(), message, cause, activityContext); this.info = info; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java index 85eae4d2..2fe9e2ac 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java @@ -40,7 +40,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message) { - super(owner.getContext(), message); + super(owner.getMixin(), message); } public InvalidSliceException(IMixinContext context, Throwable cause) { @@ -48,7 +48,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, Throwable cause) { - super(owner.getContext(), cause); + super(owner.getMixin(), cause); } public InvalidSliceException(IMixinContext context, String message, Throwable cause) { @@ -56,7 +56,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message, Throwable cause) { - super(owner.getContext(), message, cause); + super(owner.getMixin(), message, cause); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java new file mode 100644 index 00000000..a1a3d686 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Throwable classes (errors and exceptions) for injectors. + */ +package org.spongepowered.asm.mixin.injection.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/package-info.java b/src/main/java/org/spongepowered/asm/mixin/package-info.java new file mode 100644 index 00000000..08b2b9c2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/package-info.java @@ -0,0 +1,34 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Primary interaction points ( + * {@link org.spongepowered.asm.mixin.Mixin @Mixin} and + * {@link org.spongepowered.asm.mixin.MixinEnvironment @MixinEnvironment}) + * and annotations (eg. + * {@link org.spongepowered.asm.mixin.Mixin @Mixin}, + * {@link org.spongepowered.asm.mixin.Shadow @Shadow}) for mixin consumers. + */ +package org.spongepowered.asm.mixin; diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java index fd12eddb..22ed77d1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java @@ -24,10 +24,8 @@ */ package org.spongepowered.asm.mixin.refmap; -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.injection.struct.Target; import org.spongepowered.asm.mixin.transformer.ext.Extensions; /** @@ -87,14 +85,4 @@ public interface IMixinContext { */ public abstract int getPriority(); - /** - * Obtain a {@link Target} method handle for a method in the target, this is - * used by consumers to manipulate the bytecode in a target method in a - * controlled manner. - * - * @param method method node to wrap - * @return target method - */ - public abstract Target getTargetMethod(MethodNode method); - } diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java index b745dde7..a031f024 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -243,7 +243,7 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { * @param writer Writer to write to */ public void write(Appendable writer) { - new GsonBuilder().setPrettyPrinting().create().toJson(this, writer); + new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(this, writer); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java index d2ae66f7..f699c77f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/RemappingReferenceMapper.java @@ -150,9 +150,9 @@ public final class RemappingReferenceMapper implements IClassReferenceMapper, IR // To handle propagation, find super/itf-class (for IRemapper) // but pass the requested class in the MemberInfo - MemberInfo info = MemberInfo.parse(remapped, null, null); + MemberInfo info = MemberInfo.parse(remapped, null); if (info.getName() == null && info.getDesc() == null) { - return info.getOwner() != null ? new MemberInfo(remapper.map(info.getOwner()), null, null).toString() : info.toString(); + return info.getOwner() != null ? new MemberInfo(remapper.map(info.getOwner()), null).toString() : info.toString(); } else if (info.isField()) { remapped = new MemberInfo( remapper.mapFieldName(info.getOwner(), info.getName(), info.getDesc()), diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java b/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java new file mode 100644 index 00000000..19669c41 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Refmaps are data bundles which map string references to obfuscated + * counterparts at runtime, see {@link + * org.spongepowered.asm.mixin.refmap.ReferenceMapper}. + */ +package org.spongepowered.asm.mixin.refmap; diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index 3fac92c6..4fb3c7fd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -24,24 +24,26 @@ */ package org.spongepowered.asm.mixin.struct; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.util.Locale; + +import javax.tools.Diagnostic.Kind; + import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.IReferenceMapper; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.asm.IAnnotationHandle; +import org.spongepowered.asm.util.logging.MessageRouter; /** * Data bundle for an annotated method in a mixin */ public class AnnotatedMethodInfo implements IInjectionPointContext { - /** - * Log more things - */ - protected static final Logger logger = LogManager.getLogger("mixin"); - /** * Mixin context */ @@ -62,6 +64,24 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { this.method = method; this.annotation = annotation; } + + @Override + public String remap(String reference) { + if (this.context != null) { + IReferenceMapper referenceMapper = this.context.getReferenceMapper(); + return referenceMapper != null ? referenceMapper.remap(this.context.getClassRef(), reference) : reference; + } + return reference; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getParent() + */ + @Override + public ISelectorContext getParent() { + return null; + } /** * Get the mixin target context for this annotated method @@ -69,7 +89,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return the target context */ @Override - public final IMixinContext getContext() { + public final IMixinContext getMixin() { return this.context; } @@ -82,16 +102,52 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { public final MethodNode getMethod() { return this.method; } - + /** - * Get the annotation which this InjectionInfo was created from - * - * @return The annotation which this InjectionInfo was created from + * Get the original name of the method, if available + */ + public String getMethodName() { + return this.method.name; + } + + /** + * Get the primary annotation which makes this method special */ @Override - public final AnnotationNode getAnnotation() { + public AnnotationNode getAnnotationNode() { return this.annotation; } + + /** + * Get the primary annotation which makes this method special + * + * @return The primary method annotation + */ + @Override + public final IAnnotationHandle getAnnotation() { + return Annotations.handleOf(this.annotation); + } + + /** + * Get the annotation context for selectors operating in the context of this + * method. + * + * @return The selector context annotation + */ + @Override + public IAnnotationHandle getSelectorAnnotation() { + return Annotations.handleOf(this.annotation); + } + + /** + * Get the selector coordinate for this method + * + * @return The selector context annotation + */ + @Override + public String getSelectorCoordinate(boolean leaf) { + return leaf ? "method" : this.getMethodName().toLowerCase(Locale.ROOT); + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.IInjectionPointContext @@ -100,7 +156,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { @Override public void addMessage(String format, Object... args) { if (this.context.getOption(Option.DEBUG_VERBOSE)) { - AnnotatedMethodInfo.logger.warn(String.format(format, args)); + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format(format, args)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java index 5d3a6344..985cec01 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java @@ -30,12 +30,13 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Handles; /** * Reference to a field or method that also includes invocation instructions. * - *

To instances are defined to be equal if they both refer to the same method - * and have the same invocation instructions.

+ *

Two instances are defined to be equal if they both refer to the same + * member and have the same invocation instructions.

*/ public abstract class MemberRef { @@ -210,26 +211,12 @@ public abstract class MemberRef { @Override public boolean isField() { - switch (this.handle.getTag()) { - case Opcodes.H_INVOKEVIRTUAL: - case Opcodes.H_INVOKESTATIC: - case Opcodes.H_INVOKEINTERFACE: - case Opcodes.H_INVOKESPECIAL: - case Opcodes.H_NEWINVOKESPECIAL: - return false; - case Opcodes.H_GETFIELD: - case Opcodes.H_GETSTATIC: - case Opcodes.H_PUTFIELD: - case Opcodes.H_PUTSTATIC: - return true; - default: - throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); - } + return Handles.isField(this.handle); } @Override public int getOpcode() { - int opcode = MemberRef.opcodeFromTag(this.handle.getTag()); + int opcode = Handles.opcodeFromTag(this.handle.getTag()); if (opcode == 0) { throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); } @@ -238,12 +225,11 @@ public abstract class MemberRef { @Override public void setOpcode(int opcode) { - int tag = MemberRef.tagFromOpcode(opcode); + int tag = Handles.tagFromOpcode(opcode); if (tag == 0) { throw new MixinTransformerError("Invalid opcode " + Bytecode.getOpcodeName(opcode) + " for method handle " + this.handle + "."); } - boolean itf = this.handle.isInterface(); - this.handle = new org.objectweb.asm.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), itf); + this.setHandle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -253,9 +239,7 @@ public abstract class MemberRef { @Override public void setOwner(String owner) { - boolean itf = this.handle.isInterface(); - assert ClassInfo.forName(owner).isInterface() == itf; - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), itf); + this.setHandle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -265,8 +249,7 @@ public abstract class MemberRef { @Override public void setName(String name) { - boolean itf = this.handle.isInterface(); - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), itf); + this.setHandle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), this.handle.isInterface()); } @Override @@ -276,23 +259,14 @@ public abstract class MemberRef { @Override public void setDesc(String desc) { - boolean itf = this.handle.isInterface(); - this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, itf); + this.setHandle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, this.handle.isInterface()); } + + public void setHandle(int tag, String owner, String name, String desc, boolean isInterface) { + this.handle = new org.objectweb.asm.Handle(tag, owner, name, desc, isInterface); + } + } - - private static final int[] H_OPCODES = { - 0, // invalid - Opcodes.GETFIELD, // H_GETFIELD - Opcodes.GETSTATIC, // H_GETSTATIC - Opcodes.PUTFIELD, // H_PUTFIELD - Opcodes.PUTSTATIC, // H_PUTSTATIC - Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL - Opcodes.INVOKESTATIC, // H_INVOKESTATIC - Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL - Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL - Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE - }; /** * Whether this member is a field. @@ -359,8 +333,8 @@ public abstract class MemberRef { @Override public String toString() { - String name = Bytecode.getOpcodeName(this.getOpcode()); - return String.format("%s for %s.%s%s%s", name, this.getOwner(), this.getName(), this.isField() ? ":" : "", this.getDesc()); + return String.format("%s for %s.%s%s%s", Bytecode.getOpcodeName(this.getOpcode()), this.getOwner(), this.getName(), this.isField() ? ":" : "", + this.getDesc()); } @Override @@ -381,17 +355,4 @@ public abstract class MemberRef { return this.toString().hashCode(); } - static int opcodeFromTag(int tag) { - return (tag >= 0 && tag < MemberRef.H_OPCODES.length) ? MemberRef.H_OPCODES[tag] : 0; - } - - static int tagFromOpcode(int opcode) { - for (int tag = 1; tag < MemberRef.H_OPCODES.length; tag++) { - if (MemberRef.H_OPCODES[tag] == opcode) { - return tag; - } - } - return 0; - } - } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java index 09344f69..d509a898 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -29,7 +29,7 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; -import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.asm.MethodNodeEx; /** @@ -60,7 +60,7 @@ public class SpecialMethodInfo extends AnnotatedMethodInfo { public SpecialMethodInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { super(mixin, method, annotation); this.mixin = mixin; - this.annotationType = this.annotation != null ? "@" + Bytecode.getSimpleName(this.annotation) : "Undecorated injector"; + this.annotationType = this.annotation != null ? "@" + Annotations.getSimpleName(this.annotation) : "Undecorated injector"; this.classNode = mixin.getTargetClassNode(); this.methodName = MethodNodeEx.getName(method); } @@ -84,6 +84,7 @@ public class SpecialMethodInfo extends AnnotatedMethodInfo { /** * Get the original name of the method, if available */ + @Override public String getMethodName() { return this.methodName; } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java b/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java new file mode 100644 index 00000000..ec338bc3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/struct/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal data bundles used by mixin during application. + */ +package org.spongepowered.asm.mixin.struct; diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java new file mode 100644 index 00000000..aa5cc880 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin throwables and throwable base classes. + */ +package org.spongepowered.asm.mixin.throwables; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index b8556ff5..6c771cf6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -49,7 +49,6 @@ import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; @@ -58,6 +57,7 @@ import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.ClassSignature; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; @@ -112,9 +112,9 @@ public final class ClassInfo { } /** - * When using {@link ClassInfo#forType}, determines whether an array type - * should be returned as declared (eg. as Object) or whether the - * element type should be returned instead. + * When using {@link ClassInfo#forType ClassInfo.forType}, determines + * whether an array type should be returned as declared (eg. as Object + * ) or whether the element type should be returned instead. */ public static enum TypeLookup { @@ -248,10 +248,11 @@ public final class ClassInfo { */ @Override public String toString() { - return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); + return String.format("FrameData[index=%d, type=%s, locals=%d size=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals, + this.size); } } - + /** * Information about a member in this class */ @@ -974,7 +975,7 @@ public final class ClassInfo { return this.name; } - public MethodMapper getMethodMapper() { + MethodMapper getMethodMapper() { return this.methodMapper; } @@ -1143,6 +1144,47 @@ public final class ClassInfo { return this.getSuperClass(); } + /** + * Test whether this class has the specified superclass in its hierarchy + * + * @param superClass Superclass to search for in the hierarchy + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(Class superClass) { + return this.hasSuperClass(superClass, Traversal.NONE, superClass.isInterface()); + } + + /** + * Test whether this class has the specified superclass in its hierarchy + * + * @param superClass Superclass to search for in the hierarchy + * @param traversal Traversal type to allow during this lookup + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(Class superClass, Traversal traversal) { + return this.hasSuperClass(superClass, traversal, superClass.isInterface()); + } + + /** + * Test whether this class has the specified superclass in its hierarchy + * + * @param superClass Superclass to search for in the hierarchy + * @param traversal Traversal type to allow during this lookup + * @param includeInterfaces True to include interfaces in the lookup + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(Class superClass, Traversal traversal, boolean includeInterfaces) { + String internalName = org.objectweb.asm.Type.getInternalName(superClass); + if (ClassInfo.JAVA_LANG_OBJECT.equals(internalName)) { + return true; + } + + return this.findSuperClass(internalName, traversal) != null; + } + /** * Test whether this class has the specified superclass in its hierarchy * @@ -1151,7 +1193,7 @@ public final class ClassInfo { * anywhere */ public boolean hasSuperClass(String superClass) { - return this.hasSuperClass(superClass, Traversal.NONE); + return this.hasSuperClass(superClass, Traversal.NONE, false); } /** @@ -1163,10 +1205,23 @@ public final class ClassInfo { * anywhere */ public boolean hasSuperClass(String superClass, Traversal traversal) { + return this.hasSuperClass(superClass, traversal, false); + } + + /** + * Test whether this class has the specified superclass in its hierarchy + * + * @param superClass Name of the superclass to search for in the hierarchy + * @param traversal Traversal type to allow during this lookup + * @param includeInterfaces True to include interfaces in the lookup + * @return true if the specified class appears in the class's hierarchy + * anywhere + */ + public boolean hasSuperClass(String superClass, Traversal traversal, boolean includeInterfaces) { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } - + return this.findSuperClass(superClass, traversal) != null; } @@ -1649,7 +1704,7 @@ public final class ClassInfo { } } - if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES))) { + if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES))) { for (String implemented : this.interfaces) { ClassInfo iface = ClassInfo.forName(implemented); if (iface == null) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java index 183190c7..769ab93f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java @@ -52,6 +52,20 @@ public interface IMixinTransformer { */ public abstract List reload(String mixinClass, ClassNode classNode); + /** + * Called when the transformation reason is computing_frames. The only + * operation we care about here is adding interfaces to target classes but + * at the moment we don't have sufficient scaffolding to determine that + * without triggering re-entrance. Currently just a no-op in order to not + * cause a re-entrance crash under ModLauncher 7.0+. + * + * @param environment Current environment + * @param name Class transformed name + * @param classNode Class tree + * @return true if the class was transformed + */ + public abstract boolean computeFramesForClass(MixinEnvironment environment, String name, ClassNode classNode); + /** * Callback from the hotswap agent and LaunchWrapper Proxy, transform class * bytecode. This method delegates to class generation or class @@ -67,6 +81,43 @@ public interface IMixinTransformer { * @see ILegacyClassTransformer#transformClassBytes(String, String, byte[]) */ public abstract byte[] transformClassBytes(String name, String transformedName, byte[] basicClass); + + /** + * Apply mixins and postprocessors to the supplied class + * + * @param environment Current environment + * @param name Class transformed name + * @param classBytes Class bytecode + * @return Transformed bytecode + */ + public abstract byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes); + + /** + * Apply mixins and postprocessors to the supplied class + * + * @param environment Current environment + * @param name Class transformed name + * @param classNode Class tree + * @return true if the class was transformed + */ + public abstract boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode); + + /** + * Generate the specified mixin-synthetic class + * + * @param environment Current environment + * @param name Class name to generate + * @return Generated bytecode or null if no class was generated + */ + public abstract byte[] generateClass(MixinEnvironment environment, String name); + + /** + * @param environment Current environment + * @param name Class transformed name + * @param classNode Empty classnode to populate + * @return True if the class was generated successfully + */ + public abstract boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode); /** * Get the transformer extensions diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java new file mode 100644 index 00000000..7e3b10ed --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerFactory.java @@ -0,0 +1,42 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.launch.MixinInitialisationError; +import org.spongepowered.asm.service.IMixinInternal; + +/** + * Factory for the mixin transformer, concrete instances of this class are only + * provided to services since only the service should be able to decide when the + * mixin transformer is initialised. + */ +public interface IMixinTransformerFactory extends IMixinInternal { + + /** + * Create a new transformer. + */ + public abstract IMixinTransformer createTransformer() throws MixinInitialisationError; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java index 5e567f3f..2ff9d94e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -42,7 +42,7 @@ import org.spongepowered.asm.util.Annotations; * Information about an interface being runtime-patched onto a mixin target * class, see {@link org.spongepowered.asm.mixin.Implements Implements} */ -public final class InterfaceInfo { +final class InterfaceInfo { /** * Parent mixin diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java index 55baab6d..1e298a57 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java @@ -44,7 +44,7 @@ import com.google.common.base.Strings; /** * Maintains method remaps for a target class */ -public class MethodMapper { +class MethodMapper { /** * Logger diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java index fe73a5eb..4304a651 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java @@ -30,11 +30,11 @@ import java.util.Map.Entry; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException; +import org.spongepowered.asm.util.LanguageFeatures; /** * Applicator for interface mixins, mainly just disables things which aren't @@ -104,7 +104,7 @@ class MixinApplicatorInterface extends MixinApplicatorStandard { InjectionInfo injectInfo = InjectionInfo.parse(mixin, method); if (injectInfo != null) { //Make sure we're running on a Java version which supports interfaces having method bodies - if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { throw new InvalidInterfaceMixinException(mixin, injectInfo + " is not supported on interface mixin method " + method.name); } } @@ -120,7 +120,7 @@ class MixinApplicatorInterface extends MixinApplicatorStandard { @Override protected void checkMethodVisibility(MixinTargetContext mixin, MethodNode mixinMethod) { //Allow injecting into static interface methods where it isn't possible to control the access of the injection method - if (Modifier.isStatic(mixinMethod.access) && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.PRIVATE_METHODS_IN_INTERFACES)) { + if (Modifier.isStatic(mixinMethod.access) && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES)) { InjectionInfo injectInfo = InjectionInfo.parse(mixin, mixinMethod); if (injectInfo != null) { return; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 9f43be95..dd2ef0e1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -64,6 +64,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.ConstraintParser; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.ConstraintParser.Constraint; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; @@ -381,6 +382,8 @@ class MixinApplicatorStandard { this.applyMethods(mixin); activity.next("Apply Initialisers"); this.applyInitialisers(mixin); + activity.next("Apply Nesting"); + this.applyNesting(mixin); break; case PREINJECT: @@ -431,7 +434,11 @@ class MixinApplicatorStandard { if (mixin.shouldSetSourceFile()) { this.targetClass.sourceFile = mixin.getSourceFile(); } - this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion()); + + int requiredVersion = mixin.getMinRequiredClassVersion(); + if ((requiredVersion & 0xFFFF) > (this.targetClass.version & 0xFFFF)) { + this.targetClass.version = requiredVersion; + } } /** @@ -636,7 +643,7 @@ class MixinApplicatorStandard { return true; } throw new InvalidMixinException(mixin, String.format("Incompatible @%s %s (for %s) in %s previously written by %s (for %s)", - Bytecode.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget)); + Annotations.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget)); } } @@ -1023,6 +1030,30 @@ class MixinApplicatorStandard { private static String fieldKey(FieldInsnNode fieldNode) { return String.format("%s:%s", fieldNode.desc, fieldNode.name); } + + /** + * Apply nesting attributes from the mixin to the target. + * + *

NOT YET SUPPORTED!

+ */ + protected void applyNesting(MixinTargetContext mixin) { + + String nestHostClass = mixin.getNestHostClass(); + List nestMembers = mixin.getNestMembers(); + if ((nestHostClass == null && nestMembers == null) || (nestMembers != null && nestMembers.size() == 0)) { + return; + } + + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) { + // Shouldn't get here because we should error out during the initial scan, but you never know + throw new InvalidMixinException(mixin, + String.format("%s contains nesting information but the current compatibility level does not support class nesting attributes", + mixin)); + } + + // TODO Nesting not done yet, just log an error for now that we're not applying these attributes + this.logger.error("NESTING not supported in this version of Mixin. {} nesting attributes will not be applied to the target", mixin); + } /** * Scan for injector methods and injection points @@ -1140,7 +1171,7 @@ class MixinApplicatorStandard { */ protected final FieldNode findTargetField(FieldNode searchFor) { for (FieldNode target : this.targetClass.fields) { - if (target.name.equals(searchFor.name)) { + if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc)) { return target; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index 4b983d7e..3281808c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.transformer; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.Constructor; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -46,6 +47,8 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.refmap.IClassReferenceMapper; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; @@ -78,9 +81,15 @@ final class MixinConfig implements Comparable, IMixinConfig { @SerializedName("defaultGroup") String defaultGroup = "default"; + @SerializedName("namespace") + String namespace; + @SerializedName("injectionPoints") List injectionPoints; + @SerializedName("dynamicSelectors") + List dynamicSelectors; + @SerializedName("maxShiftBy") int maxShiftBy = InjectionPoint.DEFAULT_ALLOWED_SHIFT_BY; @@ -278,7 +287,19 @@ final class MixinConfig implements Comparable, IMixinConfig { */ @SerializedName("refmap") private String refMapperConfig; - + + /** + * The class name for an implementation of {@Link IReferenceMapper}, + * mixinPackage will be prepended. This allows for full control over the + * refmap for cases where you need more fine-grained control then the + * default remappers. + * + *

Must have a public constructor that takes {@Link MixinEnvironment} and + * {@Link IReferenceMapper} + */ + @SerializedName("refmapWrapper") + private String refMapperWrapper; + /** * True to output "mixing in" messages at INFO level rather than DEBUG */ @@ -461,7 +482,7 @@ final class MixinConfig implements Comparable, IMixinConfig { this.initialised = true; this.initCompatibilityLevel(); - this.initInjectionPoints(); + this.initExtensions(); return this.checkVersion(); } @@ -516,46 +537,68 @@ final class MixinConfig implements Comparable, IMixinConfig { return fallbackEnvironment; } - private void initInjectionPoints() { - if (this.injectorOptions.injectionPoints == null) { - return; + private void initExtensions() { + if (this.injectorOptions.injectionPoints != null) { + for (String injectionPointClassName : this.injectorOptions.injectionPoints) { + this.initInjectionPoint(injectionPointClassName, this.injectorOptions.namespace); + } } - - for (String injectionPointClassName : this.injectorOptions.injectionPoints) { - this.initInjectionPoint(injectionPointClassName); + + if (this.injectorOptions.dynamicSelectors != null) { + for (String dynamicSelectorClassName : this.injectorOptions.dynamicSelectors) { + this.initDynamicSelector(dynamicSelectorClassName, this.injectorOptions.namespace); + } } } @SuppressWarnings("unchecked") - public void initInjectionPoint(String className) { + private void initInjectionPoint(String className, String namespace) { try { - Class injectionPointClass = null; - try { - injectionPointClass = this.service.getClassProvider().findClass(className, true); - } catch (ClassNotFoundException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the specified class was not found", className, this, cnfe); - return; - } - - if (!InjectionPoint.class.isAssignableFrom(injectionPointClass)) { - this.logger.error("Unable to register injection point {} for {}, class must extend InjectionPoint", className, this); - return; - } - - try { - injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); - } catch (NoSuchMethodException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", - className, this, cnfe); - return; - } + Class injectionPointClass = this.findExtensionClass(className, InjectionPoint.class, "injection point"); + if (injectionPointClass != null) { + try { + injectionPointClass.getMethod("find", String.class, InsnList.class, Collection.class); + } catch (NoSuchMethodException cnfe) { + this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", + className, this, cnfe); + return; + } - InjectionPoint.register((Class)injectionPointClass); + InjectionPoint.register((Class)injectionPointClass, namespace); + } } catch (Throwable th) { this.logger.catching(th); } } + @SuppressWarnings("unchecked") + private void initDynamicSelector(String className, String namespace) { + try { + Class dynamicSelectorClass = this.findExtensionClass(className, ITargetSelectorDynamic.class, "dynamic selector"); + if (dynamicSelectorClass != null) { + TargetSelector.register((Class)dynamicSelectorClass, namespace); + } + } catch (Throwable th) { + this.logger.catching(th); + } + } + + private Class findExtensionClass(String className, Class superType, String extensionType) { + Class extensionClass = null; + try { + extensionClass = this.service.getClassProvider().findClass(className, true); + } catch (ClassNotFoundException cnfe) { + this.logger.error("Unable to register {} {} for {}, the specified class was not found", extensionType, className, this, cnfe); + return null; + } + + if (!superType.isAssignableFrom(extensionClass)) { + this.logger.error("Unable to register {} {} for {}, class is not assignable to {}", extensionType, className, this, superType); + return null; + } + return extensionClass; + } + private boolean checkVersion() throws MixinInitialisationError { if (this.version == null) { // If the parent is non-null, then the version check has already been @@ -624,6 +667,22 @@ final class MixinConfig implements Comparable, IMixinConfig { if (this.env.getOption(Option.REFMAP_REMAP)) { this.refMapper = RemappingReferenceMapper.of(this.env, this.refMapper); } + + if (this.refMapperWrapper != null) { + String wrapperName = this.mixinPackage + this.refMapperWrapper; + try { + @SuppressWarnings("unchecked") + Class wrapperCls = (Class) Class.forName(wrapperName); + Constructor ctr = wrapperCls.getConstructor(MixinEnvironment.class, IReferenceMapper.class); + this.refMapper = ctr.newInstance(this.env, this.refMapper); + } catch (ClassNotFoundException e) { + this.logger.error("Reference map wrapper '{}' could not be found: ", wrapperName, e); + } catch (ReflectiveOperationException e) { + this.logger.error("Reference map wrapper '{}' could not be created: ", wrapperName, e); + } catch (SecurityException e) { + this.logger.error("Reference map wrapper '{}' could not be created: ", wrapperName, e); + } + } } /** @@ -961,6 +1020,14 @@ final class MixinConfig implements Comparable, IMixinConfig { return this.plugin.get(); } + /** + * Returns a mutable view of the targets set, used to pass the targets to + * config plugins + */ + public Set getTargetsSet() { + return this.mixinMapping.keySet(); + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getTargets() */ @@ -983,6 +1050,13 @@ final class MixinConfig implements Comparable, IMixinConfig { return this.verboseLogging ? Level.INFO : Level.DEBUG; } + /** + * Get whether verbose logging is enabled + */ + public boolean isVerboseLogging() { + return this.verboseLogging; + } + /** * Get whether this config's package matches the supplied class name * diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index 81a20189..518a6486 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -51,7 +51,6 @@ import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.Overwrite; @@ -70,6 +69,7 @@ import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.LanguageFeatures; import org.spongepowered.asm.util.asm.ASM; import org.spongepowered.asm.util.asm.MethodNodeEx; import org.spongepowered.asm.util.CompareUtil; @@ -318,6 +318,7 @@ class MixinInfo implements Comparable, IMixinInfo { */ void validate(SubType type, List targetClasses) { MixinClassNode classNode = this.getValidationClassNode(); + MixinPreProcessorStandard preProcessor = type.createPreProcessor(classNode).prepare(); for (ClassInfo target : targetClasses) { preProcessor.conform(target); @@ -330,7 +331,7 @@ class MixinInfo implements Comparable, IMixinInfo { // Pre-flight checks this.validateInner(); - this.validateClassVersion(); + this.validateClassFeatures(); this.validateRemappables(targetClasses); // Read information from the mixin @@ -351,17 +352,19 @@ class MixinInfo implements Comparable, IMixinInfo { } } - private void validateClassVersion() { - if (this.validationClassNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) { - String helpText = "."; - for (CompatibilityLevel level : CompatibilityLevel.values()) { - if (level.classVersion() >= this.validationClassNode.version) { - helpText = String.format(". Mixin requires compatibility level %s or above.", level.name()); - } - } - - throw new InvalidMixinException(MixinInfo.this, "Unsupported mixin class version " + this.validationClassNode.version + helpText); + private void validateClassFeatures() { + CompatibilityLevel compatibilityLevel = MixinEnvironment.getCompatibilityLevel(); + int requiredLanguageFeatures = LanguageFeatures.scan(this.validationClassNode); + if (requiredLanguageFeatures == 0 || compatibilityLevel.supports(requiredLanguageFeatures)) { + return; } + + int missingFeatures = requiredLanguageFeatures & ~compatibilityLevel.getLanguageFeatures(); + CompatibilityLevel minRequiredLevel = CompatibilityLevel.requiredFor(requiredLanguageFeatures); + + throw new InvalidMixinException(MixinInfo.this, String.format( + "Unsupported mixin, %s requires the following unsupported language features: %s, these features require compatibility level %s", + MixinInfo.this, LanguageFeatures.format(missingFeatures), minRequiredLevel != null ? minRequiredLevel.toString() : "UNKNOWN")); } private void validateRemappables(List targetClasses) { @@ -428,7 +431,7 @@ class MixinInfo implements Comparable, IMixinInfo { || inner.name.startsWith(this.validationClassNode.name + "$")) { if (innerClass.isProbablyStatic() && innerClass.isSynthetic()) { this.syntheticInnerClasses.add(inner.name); - } else { + } else if (!innerClass.isMixin()) { this.innerClasses.add(inner.name); } } @@ -611,7 +614,7 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validate(State state, List targetClasses) { - if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Interface mixin not supported in current enviromnment"); } @@ -655,7 +658,7 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validateTarget(String targetName, ClassInfo targetInfo) { boolean targetIsInterface = targetInfo.isInterface(); - if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Accessor mixin targetting an interface is not supported in current enviromnment"); } } @@ -1010,23 +1013,23 @@ class MixinInfo implements Comparable, IMixinInfo { if (this.isVirtual()) { this.logger.debug("Skipping virtual target {} for {}", target.name, this); } else { - this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this), false); } return null; } this.type.validateTarget(target.name, targetInfo); if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) { - this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this), true); } return targetInfo; } - private void handleTargetError(String message) { + private void handleTargetError(String message, boolean verboseOnly) { if (this.strict) { this.logger.error(message); throw new InvalidMixinException(this, message); } - this.logger.warn(message); + this.logger.log(verboseOnly && !this.parent.isVerboseLogging() ? Level.DEBUG : Level.WARN, message); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index 4e9ff44b..68fcee4d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -38,7 +38,6 @@ import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; @@ -48,6 +47,8 @@ import org.spongepowered.asm.mixin.transformer.meta.MixinProxy; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Bytecode.Visibility; +import org.spongepowered.asm.util.LanguageFeatures; /** * Performs post-processing tasks required for certain classes which pass @@ -162,7 +163,7 @@ class MixinPostProcessor implements MixinConfig.IListener { } private boolean processAccessor(ClassNode classNode, MixinInfo mixin) { - if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) { return false; } @@ -170,6 +171,11 @@ class MixinPostProcessor implements MixinConfig.IListener { MixinClassNode mixinClassNode = mixin.getClassNode(0); ClassInfo targetClass = mixin.getTargets().get(0); + if (!Bytecode.hasFlag(mixinClassNode, Opcodes.ACC_PUBLIC)) { + Bytecode.setVisibility(mixinClassNode, Visibility.PUBLIC); + transformed = true; + } + for (MixinMethodNode methodNode : mixinClassNode.mixinMethods) { if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_STATIC)) { continue; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java index 5294e884..a5b20576 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java @@ -28,12 +28,13 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.FieldNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.LanguageFeatures; /** * Bytecode preprocessor for interface mixins, simply performs some additional @@ -59,9 +60,18 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { @Override protected void prepareMethod(MixinMethodNode mixinMethod, Method method) { // Userland interfaces should not have non-public methods except for lambda bodies - if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC) && !Bytecode.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)) { + if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC)) { + if (Bytecode.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)) { + CompatibilityLevel requiredLevel = CompatibilityLevel.requiredFor(LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES); + if (MixinEnvironment.getCompatibilityLevel().isLessThan(requiredLevel)) { + throw new InvalidInterfaceMixinException(this.mixin, String.format( + "Interface mixin contains a synthetic private method but compatibility level %s is required! Found %s in %s", + requiredLevel, method, this.mixin)); + } + } + //On versions that support it private methods are also allowed - if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE) || !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.PRIVATE_METHODS_IN_INTERFACES)) { + if (!Bytecode.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE) || !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES)) { throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains a non-public method! Found " + method + " in " + this.mixin); } @@ -80,8 +90,8 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { @Override protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { if (!Bytecode.isStatic(field)) { - throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains an instance field! Found " + field.name + " in " - + this.mixin); + throw new InvalidInterfaceMixinException(this.mixin, String.format("Interface mixin contains an instance field! Found %s in %s", + field.name, this.mixin)); } return super.validateField(context, field, shadow); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index 818d73cb..d24bce2d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -109,7 +109,7 @@ class MixinPreProcessorStandard { private SpecialMethod(boolean isOverwrite, Class type) { this.isOverwrite = isOverwrite; this.annotation = type; - this.description = "@" + Bytecode.getSimpleName(type); + this.description = "@" + Annotations.getSimpleName(type); } private SpecialMethod(boolean isOverwrite) { @@ -377,7 +377,7 @@ class MixinPreProcessorStandard { } else { String uniqueName = context.getUniqueName(mixinMethod, true); MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @{} method {}{} to {} in {}", - Bytecode.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); + Annotations.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); mixinMethod.name = method.conform(uniqueName); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 86d82b28..8dc8fea7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -42,6 +42,8 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; import org.spongepowered.asm.mixin.throwables.MixinApplyError; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -69,7 +71,7 @@ import org.spongepowered.asm.util.perf.Profiler.Section; /** * Heart of the Mixin pipeline */ -public class MixinProcessor { +class MixinProcessor { /** * Phase during which an error occurred, delegates to functionality in @@ -304,7 +306,6 @@ public class MixinProcessor { return success; } - SortedSet mixins = null; MixinConfig packageOwnedByConfig = null; for (MixinConfig config : this.configs) { @@ -315,7 +316,20 @@ public class MixinProcessor { } continue; } + } + + if (packageOwnedByConfig != null) { + // AMS - Temp passthrough for injection points and dynamic selectors. Moving to service in 0.9 + ClassInfo targetInfo = ClassInfo.fromClassNode(targetClassNode); + if (targetInfo.hasSuperClass(InjectionPoint.class) || targetInfo.hasSuperClass(ITargetSelectorDynamic.class)) { + return false; + } + throw new IllegalClassLoadError(this.getInvalidClassError(name, targetClassNode, packageOwnedByConfig)); + } + + SortedSet mixins = null; + for (MixinConfig config : this.configs) { if (config.hasMixinsFor(name)) { if (mixins == null) { mixins = new TreeSet(); @@ -325,10 +339,6 @@ public class MixinProcessor { mixins.addAll(config.getMixinsFor(name)); } } - - if (packageOwnedByConfig != null) { - throw new IllegalClassLoadError(this.getInvalidClassError(name, targetClassNode, packageOwnedByConfig)); - } if (mixins != null) { // Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now @@ -373,12 +383,6 @@ public class MixinProcessor { return String.format("Illegal classload request for %s. Mixin is defined in %s and cannot be referenced directly", name, ownedByConfig); } -// AnnotationNode proxy = Annotations.getInvisible(targetClassNode, Proxy.class); -// if (proxy != null) { -// return String.format("Illegal classload request for UNRESOLVED @Proxy %s. " -// + "The proxy was referenced outside a mixin or the mixin processor encountered an internal error.", name); -// } - AnnotationNode mixin = Annotations.getInvisible(targetClassNode, Mixin.class); if (mixin != null) { Variant variant = MixinInfo.getVariant(targetClassNode); @@ -534,7 +538,7 @@ public class MixinProcessor { } } - plugin.acceptTargets(config.getTargets(), Collections.unmodifiableSet(otherTargets)); + plugin.acceptTargets(config.getTargetsSet(), Collections.unmodifiableSet(otherTargets)); } for (MixinConfig config : this.pendingConfigs) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 268bc9e5..51f2077d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -39,6 +39,7 @@ import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.objectweb.asm.ConstantDynamic; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -54,8 +55,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.struct.Target; -import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.struct.MemberRef; @@ -76,6 +77,9 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.Visibility; import org.spongepowered.asm.util.ClassSignature; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.LanguageFeatures; +import org.spongepowered.asm.util.asm.ASM; +import org.spongepowered.asm.util.asm.ClassNodeAdapter; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; @@ -179,7 +183,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * Minimum class version required to apply this mixin, target class will be * upgraded if the version is below this value */ - private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion(); + private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.getClassVersion(); /** * ctor @@ -666,7 +670,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { if (typeInsn.getOpcode() == Opcodes.CHECKCAST && typeInsn.desc.equals(this.getTarget().getClassRef()) && lastNode.getOpcode() == Opcodes.ALOAD - && ((VarInsnNode)lastNode).var == 0) { + && ((VarInsnNode)lastNode).var == 0 + && !Bytecode.isStatic(method)) { iter.remove(); return; } @@ -729,6 +734,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return constant; } else if (constant instanceof Handle) { return this.transformHandle(method, iter, (Handle)constant); + } else if (ASM.isAtLeastVersion(6) && constant instanceof ConstantDynamic) { + return this.transformDynamicConstant(method, iter, (ConstantDynamic)constant); } return constant; } @@ -751,6 +758,36 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return memberRef.getMethodHandle(); } + /** + * Transforms a dynamic constant, this is currently a blind implementation + * since I haven't seen this bytecode in the wild. + * TODO Find out if this even works + * + * @param method Method being processed + * @param iter Insn iterator + * @param constant Dynamic constant to transform + * @return Transformed dynamic constant + */ + private ConstantDynamic transformDynamicConstant(MethodNode method, Iterator iter, ConstantDynamic constant) { + this.requireVersion(Opcodes.V11); + + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.DYNAMIC_CONSTANTS)) { + // Shouldn't get here because we should error out during the initial scan, but you never know + throw new InvalidMixinException(this, String.format( + "%s%s in %s contains a dynamic constant, which is not supported by the current compatibility level", + method.name, method.desc, this)); + } + + String desc = this.transformSingleDescriptor(constant.getDescriptor(), false); + Handle bsm = this.transformHandle(method, iter, constant.getBootstrapMethod()); + Object[] bsmArgs = new Object[constant.getBootstrapMethodArgumentCount()]; + for (int i = 0; i < bsmArgs.length; i++) { + bsmArgs[i] = this.transformConstant(method, iter, constant.getBootstrapMethodArgument(i)); + } + + return new ConstantDynamic(constant.getName(), desc, bsm, bsmArgs); + } + /** * Handle "imaginary super" invocations, these are invocations in * non-derived mixins for accessing methods known to exist in a supermixin @@ -972,7 +1009,6 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param method method to get a target handle for * @return new or existing target handle for the supplied method */ - @Override public Target getTargetMethod(MethodNode method) { return this.getTarget().getTargetMethod(method); } @@ -1035,13 +1071,28 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param version version to require */ protected void requireVersion(int version) { - this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version); + int majorVersion = version & 0xFFFF; + int minorVersion = (version >> 16) & 0xFFFF; + + if (majorVersion <= (this.minRequiredClassVersion & 0xFFFF)) { + return; + } + + this.minRequiredClassVersion = version; // This validation is done on the mixin beforehand, however it's still - // possible that an upstream transformer can inject java 7 instructions - // without updating the class version. - if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) { - throw new InvalidMixinException(this, "Unsupported mixin class version " + version); + // possible that an upstream transformer can inject unsupported + // instructions without updating the class version. + if (majorVersion > ASM.getMaxSupportedClassVersionMajor()) { + throw new InvalidMixinException(this, String.format("Unsupported mixin class version %d.%d. ASM supports %s", + majorVersion, minorVersion, ASM.getClassVersionString())); + } + + CompatibilityLevel compatibilityLevel = MixinEnvironment.getCompatibilityLevel(); + if (majorVersion > compatibilityLevel.getClassMajorVersion()) { + MixinTargetContext.logger.warn( + "{}: Class version {}.{} required is higher than the class version supported by the current compatibility level {} ", + this, majorVersion, minorVersion, compatibilityLevel); } } @@ -1157,6 +1208,20 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { String getSourceFile() { return this.classNode.sourceFile; } + + /** + * Get the nest host class from the mixin + */ + String getNestHostClass() { + return ClassNodeAdapter.getNestHostClass(this.classNode); + } + + /** + * Get the nest members from the mixin + */ + List getNestMembers() { + return ClassNodeAdapter.getNestMembers(this.classNode); + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext @@ -1194,9 +1259,9 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { activity.end(); } catch (InjectionValidationException ex) { InjectorGroupInfo group = ex.getGroup(); - throw new InjectionError( + throw new InvalidInjectionException(group.getMembers().iterator().next().getMixin(), String.format("Critical injection failure: Callback group %s in %s failed injection check: %s", - group, this.mixin, ex.getMessage())); + group, this.mixin, ex.getMessage()), ex); } catch (InvalidMixinException ex) { ex.prepend(this.activities); throw ex; @@ -1257,7 +1322,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { } methodActivity.next("Undecorate"); - method.visibleAnnotations.remove(injectInfo.getAnnotation()); + method.visibleAnnotations.remove(injectInfo.getAnnotationNode()); methodActivity.end(); } prepareActivity.end(); @@ -1277,7 +1342,14 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { this.activities.clear(); try { - Activity applyActivity = this.activities.begin("Inject"); + Activity applyActivity = this.activities.begin("PreInject"); + Activity preInjectActivity = this.activities.begin("?"); + for (InjectionInfo injectInfo : this.injectors) { + preInjectActivity.next(injectInfo.toString()); + injectInfo.preInject(); + } + + applyActivity.next("Inject"); Activity injectActivity = this.activities.begin("?"); for (InjectionInfo injectInfo : this.injectors) { injectActivity.next(injectInfo.toString()); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index a9b09c74..f65908ea 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -28,6 +28,7 @@ import java.lang.reflect.Constructor; import java.util.List; import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.launch.MixinInitialisationError; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -41,10 +42,26 @@ import org.spongepowered.asm.util.asm.ASM; /** * Transformer which manages the mixin configuration and application process */ -class MixinTransformer extends TreeTransformer implements IMixinTransformer { +final class MixinTransformer extends TreeTransformer implements IMixinTransformer { + + /** + * Impl of mixin transformer factory + */ + static class Factory implements IMixinTransformerFactory { + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory + * #createTransformer() + */ + @Override + public IMixinTransformer createTransformer() throws MixinInitialisationError { + return new MixinTransformer(); + } + + } private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; - + /** * Synthetic class registry */ @@ -70,7 +87,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { */ private final MixinClassGenerator generator; - public MixinTransformer() { + MixinTransformer() { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); Object globalMixinTransformer = environment.getActiveTransformer(); @@ -190,6 +207,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Class tree * @return true if the class was transformed */ + @Override public boolean computeFramesForClass(MixinEnvironment environment, String name, ClassNode classNode) { // TODO compute added interfaces return false; @@ -203,8 +221,9 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classBytes Class bytecode * @return Transformed bytecode */ + @Override public byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes) { - ClassNode classNode = this.readClass(classBytes); + ClassNode classNode = this.readClass(name, classBytes); if (this.processor.applyMixins(environment, name, classNode)) { return this.writeClass(classNode); } @@ -219,6 +238,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Class tree * @return true if the class was transformed */ + @Override public boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode) { return this.processor.applyMixins(environment, name, classNode); } @@ -230,6 +250,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param name Class name to generate * @return Generated bytecode or null if no class was generated */ + @Override public byte[] generateClass(MixinEnvironment environment, String name) { ClassNode classNode = MixinTransformer.createEmptyClass(name); if (this.generator.generateClass(environment, name, classNode)) { @@ -244,6 +265,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { * @param classNode Empty classnode to populate * @return True if the class was generated successfully */ + @Override public boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { return this.generator.generateClass(environment, name, classNode); } @@ -254,7 +276,7 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { private static ClassNode createEmptyClass(String name) { ClassNode classNode = new ClassNode(ASM.API_VERSION); classNode.name = name.replace('.', '/'); - classNode.version = MixinEnvironment.getCompatibilityLevel().classVersion(); + classNode.version = MixinEnvironment.getCompatibilityLevel().getClassVersion(); classNode.superName = Constants.OBJECT; return classNode; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java index 31565a5f..3a8ef03b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java @@ -94,7 +94,7 @@ class PluginHandle { if (!Strings.isNullOrEmpty(pluginClassName)) { try { Class pluginClass = service.getClassProvider().findClass(pluginClassName, true); - plugin = (IMixinConfigPlugin)pluginClass.newInstance(); + plugin = (IMixinConfigPlugin)pluginClass.getDeclaredConstructor().newInstance(); } catch (Throwable th) { PluginHandle.logger.error("Error loading companion plugin class [{}] for mixin config [{}]. The plugin may be out of date: {}:{}", pluginClassName, parent, th.getClass().getSimpleName(), th.getMessage(), th); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java index c72601de..f1768adc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java @@ -86,13 +86,29 @@ public class ExtensionCheckInterfaces implements IExtension { * Strict mode */ private boolean strict; + + /** + * True once the output dir and csv have been created, not triggered until + * something is written + */ + private boolean started = false; public ExtensionCheckInterfaces() { File debugOutputFolder = new File(Constants.DEBUG_OUTPUT_DIR, ExtensionCheckInterfaces.AUDIT_DIR); - debugOutputFolder.mkdirs(); this.csv = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_CSV_FILENAME); this.report = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_TXT_FILENAME); + } + + /** + * Delayed creation of CSV so the dir doesn't get created when the extension + * is inactive + */ + private void start() { + if (this.started) { + return; + } + this.started = true; this.csv.getParentFile().mkdirs(); try { @@ -137,6 +153,8 @@ public class ExtensionCheckInterfaces implements IExtension { */ @Override public void postApply(ITargetClassContext context) { + this.start(); + ClassInfo targetClassInfo = context.getClassInfo(); // If the target is abstract and strict mode is not enabled, skip this class diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java new file mode 100644 index 00000000..9f661b44 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline extensions. + */ +package org.spongepowered.asm.mixin.transformer.ext.extensions; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java new file mode 100644 index 00000000..16d1fa4d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline extension interface and registry of + * active extensions. + */ +package org.spongepowered.asm.mixin.transformer.ext; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java new file mode 100644 index 00000000..9d6a3b8b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Meta annotations applied by the mixin processor to fingerprint mixin actions. + */ +package org.spongepowered.asm.mixin.transformer.meta; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java new file mode 100644 index 00000000..34f240d9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Internal mixin transformation pipeline classes. + */ +package org.spongepowered.asm.mixin.transformer; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java new file mode 100644 index 00000000..cd3fafb2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin transformation pipeline throwables. + */ +package org.spongepowered.asm.mixin.transformer.throwables; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java new file mode 100644 index 00000000..da35f651 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings. + */ +package org.spongepowered.asm.obfuscation.mapping.common; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java new file mode 100644 index 00000000..b18be912 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/fg3/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings with specific behaviour for ForgeGradle + * 3 and above. + */ +package org.spongepowered.asm.obfuscation.mapping.fg3; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java new file mode 100644 index 00000000..a12457a2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/mcp/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Structs for method and field mappings with specific behaviour for MCP + */ +package org.spongepowered.asm.obfuscation.mapping.mcp; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java new file mode 100644 index 00000000..ea731a55 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Interface for structs for method and field mappings. + */ +package org.spongepowered.asm.obfuscation.mapping; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/package-info.java b/src/main/java/org/spongepowered/asm/obfuscation/package-info.java new file mode 100644 index 00000000..4aa77ff4 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Obfuscation-related structs for interoperability with the annotation + * processor and runtime obfuscation utilities. + */ +package org.spongepowered.asm.obfuscation; diff --git a/src/main/java/org/spongepowered/asm/package-info.java b/src/main/java/org/spongepowered/asm/package-info.java new file mode 100644 index 00000000..41b69dd0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * The Mixin runtime and utilities. + */ +package org.spongepowered.asm; diff --git a/src/main/java/org/spongepowered/asm/service/IMixinInternal.java b/src/main/java/org/spongepowered/asm/service/IMixinInternal.java new file mode 100644 index 00000000..2e354fd9 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/IMixinInternal.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.service; + +/** + * A mixin internal part, offered to services. + */ +public interface IMixinInternal { + +} diff --git a/src/main/java/org/spongepowered/asm/service/IMixinService.java b/src/main/java/org/spongepowered/asm/service/IMixinService.java index aa5c324f..a4f068c6 100644 --- a/src/main/java/org/spongepowered/asm/service/IMixinService.java +++ b/src/main/java/org/spongepowered/asm/service/IMixinService.java @@ -62,6 +62,15 @@ public interface IMixinService { */ public abstract Phase getInitialPhase(); + /** + * Called when the subsystem is offering internal components to the service, + * the service can determine whether to retain or ignore the component based + * on its own requirements. + * + * @param internal Internal component being offered + */ + public abstract void offer(IMixinInternal internal); + /** * Called at the end of subsystem boot */ diff --git a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java index 9e57708a..1babae68 100644 --- a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java +++ b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java @@ -26,7 +26,9 @@ package org.spongepowered.asm.service; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -50,6 +52,7 @@ public abstract class MixinServiceAbstract implements IMixinService { // Consts protected static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; protected static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin."; + protected static final String SERVICE_PACKAGE = "org.spongepowered.asm.service."; /** * Logger @@ -62,6 +65,11 @@ public abstract class MixinServiceAbstract implements IMixinService { */ protected final ReEntranceLock lock = new ReEntranceLock(1); + /** + * All internals offered to this service + */ + private final Map, IMixinInternal> internals = new HashMap, IMixinInternal>(); + /** * Service agent instances */ @@ -104,6 +112,46 @@ public abstract class MixinServiceAbstract implements IMixinService { public CompatibilityLevel getMaxCompatibilityLevel() { return null; } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService + * #offer(org.spongepowered.asm.service.IMixinInternal) + */ + @Override + public void offer(IMixinInternal internal) { + this.registerInternal(internal, internal.getClass()); + } + + @SuppressWarnings("unchecked") + private void registerInternal(IMixinInternal internal, Class clazz) { + for (Class iface : clazz.getInterfaces()) { + if (iface == IMixinInternal.class) { + this.internals.put((Class)clazz, internal); + } + this.registerInternal(internal, iface); + } + } + + @SuppressWarnings("unchecked") + protected final T getInternal(Class type) { + for (Class internalType : this.internals.keySet()) { + if (type.isAssignableFrom(internalType)) { + return (T)this.internals.get(internalType); + } + } + + return null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#init() + */ + @Override + public void init() { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + agent.init(); + } + } /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#beginPhase() @@ -120,16 +168,6 @@ public abstract class MixinServiceAbstract implements IMixinService { public void checkEnv(Object bootSource) { } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#init() - */ - @Override - public void init() { - for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { - agent.init(); - } - } - /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#getReEntranceLock() */ @@ -192,7 +230,7 @@ public abstract class MixinServiceAbstract implements IMixinService { try { @SuppressWarnings("unchecked") Class agentClass = (Class)this.getClassProvider().findClass(agentClassName, false); - IMixinPlatformAgent agent = agentClass.newInstance(); + IMixinPlatformAgent agent = agentClass.getDeclaredConstructor().newInstance(); if (agent instanceof IMixinPlatformServiceAgent) { this.serviceAgents.add((IMixinPlatformServiceAgent)agent); } diff --git a/src/main/java/org/spongepowered/asm/service/package-info.java b/src/main/java/org/spongepowered/asm/service/package-info.java new file mode 100644 index 00000000..39cc7d8f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/package-info.java @@ -0,0 +1,31 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Mixin service interface, with base classes for all the moving parts of the + * Mixin transformation pipeline and supporting infrastructure. Abstracted here + * and implemented by platform-specific modules. + */ +package org.spongepowered.asm.service; diff --git a/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java b/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java new file mode 100644 index 00000000..bee1d5ee --- /dev/null +++ b/src/main/java/org/spongepowered/asm/transformers/MixinClassReader.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.transformers; + +import org.objectweb.asm.ClassReader; +import org.spongepowered.asm.util.asm.ASM; + +/** + * A ClassReader which returns a more verbose exception message when the + * incoming class major version is higher than the version supported by the + * active ASM. + */ +public class MixinClassReader extends ClassReader { + + public MixinClassReader(final byte[] classFile, final String name) { + super(MixinClassReader.checkClassVersion(classFile, name)); + } + + private static byte[] checkClassVersion(final byte[] classFile, final String name) { + short majorClassVersion = (short)(((classFile[6] & 0xFF) << 8) | (classFile[7] & 0xFF)); + if (majorClassVersion > ASM.getMaxSupportedClassVersionMajor()) { + throw new IllegalArgumentException(String.format( + "Class file major version %d is not supported by active ASM (version %d.%d supports class version %d), reading %s", + majorClassVersion, ASM.getApiVersionMajor(), ASM.getApiVersionMinor(), ASM.getMaxSupportedClassVersionMajor(), name)); + } + return classFile; + } + +} diff --git a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java index 8e07d2e9..c2078b8b 100644 --- a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java +++ b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java @@ -41,8 +41,8 @@ public abstract class TreeTransformer implements ILegacyClassTransformer { * @param basicClass Original bytecode * @return tree */ - protected final ClassNode readClass(byte[] basicClass) { - return this.readClass(basicClass, true); + protected final ClassNode readClass(String className, byte[] basicClass) { + return this.readClass(className, basicClass, true); } /** @@ -51,8 +51,8 @@ public abstract class TreeTransformer implements ILegacyClassTransformer { * writing the generated ClassNode later * @return tree */ - protected final ClassNode readClass(byte[] basicClass, boolean cacheReader) { - ClassReader classReader = new ClassReader(basicClass); + protected final ClassNode readClass(String className, byte[] basicClass, boolean cacheReader) { + ClassReader classReader = new MixinClassReader(basicClass, className); if (cacheReader) { this.classReader = classReader; } diff --git a/src/main/java/org/spongepowered/asm/transformers/package-info.java b/src/main/java/org/spongepowered/asm/transformers/package-info.java new file mode 100644 index 00000000..ea62595f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/transformers/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Specialised ASM utility and base classes used by the mixin processor. + */ +package org.spongepowered.asm.transformers; diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index e50725f7..d248c593 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -43,6 +43,7 @@ import org.spongepowered.asm.mixin.Debug; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import com.google.common.base.Function; import com.google.common.base.Preconditions; @@ -53,6 +54,87 @@ import com.google.common.collect.Lists; */ public final class Annotations { + /** + * Wrapper for {@link AnnotationNode} to support access via common interface + */ + public static class Handle implements IAnnotationHandle { + + private final AnnotationNode annotation; + + Handle(AnnotationNode annotation) { + Preconditions.checkNotNull(annotation, "annotation"); + this.annotation = annotation; + } + + @Override + public boolean exists() { + return true; + } + + public AnnotationNode getNode() { + return this.annotation; + } + + @Override + public String getDesc() { + return Type.getType(this.annotation.desc).getInternalName(); + } + + @Override + public List getAnnotationList(String key) { + List value = Annotations.getValue(this.annotation, key, false); + List list = new ArrayList(); + if (value != null) { + for (AnnotationNode node : value) { + list.add(new Handle(node)); + } + } + return list; + } + + @Override + public Type getTypeValue(String key) { + return this.getValue(key, Type.VOID_TYPE); + } + + @Override + public List getTypeList(String key) { + return this.getList(key); + } + + @Override + public IAnnotationHandle getAnnotation(String key) { + AnnotationNode value = Annotations.getValue(this.annotation, key); + return value != null ? new Handle(value) : null; + } + + @Override + public T getValue(String key, T defaultValue) { + return Annotations.getValue(this.annotation, key, defaultValue); + } + + @Override + public T getValue() { + return this.getValue("value", null); + } + + @Override + public T getValue(String key) { + return this.getValue(key, null); + } + + @Override + public List getList(String key) { + return Annotations.getValue(this.annotation, key, false); + } + + @Override + public String toString() { + return "@" + Annotations.getSimpleName(this.annotation); + } + + } + /** * Annotations which are eligible for merge via {@link #mergeAnnotations} */ @@ -70,6 +152,56 @@ public final class Annotations { private Annotations() { // Utility class } + + /** + * Get the supplied annotation object as an annotation handle + * + * @param annotation Annotation to return + * @return Wrapped or cast annotation + */ + public static IAnnotationHandle handleOf(Object annotation) { + if (annotation instanceof IAnnotationHandle) { + return (IAnnotationHandle)annotation; + } else if (annotation instanceof AnnotationNode) { + return new Annotations.Handle((AnnotationNode)annotation); + } else if (annotation == null) { + return null; + } else { + throw new IllegalArgumentException("Unsupported annotation type: " + annotation.getClass().getName()); + } + } + + /** + * Returns the bytecode descriptor of an annotation + * + * @param annotationType annotation + * @return annotation's descriptor + */ + public static String getDesc(Class annotationType) { + return Type.getType(annotationType).getInternalName(); + } + + /** + * Returns the simple name of an annotation, mainly used for printing + * annotation names in error messages/user-facing strings + * + * @param annotationType annotation + * @return annotation's simple name + */ + public static String getSimpleName(Class annotationType) { + return annotationType.getSimpleName(); + } + + /** + * Returns the simple name of an annotation, mainly used for printing + * annotation names in error messages/user-facing strings + * + * @param annotation annotation node + * @return annotation's simple name + */ + public static String getSimpleName(AnnotationNode annotation) { + return Bytecode.getSimpleName(annotation.desc); + } /** * Set a runtime-visible annotation of the specified class on the supplied diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 0bc9e7a2..e199fd33 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -26,7 +26,6 @@ package org.spongepowered.asm.util; import java.io.OutputStream; import java.io.PrintWriter; -import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -104,6 +103,17 @@ public final class Bytecode { return other == null || other.ordinal() <= this.ordinal(); } + /** + * Get whether this visibility level represents a level which less than + * the supplied level + * + * @param other level to compare to + * @return true if greater or equal + */ + public boolean isLessThan(Visibility other) { + return other != null && this.ordinal() < other.ordinal(); + } + } /** @@ -414,15 +424,27 @@ public final class Bytecode { * @return human-readable description of node */ public static String describeNode(AbstractInsnNode node) { + return Bytecode.describeNode(node, true); + } + + /** + * Gets a description of the supplied node for debugging purposes + * + * @param node node to describe + * @param listFormat format the returned string so that returned nodes line + * up (node names aligned to 14 chars) + * @return human-readable description of node + */ + public static String describeNode(AbstractInsnNode node, boolean listFormat) { if (node == null) { - return String.format(" %-14s ", "null"); + return listFormat ? String.format(" %-14s ", "null") : "null"; } if (node instanceof LabelNode) { return String.format("[%s]", ((LabelNode)node).getLabel()); } - String out = String.format(" %-14s ", node.getClass().getSimpleName().replace("Node", "")); + String out = String.format(listFormat ? " %-14s " : "%s ", node.getClass().getSimpleName().replace("Node", "")); if (node instanceof JumpInsnNode) { out += String.format("[%s] [%s]", Bytecode.getOpcodeName(node), ((JumpInsnNode)node).label.getLabel()); } else if (node instanceof VarInsnNode) { @@ -446,6 +468,8 @@ public final class Bytecode { out += (((IntInsnNode)node).operand); } else if (node instanceof FrameNode) { out += String.format("[%s] ", Bytecode.getOpcodeName(((FrameNode)node).type, "H_INVOKEINTERFACE", -1)); + } else if (node instanceof TypeInsnNode) { + out += String.format("[%s] %s", Bytecode.getOpcodeName(node), ((TypeInsnNode)node).desc); } else { out += String.format("[%s] ", Bytecode.getOpcodeName(node)); } @@ -646,6 +670,72 @@ public final class Bytecode { } } +// /** +// * Generate required APPEND frame nodes for the listed types and append them +// * to the supplied instruction list +// * +// * @param insns Insnlist to append to +// * @param types frame types to append +// */ +// public static void extendFrame(InsnList insns, Type[] types) { +// int offset = 0; +// Object[] locals = new Object[3]; +// +// for (int index = 0; index < types.length; index++) { +// +// Type type = types[index]; +// int size = type.getSize(); +// if (offset + size <= 3) { +// if (type.getSort() < Type.ARRAY) { +// locals[offset] = type.getSort(); +// } else { +// locals[offset] = type.getInternalName(); +// } +// if (size > 1) { +// locals[offset + 1] = null; +// } +// offset += size; +// } else { +// insns.add(new FrameNode(Opcodes.F_APPEND, offset, locals, 0, null)); +// offset = 0; +// } +// } +// +// if (offset > 0) { +// insns.add(new FrameNode(Opcodes.F_APPEND, offset, locals, 0, null)); +// } +// } +// +// /** +// * Generate required CHOP frame nodes for the listed types and append them +// * to the supplied insn list +// * +// * @param insns Insnlist to append generated nodes to +// * @param types types to chop +// */ +// public static void chopFrame(InsnList insns, Type[] types) { +// int size = Bytecode.getArgsSize(types); +// while (size > 0) { +// int chop = Math.min(size, 3); +// insns.add(new FrameNode(Opcodes.F_CHOP, chop, null, 0, null)); +// size -= chop; +// } +// } + + /** + * Get an array of Types from an array of classes. + * + * @param classes Array of classes to convert + * @return Array of types + */ + public static Type[] getTypes(Class... classes) { + Type[] types = new Type[classes.length]; + for (int index = 0; index < classes.length; index++) { + types[index] = Type.getType(classes[index]); + } + return types; + } + /** * Clones all of the labels in the source instruction list and returns the * clones in a map of old label -> new label. This is used to facilitate @@ -752,17 +842,6 @@ public final class Bytecode { return desc.substring(0, desc.lastIndexOf(')') + 1) + returnType; } - /** - * Returns the simple name of an annotation, mainly used for printing - * annotation names in error messages/user-facing strings - * - * @param annotationType annotation - * @return annotation's simple name - */ - public static String getSimpleName(Class annotationType) { - return annotationType.getSimpleName(); - } - /** * Returns the simple name of a type representing a class * @@ -772,17 +851,6 @@ public final class Bytecode { public static String getSimpleName(Type type) { return type.getSort() < Type.ARRAY ? type.getDescriptor() : Bytecode.getSimpleName(type.getClassName()); } - - /** - * Returns the simple name of an annotation, mainly used for printing - * annotation names in error messages/user-facing strings - * - * @param annotation annotation node - * @return annotation's simple name - */ - public static String getSimpleName(AnnotationNode annotation) { - return Bytecode.getSimpleName(annotation.desc); - } /** * Returns the simple name from an object type descriptor (in L...; format) @@ -1008,6 +1076,17 @@ public final class Bytecode { return Bytecode.Visibility.PACKAGE; } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param visibility new visibility + */ + public static void setVisibility(ClassNode classNode, Visibility visibility) { + classNode.access = Bytecode.setVisibility(classNode.access, visibility.access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged @@ -1030,6 +1109,17 @@ public final class Bytecode { field.access = Bytecode.setVisibility(field.access, visibility.access); } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param access new visibility + */ + public static void setVisibility(ClassNode classNode, int access) { + classNode.access = Bytecode.setVisibility(classNode.access, access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged @@ -1222,9 +1312,12 @@ public final class Bytecode { } // TODO Java 10 -// dest.nestHostClassExperimental = source.nestHostClassExperimental; -// Bytecode.clear(dest.nestMembersExperimental); -// dest.nestMembersExperimental = Bytecode.merge(source.nestMembersExperimental, dest.nestMembersExperimental); +// if (MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) { +// ClassNodeAdapter.setNestHostClass(dest, ClassNodeAdapter.getNestHostClass(source)); +// Bytecode.clear(ClassNodeAdapter.getNestMembers(dest)); +// ClassNodeAdapter.setNestMembers(dest, Bytecode.merge(ClassNodeAdapter.getNestMembers(source), +// ClassNodeAdapter.getNestMembers(dest))); +// } Bytecode.merge(source, dest); diff --git a/src/main/java/org/spongepowered/asm/util/Handles.java b/src/main/java/org/spongepowered/asm/util/Handles.java new file mode 100644 index 00000000..55709f2b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Handles.java @@ -0,0 +1,82 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +import org.objectweb.asm.Handle; +import org.objectweb.asm.Opcodes; + +/** + * Utility class for working with method and field handles + */ +public final class Handles { + + private static final int[] H_OPCODES = { + 0, // invalid + Opcodes.GETFIELD, // H_GETFIELD + Opcodes.GETSTATIC, // H_GETSTATIC + Opcodes.PUTFIELD, // H_PUTFIELD + Opcodes.PUTSTATIC, // H_PUTSTATIC + Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL + Opcodes.INVOKESTATIC, // H_INVOKESTATIC + Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL + Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL + Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE + }; + + private Handles() { + } + + public static boolean isField(Handle handle) { + switch (handle.getTag()) { + case Opcodes.H_INVOKEVIRTUAL: + case Opcodes.H_INVOKESTATIC: + case Opcodes.H_INVOKEINTERFACE: + case Opcodes.H_INVOKESPECIAL: + case Opcodes.H_NEWINVOKESPECIAL: + return false; + case Opcodes.H_GETFIELD: + case Opcodes.H_GETSTATIC: + case Opcodes.H_PUTFIELD: + case Opcodes.H_PUTSTATIC: + return true; + default: + throw new IllegalArgumentException("Invalid tag " + handle.getTag() + " for method handle " + handle + "."); + } + } + + public static int opcodeFromTag(int tag) { + return (tag >= 0 && tag < Handles.H_OPCODES.length) ? Handles.H_OPCODES[tag] : 0; + } + + public static int tagFromOpcode(int opcode) { + for (int tag = 1; tag < Handles.H_OPCODES.length; tag++) { + if (Handles.H_OPCODES[tag] == opcode) { + return tag; + } + } + return 0; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java b/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java new file mode 100644 index 00000000..ca39785c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/LanguageFeatures.java @@ -0,0 +1,176 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.ListIterator; + +import org.objectweb.asm.ConstantDynamic; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.util.Bytecode.Visibility; +import org.spongepowered.asm.util.asm.ASM; +import org.spongepowered.asm.util.asm.ClassNodeAdapter; + +/** + * Bitmask values for language features supported. Contains utility methods for + * detecting language features in use in supplied class nodes. + */ +public final class LanguageFeatures { + + /** + * Language version supports methods in interfaces + */ + public static final int METHODS_IN_INTERFACES = 1; + + /** + * Language version supports synthetic private methods in interfaces + */ + public static final int PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES = 2; + + /** + * Language version supports user-defined private methods in interfaces + */ + public static final int PRIVATE_METHODS_IN_INTERFACES = 4; + + /** + * Native nesting + */ + public static final int NESTING = 8; + + /** + * Dynamic constants + */ + public static final int DYNAMIC_CONSTANTS = 16; + + /** + * Utility class + */ + private LanguageFeatures() { + } + + /** + * Scan the supplied class node to determine required language features via + * heuristic. + * + * @param classNode ClassNode to scan (must include method bodies for + * reliable detection) + * @return detected language features + */ + public static int scan(ClassNode classNode) { + int features = LanguageFeatures.scanClassFeatures(classNode); + + boolean isInterface = Bytecode.hasFlag(classNode, Opcodes.ACC_INTERFACE); + for (MethodNode methodNode : classNode.methods) { + if (isInterface) { + features |= LanguageFeatures.scanInterfaceFeatures(methodNode); + } else { + features |= LanguageFeatures.scanMethodFeatures(methodNode); + } + } + + return features; + } + + /** + * Sacn for features at the class level + */ + private static int scanClassFeatures(ClassNode classNode) { + int features = 0; + + String nestHostClass = ClassNodeAdapter.getNestHostClass(classNode); + List nestMembers = ClassNodeAdapter.getNestMembers(classNode); + if (nestHostClass != null || (nestMembers != null && nestMembers.size() > 0)) { + features |= LanguageFeatures.NESTING; + } + + return features; + } + + /** + * Scan the method for interface-specific features + */ + private static int scanInterfaceFeatures(MethodNode methodNode) { + int features = 0; + + if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_ABSTRACT)) { + features |= LanguageFeatures.METHODS_IN_INTERFACES; + } + + if (Bytecode.getVisibility(methodNode).isLessThan(Visibility.PUBLIC)) { + features |= Bytecode.hasFlag(methodNode, Opcodes.ACC_SYNTHETIC) + ? LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES + : LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES; + } + + return features; + } + + /** + * Scan the method code for feature requirements + */ + private static int scanMethodFeatures(MethodNode methodNode) { + // ConstantDynamic only exists in ASM 6 and later + if (ASM.isAtLeastVersion(6)) { + for (ListIterator iter = methodNode.instructions.iterator(); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof LdcInsnNode && ((LdcInsnNode)insn).cst instanceof ConstantDynamic) { + return LanguageFeatures.DYNAMIC_CONSTANTS; + } + } + } + return 0; + } + + /** + * Format the supplied feature mask as a plain-text list for use in error + * messages etc. + * + * @param features Language features to format + * @return Formatted list of features + */ + public static final String format(int features) { + StringBuilder sb = new StringBuilder("["); + try { + int count = 0; + for (Field field : LanguageFeatures.class.getDeclaredFields()) { + if ((features & field.getInt(null)) != 0) { + if (count++ > 0) { + sb.append(','); + } + sb.append(field.getName()); + } + } + } catch (ReflectiveOperationException ex) { + sb.append("ERROR"); + } + return sb.append(']').toString(); + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 733b57f2..116fc122 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -57,6 +57,17 @@ import org.spongepowered.asm.util.throwables.LVTGeneratorError; */ public final class Locals { + /** + * A local variable entry added by mixin itself, eg. by an injector + */ + public static class SyntheticLocalVariableNode extends LocalVariableNode { + + public SyntheticLocalVariableNode(String name, String descriptor, String signature, LabelNode start, LabelNode end, int index) { + super(name, descriptor, signature, start, end, index); + } + + } + /** * Frame type names just for the purposes of debug printing */ @@ -135,9 +146,13 @@ public final class Locals { */ public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node) { for (int i = 0; i < 3 && (node instanceof LabelNode || node instanceof LineNumberNode); i++) { - node = Locals.nextNode(method.instructions, node); + AbstractInsnNode nextNode = Locals.nextNode(method.instructions, node); + if (nextNode instanceof FrameNode) { // Do not ffwd over frames + break; + } + node = nextNode; } - + ClassInfo classInfo = ClassInfo.forName(classNode.name); if (classInfo == null) { throw new LVTGeneratorError("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); @@ -166,12 +181,20 @@ public final class Locals { int frameSize = local; int frameIndex = -1; int lastFrameSize = local; + int knownFrameSize = local; VarInsnNode storeInsn = null; for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (storeInsn != null) { - frame[storeInsn.var] = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + frame[storeInsn.var] = storedLocal; + knownFrameSize = Math.max(knownFrameSize, storeInsn.var + 1); + if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && storedLocal.desc != null + && Type.getType(storedLocal.desc).getSize() == 2) { + frame[storeInsn.var + 1] = null; // TOP + knownFrameSize = Math.max(knownFrameSize, storeInsn.var + 2); + } storeInsn = null; } @@ -182,12 +205,12 @@ public final class Locals { break handleFrame; } + int frameNodeSize = Locals.computeFrameSize(frameNode); FrameData frameData = frameIndex < frames.size() ? frames.get(frameIndex) : null; if (frameData != null) { if (frameData.type == Opcodes.F_FULL) { - frameSize = Math.min(frameSize, frameData.locals); - lastFrameSize = frameSize; + knownFrameSize = lastFrameSize = frameSize = Math.min(frameNodeSize, frameData.size); } else { frameSize = Locals.getAdjustedFrameSize(frameSize, frameData); } @@ -195,17 +218,25 @@ public final class Locals { frameSize = Locals.getAdjustedFrameSize(frameSize, frameNode); } - if (frameNode.type == Opcodes.F_CHOP) { + // Sanity check + if (frameSize < 0) { + throw new IllegalStateException(String.format("Locals entered an invalid state evaluating %s::%s%s at instruction %d (%s). " + + "Initial frame size is %d, calculated a frame size of %d with %s", classNode.name, method.name, method.desc, + method.instructions.indexOf(insn), Bytecode.describeNode(insn, false), initialFrameSize, frameSize, frameData)); + } + + if ((frameData == null && (frameNode.type == Opcodes.F_CHOP || frameNode.type == Opcodes.F_NEW)) + || (frameData != null && frameData.type == Opcodes.F_CHOP)) { for (int framePos = frameSize; framePos < frame.length; framePos++) { frame[framePos] = null; } - lastFrameSize = frameSize; + knownFrameSize = lastFrameSize = frameSize; break handleFrame; } int framePos = frameNode.type == Opcodes.F_APPEND ? lastFrameSize : 0; lastFrameSize = frameSize; - + // localPos tracks the location in the frame node's locals list, which doesn't leave space for TOP entries for (int localPos = 0; framePos < frame.length; framePos++, localPos++) { // Get the local at the current position in the FrameNode's locals list @@ -223,7 +254,7 @@ public final class Locals { frame[framePos] = null; } else if (is32bitValue || is64bitValue) { frame[framePos] = Locals.getLocalVariableAt(classNode, method, insn, framePos); - + if (is64bitValue) { framePos++; frame[framePos] = null; // TOP @@ -234,7 +265,11 @@ public final class Locals { } } else if (localType == null) { if (framePos >= initialFrameSize && framePos >= frameSize && frameSize > 0) { - frame[framePos] = null; + if (framePos < knownFrameSize) { + frame[framePos] = Locals.getLocalVariableAt(classNode, method, insn, framePos); + } else { + frame[framePos] = null; + } } } else if (localType instanceof LabelNode) { // Uninitialised @@ -248,6 +283,8 @@ public final class Locals { boolean isLoad = insn.getOpcode() >= Opcodes.ILOAD && insn.getOpcode() <= Opcodes.SALOAD; if (isLoad) { frame[varNode.var] = Locals.getLocalVariableAt(classNode, method, insn, varNode.var); + int varSize = frame[varNode.var].desc != null ? Type.getType(frame[varNode.var].desc).getSize() : 1; + knownFrameSize = Math.max(knownFrameSize, varNode.var + varSize); } else { // Update the LVT for the opcode AFTER this one, since we always want to know // the frame state BEFORE the *current* instruction to match the contract of @@ -261,9 +298,9 @@ public final class Locals { } } - // Null out any "unknown" locals + // Null out any "unknown" or mixin-provided locals for (int l = 0; l < frame.length; l++) { - if (frame[l] != null && frame[l].desc == null) { + if (frame[l] != null && frame[l].desc == null || frame[l] instanceof SyntheticLocalVariableNode) { frame[l] = null; } } @@ -435,7 +472,7 @@ public final class Locals { labels[i] = label = new LabelNode(); } } - + if (local == null && locals[j] != null) { localVariables.add(localNodes[j]); localNodes[j].end = label; @@ -447,7 +484,13 @@ public final class Locals { localNodes[j] = null; } - String desc = (local.getType() != null) ? local.getType().getDescriptor() : lastKnownType[j]; + String desc = lastKnownType[j]; + Type localType = local.getType(); + if (localType != null) { + desc = localType.getSort() >= Type.ARRAY && "null".equals(localType.getInternalName()) + ? Constants.OBJECT_DESC : localType.getDescriptor(); + } + localNodes[j] = new LocalVariableNode("var" + j, desc, null, label, null, j); if (desc != null) { lastKnownType[j] = desc; @@ -497,7 +540,7 @@ public final class Locals { } return insn; } - + /** * Compute a new frame size based on the supplied frame type and the size of * locals contained in the frame (this may differ from the number of actual diff --git a/src/main/java/org/spongepowered/asm/util/Quantifier.java b/src/main/java/org/spongepowered/asm/util/Quantifier.java new file mode 100644 index 00000000..12141ec7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Quantifier.java @@ -0,0 +1,214 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +/** + * A regex-style quantifier, specified as a number or pair of numbers in braces. + */ +public final class Quantifier { + + /** + * Default quantifier, used when a quantifier was not specified + * (empty string) + */ + public static Quantifier DEFAULT = new Quantifier(0, -1); + + /** + * Invalid (matches none) + */ + public static Quantifier NONE = new Quantifier(0, 0); + + /** + * Single (matches zero or 1) + */ + public static Quantifier SINGLE = new Quantifier(0, 1); + + /** + * Default (matches any) + */ + public static Quantifier ANY = new Quantifier(0, Integer.MAX_VALUE); + + /** + * Plus (matches 1 or more) + */ + public static Quantifier PLUS = new Quantifier(1, Integer.MAX_VALUE); + + /** + * Minimum value, parsed from expression, 0 if unbounded + */ + private final int min; + + /** + * Maximum value, parsed from expression, Integer.MAX_VALUE if unbounded + */ + private final int max; + + public Quantifier(int min, int max) { + this.min = min; + this.max = max; + } + + /** + * Check whether this is a defaulted qualifier + */ + public boolean isDefault() { + return this.min == 0 && this.max < 0; + } + + /** + * Get the literal min value + */ + public int getMin() { + return this.min; + } + + /** + * Get the literal max value + */ + public int getMax() { + return this.max; + } + + /** + * Get the clamped min value + */ + public int getClampedMin() { + return Math.max(0, this.min); + } + + /** + * Get the clamped max value + */ + public int getClampedMax() { + return this.max < 0 ? 1 : Math.max(this.min, this.max); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + if (this.min == this.max) { + sb.append(this.min); + } else if (this.max < this.min) { + return ""; + } else { + if (this.min == 0) { + if (this.max == 1) { + return ""; + } else if (this.max == Integer.MAX_VALUE) { + return "*"; + } + } + if (this.min == 1 && this.max == Integer.MAX_VALUE) { + return "+"; + } + if (this.min > 0) { + sb.append(this.min); + } + if (this.min >= 0) { + sb.append(','); + } + if (this.max < Integer.MAX_VALUE) { + sb.append(this.max); + } + } + return sb.append('}').toString(); + } + + /** + * Parse a quantifier from the supplied string + * + * @param string string to parse + * @return parsed quantifier, malformed quantifiers return NONE + */ + public static Quantifier parse(String string) { + if (string == null || ((string = string.trim()).length() == 0)) { + return Quantifier.DEFAULT; + } + + if ("*".equals(string)) { + return Quantifier.ANY; + } + + if ("+".equals(string)) { + return Quantifier.PLUS; + } + + if (!string.startsWith("{") || !string.endsWith("}") || string.length() < 3) { + return Quantifier.NONE; // malformed + } + + String inner = string.substring(1, string.length() - 1).trim(); + if (inner.isEmpty()) { + return Quantifier.NONE; + } + + String strMin = inner; + String strMax = inner; + + int comma = inner.indexOf(','); + if (comma > -1) { + strMin = inner.substring(0, comma).trim(); + strMax = inner.substring(comma + 1).trim(); + } + + try { + int min = strMin.length() > 0 ? Integer.parseInt(strMin) : 0; + int max = strMax.length() > 0 ? Integer.parseInt(strMax) : Integer.MAX_VALUE; + return new Quantifier(min, max); + } catch (NumberFormatException ex) { + return Quantifier.NONE; + } + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Quantifier) { + Quantifier other = (Quantifier)obj; + return other.min == this.min && other.max == this.max; + } + + if (obj instanceof Number) { + int intValue = ((Number)obj).intValue(); + return (intValue == this.min) && (intValue == this.max); + } + + return false; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return 31 * this.min * this.max; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index 400a6b86..303a8513 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -238,9 +238,9 @@ public class SignaturePrinter { private StringBuilder appendType(StringBuilder sb, Type type, String name) { switch (type.getSort()) { case Type.ARRAY: - return SignaturePrinter.appendArraySuffix(this.appendType(sb, type.getElementType(), name), type); + return SignaturePrinter.appendArraySuffix(this.appendType(sb, SignaturePrinter.getElementType(type), name), type); case Type.OBJECT: - return this.appendType(sb, type.getClassName(), name); + return this.appendType(sb, SignaturePrinter.getClassName(type), name); default: sb.append(SignaturePrinter.getTypeName(type, false, this.fullyQualified)); if (name != null) { @@ -263,7 +263,7 @@ public class SignaturePrinter { } return sb; } - + /** * Get the source code name for the specified type * @@ -310,9 +310,10 @@ public class SignaturePrinter { case Type.FLOAT: return box ? "Float" : "float"; case Type.LONG: return box ? "Long" : "long"; case Type.DOUBLE: return box ? "Double" : "double"; - case Type.ARRAY: return SignaturePrinter.getTypeName(type.getElementType(), box, fullyQualified) + SignaturePrinter.arraySuffix(type); + case Type.ARRAY: + return SignaturePrinter.getTypeName(SignaturePrinter.getElementType(type), box, fullyQualified) + SignaturePrinter.arraySuffix(type); case Type.OBJECT: - String typeName = type.getClassName(); + String typeName = SignaturePrinter.getClassName(type); if (!fullyQualified) { typeName = typeName.substring(typeName.lastIndexOf('.') + 1); } @@ -322,11 +323,26 @@ public class SignaturePrinter { } } + private static Type getElementType(Type type) { + try { + return type.getElementType(); + } catch (Exception ex) { + return Type.getObjectType("InvalidType"); + } + } + + private static String getClassName(Type type) { + try { + return type.getClassName(); + } catch (Exception ex) { + return "InvalidType"; + } + } + private static String arraySuffix(Type type) { return Strings.repeat("[]", type.getDimensions()); } - private static StringBuilder appendArraySuffix(StringBuilder sb, Type type) { for (int i = 0; i < type.getDimensions(); i++) { sb.append("[]"); diff --git a/src/main/java/org/spongepowered/asm/util/asm/ASM.java b/src/main/java/org/spongepowered/asm/util/asm/ASM.java index 5174aaa5..87d38f6d 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/ASM.java +++ b/src/main/java/org/spongepowered/asm/util/asm/ASM.java @@ -38,6 +38,11 @@ public final class ASM { private static int minorVersion = 0; private static String maxVersion = "FALLBACK"; + private static int maxClassVersion = Opcodes.V1_6; + private static int maxClassMajorVersion = Opcodes.V1_6 & 0xFFFF; + private static int maxClassMinorVersion = (Opcodes.V1_6 >> 16) & 0xFFFF; + private static String maxJavaVersion = "V1.6"; + /** * The detected ASM API Version */ @@ -46,6 +51,15 @@ public final class ASM { private ASM() { } + /** + * Get whether the current ASM API is at least the specified version + * + * @param majorVersion version to check for (eg. 6) + */ + public static boolean isAtLeastVersion(int majorVersion) { + return ASM.majorVersion >= majorVersion; + } + /** * Get the major API version */ @@ -69,29 +83,72 @@ public final class ASM { return String.format("ASM %d.%d (%s)", ASM.majorVersion, ASM.minorVersion, ASM.maxVersion); } + /** + * Get the maximum supported class version (raw) + */ + public static int getMaxSupportedClassVersion() { + return ASM.maxClassVersion; + } + + /** + * Get the maximum supported major class versior + */ + public static int getMaxSupportedClassVersionMajor() { + return ASM.maxClassMajorVersion; + } + + /** + * Get the maximum supported minor class versior + */ + public static int getMaxSupportedClassVersionMinor() { + return ASM.maxClassMinorVersion; + } + + /** + * Get the supported java version as a string (mostly for the banner) + * + * @return Java class supported version as string + */ + public static String getClassVersionString() { + return String.format("Up to Java %s (class file version %d.%d)", ASM.maxJavaVersion, ASM.maxClassMajorVersion, ASM.maxClassMinorVersion); + } + private static int detectVersion() { int apiVersion = Opcodes.ASM4; for (Field field : Opcodes.class.getDeclaredFields()) { - if (field.getType() != Integer.TYPE || !field.getName().startsWith("ASM")) { + if (field.getType() != Integer.TYPE) { continue; } try { + String name = field.getName(); int version = field.getInt(null); - - // int patch = version & 0xFF; - int minor = (version >> 8) & 0xFF; - int major = (version >> 16) & 0xFF; - boolean experimental = ((version >> 24) & 0xFF) != 0; - - if (major >= ASM.majorVersion) { - ASM.maxVersion = field.getName(); - if (!experimental) { - apiVersion = version; - ASM.majorVersion = major; - ASM.minorVersion = minor; + if (name.startsWith("ASM")) { + // int patch = version & 0xFF; + int minor = (version >> 8) & 0xFF; + int major = (version >> 16) & 0xFF; + boolean experimental = ((version >> 24) & 0xFF) != 0; + + if (major >= ASM.majorVersion) { + ASM.maxVersion = name; + if (!experimental) { + apiVersion = version; + ASM.majorVersion = major; + ASM.minorVersion = minor; + } } + } else if (name.matches("V([0-9_]+)")) { + int minor = (version >> 16) & 0xFFFF; + int major = (version) & 0xFFFF; + if (major > ASM.maxClassMajorVersion || (major == ASM.maxClassMajorVersion && minor > ASM.maxClassMinorVersion)) { + ASM.maxClassMajorVersion = major; + ASM.maxClassMinorVersion = minor; + ASM.maxClassVersion = version; + ASM.maxJavaVersion = name.replace('_', '.').substring(1); + } + } else if ("ACC_PUBLIC".equals(name)) { + break; } } catch (ReflectiveOperationException ex) { throw new Error(ex); diff --git a/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java b/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java new file mode 100644 index 00000000..6f99bf48 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/ClassNodeAdapter.java @@ -0,0 +1,139 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.asm; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import org.objectweb.asm.tree.ClassNode; + +/** + * Adapter for ClassNode to access members added after ASM 5 + */ +public final class ClassNodeAdapter { + + private static final String NEST_HOST_FIELD = "nestHostClass"; + private static final String NEST_MEMBERS_FIELD = "nestMembers"; + private static final String EXPERIMENTAL_SUFFIX = "Experimental"; + + private static final Field fdNestHost = ClassNodeAdapter.getField(ClassNodeAdapter.NEST_HOST_FIELD); + private static final Field fdNestMembers = ClassNodeAdapter.getField(ClassNodeAdapter.NEST_MEMBERS_FIELD); + + private static boolean notSupported = false; + + private ClassNodeAdapter() { + } + + public static String getNestHostClass(ClassNode classNode) { + if (ASM.isAtLeastVersion(7)) { + return classNode.nestHostClass; + } + + if (ClassNodeAdapter.fdNestHost == null || ClassNodeAdapter.notSupported) { + return null; + } + + try { + return (String)ClassNodeAdapter.fdNestHost.get(classNode); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + return null; + } + } + + public static void setNestHostClass(ClassNode classNode, String nestHostClass) { + if (ASM.isAtLeastVersion(7)) { + classNode.nestHostClass = nestHostClass; + } + + if (ClassNodeAdapter.fdNestHost == null || ClassNodeAdapter.notSupported) { + return; + } + + try { + ClassNodeAdapter.fdNestHost.set(classNode, nestHostClass); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + } + } + + @SuppressWarnings("unchecked") + public static List getNestMembers(ClassNode classNode) { + if (ASM.isAtLeastVersion(7)) { + return classNode.nestMembers; + } + + if (ClassNodeAdapter.fdNestMembers == null || ClassNodeAdapter.notSupported) { + return null; + } + + try { + return (List)ClassNodeAdapter.fdNestMembers.get(classNode); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + return null; + } + } + + public static List getNestMembersAsList(ClassNode classNode) { + List nestMembers = ClassNodeAdapter.getNestMembers(classNode); + if (nestMembers == null) { + nestMembers = new ArrayList(); + ClassNodeAdapter.setNestMembers(classNode, nestMembers); + } + return nestMembers; + } + + public static void setNestMembers(ClassNode classNode, List nestMembers) { + if (ASM.isAtLeastVersion(7)) { + classNode.nestMembers = nestMembers; + } + + if (ClassNodeAdapter.fdNestMembers == null || ClassNodeAdapter.notSupported) { + return; + } + + try { + ClassNodeAdapter.fdNestMembers.set(classNode, nestMembers); + } catch (ReflectiveOperationException ex) { + ClassNodeAdapter.notSupported = true; + } + } + + private static Field getField(String fieldBaseName) { + try { + return ClassNode.class.getDeclaredField(fieldBaseName); + } catch (NoSuchFieldException ex) { + try { + return ClassNode.class.getDeclaredField(fieldBaseName + ClassNodeAdapter.EXPERIMENTAL_SUFFIX); + } catch (NoSuchFieldException ex1) { + ClassNodeAdapter.notSupported = true; + } + } + return null; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java b/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java deleted file mode 100644 index aa213c3e..00000000 --- a/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * This file is part of Mixin, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.asm.util.asm; - -import java.util.ArrayList; -import java.util.List; - -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldNode; -import org.objectweb.asm.tree.MethodNode; - -/** - * Holder for {@link FieldNode} and {@link MethodNode} for consumers which can - * handle both types (since they have a lot in common), with common accessors - * for overlapping properties. - * - * @param node type - */ -public abstract class ElementNode { - - /** - * ElementNode for MethodNode - */ - static class ElementNodeMethod extends ElementNode { - - private MethodNode method; - - ElementNodeMethod(ClassNode owner, MethodNode method) { - super(owner); - this.method = method; - } - - @Override - public boolean isMethod() { - return true; - } - - @Override - public MethodNode getMethod() { - return this.method; - } - - @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 String toString() { - return String.format("MethodElement[%s%s]", this.method.name, this.method.desc); - } - - } - - /** - * ElementNode for FieldNode - */ - static class ElementNodeField extends ElementNode { - - private FieldNode field; - - ElementNodeField(ClassNode owner, FieldNode field) { - super(owner); - this.field = field; - } - - @Override - public boolean isField() { - return true; - } - - @Override - public FieldNode getField() { - return this.field; - } - - @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 String toString() { - return String.format("FieldElement[%s:%s]", this.field.name, this.field.desc); - } - - } - - /** - * The class which owns this element, can be null - */ - private final ClassNode owner; - - protected ElementNode(ClassNode owner) { - this.owner = owner; - } - - /** - * Get whether this element is a method - */ - public boolean isMethod() { - return false; - } - - /** - * get whether this element is a field - */ - public boolean isField() { - return false; - } - - /** - * Get the {@link MethodNode} if this member is a method, otherwise returns - * null - */ - public MethodNode getMethod() { - return null; - } - - /** - * Get the {@link FieldNode} if this member is a field, otherwise returns - * null - */ - public FieldNode getField() { - return null; - } - - /** - * Get the element's owner, can be null - */ - public ClassNode getOwner() { - return this.owner; - } - - /** - * Get the element owner's name, if this element has an owner, otherwise - * returns null - */ - public String getOwnerName() { - return this.owner != null ? this.owner.name : null; - } - - /** - * Get the element name - */ - public abstract String getName(); - - /** - * Get the element descriptor - */ - public abstract String getDesc(); - - /** - * Get the element signature, can be null - */ - public abstract String getSignature(); - - /** - * Returns the node with horrible duck typing - */ - public abstract TNode get(); - - /** - * Create an ElementNode wrapper for the supplied method node - * - * @param owner class which owns the method or null - * @param method Method node to wrap - * @return ElementNode - */ - public static ElementNode 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 null - * @param field Field node to wrap - * @return ElementNode - */ - public static ElementNode 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 null - * @param node Node to wrap - * @param Node type - * @return ElementNode - * @throws IllegalArgumentException if the supplied argument is not a - * {@link MethodNode} or {@link FieldNode} - */ - @SuppressWarnings("unchecked") - public static ElementNode of(ClassNode owner, TNode node) { - if (node instanceof MethodNode) { - return (ElementNode)new ElementNodeMethod(owner, (MethodNode)node); - } else if (node instanceof FieldNode) { - return (ElementNode)new ElementNodeField(owner, (FieldNode)node); - } - throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName()); - } - - /** - * Convert the supplied list of nodes to a list of wrapped ElementNodes - * - * @param owner Owner of the supplied nodes, can be null - * @param list List of nodes - * @param Node type - * @return List of wrapped nodes - */ - public static List> listOf(ClassNode owner, List list) { - List> nodes = new ArrayList>(); - for (TNode node : list) { - nodes.add(ElementNode.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 null - * @return List of wrapped nodes - */ - public static List> fieldList(ClassNode owner) { - List> fields = new ArrayList>(); - 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 null - * @return List of wrapped nodes - */ - public static List> methodList(ClassNode owner) { - List> methods = new ArrayList>(); - for (MethodNode method : owner.methods) { - methods.add(new ElementNodeMethod(owner, method)); - } - return methods; - } - -} diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java new file mode 100644 index 00000000..0a450969 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotatedElement.java @@ -0,0 +1,43 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.asm; + +import java.lang.annotation.Annotation; + +/** + * Interface for objects which can be annotated since main classes may need to + * read info from mirror annotations in the AP + */ +public interface IAnnotatedElement { + + /** + * Get annotation from element + * + * @param annotationClass Annotation class to retrieve + * @return annotation handle + */ + public abstract IAnnotationHandle getAnnotation(Class annotationClass); + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java new file mode 100644 index 00000000..a62bc28b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -0,0 +1,134 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.asm; + +import java.util.List; + +import javax.lang.model.type.TypeMirror; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; + +/** + * Interface for annotation handle since some classes may need to read info from + * both ASM {@link AnnotationNode}s at runtime and mirror annotations in the AP + * at compile time. + */ +public interface IAnnotationHandle { + + /** + * Get whether the annotation inside the handle actually exists, if the + * contained element is null, returns false. + * + * @return true if the annotation exists + */ + public abstract boolean exists(); + + /** + * Get the annotation descriptor + */ + public abstract String getDesc(); + + /** + * Retrieve an annotation key as a list of annotation handles + * + * @param key key to fetch + * @return list of annotations + */ + public abstract List getAnnotationList(String key); + + /** + * Get an annotation value as an ASM {@link Type}. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. + * + * @param key key to fetch + * @return value + */ + public abstract Type getTypeValue(String key); + + /** + * Retrieve an annotation key as a list of Types. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. + * + * @param key key to fetch + * @return list of types + */ + public abstract List getTypeList(String key); + + /** + * Get an annotation value as an annotation handle + * + * @param key key to search for in the value map + * @return value or null if not set + */ + public abstract IAnnotationHandle getAnnotation(String key); + + /** + * Get a value with the specified key from this annotation, return the + * specified default value if the key is not set or is not present + * + * @param key key + * @param defaultValue value to return if the key is not set or not present + * @param duck type + * @return value or default if not set + */ + public abstract T getValue(String key, T defaultValue); + + /** + * Get the annotation value or return null if not present or not set + * + * @param duck type + * @return value or null if not present or not set + */ + public abstract T getValue(); + + /** + * Get the annotation value with the specified key or return null if not + * present or not set + * + * @param key key to fetch + * @param duck type + * @return value or null if not present or not set + */ + public abstract T getValue(String key); + + /** + * Retrieve the annotation value with the specified key as a list with + * values of the specified type. Returns an empty list if the value is not + * present or not set. + * + * @param key key to fetch + * @param list element duck type + * @return list of values + */ + public abstract List getList(String key); + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/package-info.java b/src/main/java/org/spongepowered/asm/util/asm/package-info.java new file mode 100644 index 00000000..6fe9322f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Utilities, abstractions and specialised subclasses used by Mixin for + * interacting with ASM. + */ +package org.spongepowered.asm.util.asm; diff --git a/src/main/java/org/spongepowered/asm/util/logging/package-info.java b/src/main/java/org/spongepowered/asm/util/logging/package-info.java new file mode 100644 index 00000000..387fd39f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/logging/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Logging abstraction to provide a unified logging interface for classes which + * operate both at runtime and in the AP. + */ +package org.spongepowered.asm.util.logging; diff --git a/src/main/java/org/spongepowered/asm/util/package-info.java b/src/main/java/org/spongepowered/asm/util/package-info.java new file mode 100644 index 00000000..1ab1784e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 used by the entire Mixin pipeline, including utilities for + * working with bytecode as well as general-purpose tools and parsers. + */ +package org.spongepowered.asm.util; diff --git a/src/main/java/org/spongepowered/asm/util/perf/package-info.java b/src/main/java/org/spongepowered/asm/util/perf/package-info.java new file mode 100644 index 00000000..2c054f95 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/perf/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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. + */ + +/** + * Performance profiling for Mixin. + */ +package org.spongepowered.asm.util.perf; diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java index 1feedbab..857468cc 100644 --- a/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java +++ b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.service.modlauncher.MixinServiceModLauncher; import org.spongepowered.asm.service.modlauncher.ModLauncherAuditTrail; +import org.spongepowered.asm.transformers.MixinClassReader; import com.google.common.io.Resources; @@ -229,7 +230,7 @@ public class MixinLaunchPlugin implements ILaunchPluginService, IClassBytecodePr } ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(classBytes); + ClassReader classReader = new MixinClassReader(classBytes, name); classReader.accept(classNode, ClassReader.EXPAND_FRAMES); return classNode; } diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java index 700897d5..37bf650f 100644 --- a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java +++ b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java @@ -24,8 +24,10 @@ */ package org.spongepowered.asm.launch.platform; +import java.lang.reflect.Method; import java.util.Collection; import java.util.Locale; +import java.util.Optional; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.util.Constants; @@ -33,12 +35,18 @@ import org.spongepowered.asm.util.Constants; import cpw.mods.modlauncher.Environment; import cpw.mods.modlauncher.Launcher; import cpw.mods.modlauncher.api.IEnvironment; +import cpw.mods.modlauncher.api.ILaunchHandlerService; /** * Platform agent for minecraft forge under ModLauncher, only detects the side */ public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent { + /** + * getDist method name in launch handler + */ + private static final String GET_DIST_METHOD = "getDist"; + /* (non-Javadoc) * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent * #init() @@ -72,6 +80,22 @@ public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract if (launchTarget.contains("client")) { return Constants.SIDE_CLIENT; } + Optional launchHandler = environment.findLaunchHandler(launchTarget); + if (launchHandler.isPresent()) { + ILaunchHandlerService service = launchHandler.get(); + try { + Method mdGetDist = service.getClass().getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_DIST_METHOD); + String strDist = mdGetDist.invoke(service).toString().toLowerCase(Locale.ROOT); + if (strDist.contains("server")) { + return Constants.SIDE_SERVER; + } + if (strDist.contains("client")) { + return Constants.SIDE_CLIENT; + } + } catch (Exception ex) { + return null; + } + } return null; } diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java index c7782f6e..80791f9e 100644 --- a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java @@ -31,11 +31,12 @@ import org.spongepowered.asm.launch.IClassProcessor; import org.spongepowered.asm.launch.platform.container.ContainerHandleModLauncher; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; -import org.spongepowered.asm.mixin.transformer.MixinTransformationHandler; +import org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory; import org.spongepowered.asm.service.IClassBytecodeProvider; import org.spongepowered.asm.service.IClassProvider; import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.IMixinAuditTrail; +import org.spongepowered.asm.service.IMixinInternal; import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinServiceAbstract; import org.spongepowered.asm.util.IConsumer; @@ -114,6 +115,14 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { public void onStartup() { this.phaseConsumer.accept(Phase.DEFAULT); } + + @Override + public void offer(IMixinInternal internal) { + if (internal instanceof IMixinTransformerFactory) { + this.getTransformationHandler().offer((IMixinTransformerFactory)internal); + } + super.offer(internal); + } // TEMP @SuppressWarnings("deprecation") @@ -212,7 +221,7 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { /** * Get (or create) the transformation handler */ - private IClassProcessor getTransformationHandler() { + private MixinTransformationHandler getTransformationHandler() { if (this.transformationHandler == null) { this.transformationHandler = new MixinTransformationHandler(); } diff --git a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java similarity index 76% rename from src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java rename to src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java index 303efd2e..303e1c7e 100644 --- a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinTransformationHandler.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; +package org.spongepowered.asm.service.modlauncher; import java.util.EnumSet; @@ -32,9 +32,13 @@ import org.spongepowered.asm.launch.IClassProcessor; import org.spongepowered.asm.launch.MixinLaunchPlugin; import org.spongepowered.asm.launch.Phases; import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.transformer.IMixinTransformer; +import org.spongepowered.asm.mixin.transformer.IMixinTransformerFactory; import org.spongepowered.asm.service.ISyntheticClassInfo; import org.spongepowered.asm.service.ISyntheticClassRegistry; +import com.google.common.base.Preconditions; + import cpw.mods.modlauncher.api.ITransformerActivity; import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; @@ -43,16 +47,16 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; * application, post processing and synthetic class generation */ public class MixinTransformationHandler implements IClassProcessor { - + /** - * Lock for initialising the transformer + * Mixin transformer factory, from service */ - private final Object initialisationLock = new Object(); + private IMixinTransformerFactory transformerFactory; /** * Transformer pipeline instance */ - private MixinTransformer transformer; + private IMixinTransformer transformer; /** * Synthetic class registry, used so the processor knows when to respond to @@ -60,6 +64,11 @@ public class MixinTransformationHandler implements IClassProcessor { */ private ISyntheticClassRegistry registry; + void offer(IMixinTransformerFactory transformerFactory) { + Preconditions.checkNotNull(transformerFactory, "transformerFactory"); + this.transformerFactory = transformerFactory; + } + /* (non-Javadoc) * @see org.spongepowered.asm.launch.IClassProcessor#handlesClass( * org.objectweb.asm.Type, boolean, java.lang.String) @@ -89,18 +98,13 @@ public class MixinTransformationHandler implements IClassProcessor { if (phase == Phase.BEFORE) { return false; } - - MixinTransformer transformer = null; + if (this.transformer == null) { - synchronized (this.initialisationLock) { - transformer = this.transformer; - if (transformer == null) { - transformer = this.transformer = new MixinTransformer(); - this.registry = transformer.getExtensions().getSyntheticClassRegistry(); - } + if (this.transformerFactory == null) { + throw new IllegalStateException("processClass called before transformer factory offered to transformation handler"); } - } else { - transformer = this.transformer; + this.transformer = this.transformerFactory.createTransformer(); + this.registry = this.transformer.getExtensions().getSyntheticClassRegistry(); } // Don't transform when the reason is mixin (side-loading in progress) @@ -111,14 +115,14 @@ public class MixinTransformationHandler implements IClassProcessor { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); ISyntheticClassInfo syntheticClass = this.registry.findSyntheticClass(classType.getClassName()); if (syntheticClass != null) { - return transformer.generateClass(environment, classType.getClassName(), classNode); + return this.transformer.generateClass(environment, classType.getClassName(), classNode); } if (ITransformerActivity.COMPUTING_FRAMES_REASON.equals(reason)) { - return transformer.computeFramesForClass(environment, classType.getClassName(), classNode); + return this.transformer.computeFramesForClass(environment, classType.getClassName(), classNode); } - return transformer.transformClass(environment, classType.getClassName(), classNode); + return this.transformer.transformClass(environment, classType.getClassName(), classNode); } }