Skip to content

Commit

Permalink
Reintroduce Superclass Transformations
Browse files Browse the repository at this point in the history
Properly reintroduces superclass transformers with
ModLauncher's ITransformer api. There are some quirks with
needing to accept transforming classes multiple times based
on voting contexts. This functions as expected in both
development and production cases from limited testing.

Signed-off-by: Gabriel Harris-Rouquette <gabizou@me.com>
  • Loading branch information
gabizou committed Feb 17, 2022
1 parent 54093b7 commit ed4a0bd
Show file tree
Hide file tree
Showing 13 changed files with 274 additions and 244 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,14 @@
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.ModDirTransformerDiscoverer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.transformers.modlauncher.AccessWidenerTransformationService;
import org.spongepowered.transformers.modlauncher.SuperclassChanger;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Supplier;
Expand Down Expand Up @@ -90,11 +91,12 @@ public void initialize(final IEnvironment environment) {
throw new RuntimeException("Failed to register SpongeForge", ex);
}
// Register SF as an AW
final Optional<AccessWidenerTransformationService> aw = environment.getProperty(AccessWidenerTransformationService.INSTANCE.get());
if (aw.isPresent()) {
// todo: actually read this from the jar manifest
aw.get().offerResource(ForgeProductionBootstrap.class.getResource("/common.accesswidener"), "SpongeForge injected");
}
// todo: actually read this from the jar manifest
environment.getProperty(AccessWidenerTransformationService.INSTANCE.get()).ifPresent(aWTS ->
aWTS.offerResource(ForgeProductionBootstrap.class.getResource("/common.accesswidener"), "SpongeForge injected"));
environment.getProperty(SuperclassChanger.INSTANCE.get()).ifPresent(scc -> {
scc.offerResource(ForgeProductionBootstrap.class.getResource("/common.superclasschange"), "SpongeForge injected");
});
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
org.spongepowered.forge.applaunch.service.AccessWidenerTransformationService
org.spongepowered.forge.applaunch.service.ForgeProductionBootstrap
org.spongepowered.forge.applaunch.service.ForgeProductionBootstrap
4 changes: 3 additions & 1 deletion forge/src/mixins/resources/mixins.spongeforge.core.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
"minecraftforge.fml.ModContainerMixin_Forge",
"minecraftforge.util.ITeleporterMixin_Forge",
"server.BootstrapMixin_Forge",
"server.MainMixin_Forge",
"server.MinecraftServerMixin_Forge",
"server.level.ServerLevelMixin_Timings_Forge",
"server.level.ServerPlayerMixin_Forge",
Expand All @@ -40,5 +39,8 @@
"client": [
"client.MinecraftMixin_Forge",
"client.main.MainMixin_Forge"
],
"server": [
"server.MainMixin_Forge"
]
}
1 change: 1 addition & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ projectDescription=The SpongeAPI implementation targeting vanilla Minecraft and
mixinConfigs=mixins.sponge.accessors.json,mixins.sponge.api.json,mixins.sponge.concurrent.json,mixins.sponge.core.json,\
mixins.sponge.entityactivation.json,mixins.sponge.exploit.json,mixins.sponge.inventory.json,mixins.sponge.movementcheck.json,\
mixins.sponge.tracker.json,mixins.sponge.ipforward.json,mixins.sponge.optimization.json
superClassChanges=common.superclasschange

minecraftVersion=1.16.5
recommendedVersion=0-SNAPSHOT
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.forge.applaunch.service;
package org.spongepowered.transformers.modlauncher;

import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ITransformationService;
Expand All @@ -38,7 +38,9 @@
import net.fabricmc.accesswidener.AccessWidenerVisitor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
Expand All @@ -55,17 +57,18 @@
import java.util.function.BiFunction;
import java.util.function.Supplier;

@DefaultQualifier(NonNull.class)
public class AccessWidenerTransformationService implements ITransformationService {

public static final String NAME = "access_widener";
public static final String ACCESS_WIDENER_EXTENSION = "accesswidener";
public static final Supplier<TypesafeMap.Key<AccessWidenerTransformationService>>
INSTANCE = IEnvironment.buildKey("sponge:aw", AccessWidenerTransformationService.class);
private static final Logger LOGGER = LogManager.getLogger();
static final Logger LOGGER = LogManager.getLogger();

private final AccessWidener widener = new AccessWidener();
private final AccessWidenerReader reader = new AccessWidenerReader(this.widener);
private OptionSpec<String> configSpec;
private @MonotonicNonNull OptionSpec<String> configSpec;

@NonNull
@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.transformers.modlauncher;

import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.ITransformationService;
import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerActivity;
import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult;
import cpw.mods.modlauncher.api.TypesafeMap;
import io.leangen.geantyref.TypeToken;
import joptsimple.OptionSpec;
import joptsimple.OptionSpecBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.configurate.jackson.JacksonConfigurationLoader;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@DefaultQualifier(NonNull.class)
public class SuperclassChanger implements ITransformationService {

public static final int ASM_VERSION = Opcodes.ASM9;
public static final String NAME = "superclass_change";
public static final String SUPER_CLASS_EXTENSION = "superclasschange";
// Pulled from org.spongepowered.asm.launch.MixinLaunchPluginLegacy as
// when Mixin prepares target class nodes, it requests other ITransformers
// to load changes as necessary.
public static final String MIXIN_PLUGIN_REASON = "mixin";
public static final Supplier<TypesafeMap.Key<SuperclassChanger>>
INSTANCE = IEnvironment.buildKey("sponge:scc", SuperclassChanger.class);
static final Logger LOGGER = LogManager.getLogger();
private static final TypeToken<Map<String, String>> CONFIG_TOKEN = new TypeToken<Map<String, String>>() {
};

private @MonotonicNonNull OptionSpec<String> configSpec;
private final Map<String, String> superclassTargets = new ConcurrentHashMap<>();

@NonNull
@Override
public String name() {
return SuperclassChanger.NAME;
}

@Override
public void onLoad(final IEnvironment env, final Set<String> otherServices) {
env.computePropertyIfAbsent(SuperclassChanger.INSTANCE.get(), k -> this);
}

@Override
public void arguments(final BiFunction<String, String, OptionSpecBuilder> argumentBuilder) {
this.configSpec = argumentBuilder.apply("config", "An SCC file to apply at runtime")
.withRequiredArg()
.ofType(String.class);
}

@Override
public void argumentValues(final OptionResult option) {
option.values(this.configSpec).forEach(file -> {
SuperclassChanger.LOGGER.debug("Loading SCC file: " + file);
final @Nullable URL resource = SuperclassChanger.class.getClassLoader().getResource(file);
if (resource == null) {
SuperclassChanger.LOGGER.warn("Could not find SCC file: " + file);
return;
}
this.offerResource(resource, "command-line");
});
}

@Override
public void initialize(final IEnvironment environment) {
}

@Override
public void beginScanning(final IEnvironment environment) {
}

@Override
@SuppressWarnings("rawtypes") // :(
public @NonNull List<ITransformer> transformers() {
return Collections.singletonList(
new SuperclassTransformer(SuperclassChanger.ASM_VERSION, new ConcurrentHashMap<>(this.superclassTargets)));
}

// register additional AWs with the transformation service
public void offerResource(final URL resource, final String name) {
if (resource.getFile().endsWith(SuperclassChanger.SUPER_CLASS_EXTENSION)) {
try {
SuperclassChanger.LOGGER.debug("Reading superclass change {} from {}", name, resource);
@Nullable final Map<String, String> superClassTargets = JacksonConfigurationLoader.builder()
.url(resource)
.build()
.load()
.get(SuperclassChanger.CONFIG_TOKEN);
if (superClassTargets != null) {
this.superclassTargets.putAll(superClassTargets);
}
} catch (final IOException ex) {
SuperclassChanger.LOGGER.error("Failed to load superclass change {} from {}", name, resource, ex);
}
} else {
SuperclassChanger.LOGGER.warn(
"Offered superclass change {} from {} that does not end with expected extension '{}'",
name, resource, SuperclassChanger.SUPER_CLASS_EXTENSION
);
}
}

static class SuperclassTransformer implements ITransformer<ClassNode> {

private final int asmVersion;
private final ConcurrentHashMap<String, String> superclassTargets;

public SuperclassTransformer(final int asmVersion, final ConcurrentHashMap<String, String> superclassTargets) {
this.asmVersion = asmVersion;
this.superclassTargets = superclassTargets;
}

@Override
public @NonNull ClassNode transform(final ClassNode input, final ITransformerVotingContext context) {
final String inputKey = input.name.replace("/", ".");
final String newSuperclass = this.superclassTargets.get(inputKey);
if (newSuperclass == null) {
SuperclassChanger.LOGGER.warn("No superclass change for {}", inputKey);
return input;
}
final String sanitizedSuperClass = newSuperclass.replace('.', '/');

input.methods.forEach(m -> SuperclassTransformer.transformMethod(m, input.superName, sanitizedSuperClass));
input.superName = sanitizedSuperClass;
return input;
}

private static void transformMethod(
final MethodNode node, final String originalSuperclass, final String superClass
) {
for (final MethodInsnNode insn : SuperclassTransformer.findSuper(node, originalSuperclass)) {
insn.owner = superClass;
}
}

private static List<MethodInsnNode> findSuper(
final MethodNode method, final String originalSuperClass
) {
final List<MethodInsnNode> nodes = new ArrayList<>();
for (final AbstractInsnNode node : method.instructions.toArray()) {
if (node.getOpcode() == Opcodes.INVOKESPECIAL && originalSuperClass.equals(
((MethodInsnNode) node).owner)) {
nodes.add((MethodInsnNode) node);
}
}
return nodes;
}

@Override
public @NonNull TransformerVoteResult castVote(final ITransformerVotingContext context) {
switch (context.getReason()) {
case ITransformerActivity.CLASSLOADING_REASON:
case SuperclassChanger.MIXIN_PLUGIN_REASON:
return TransformerVoteResult.YES;
default:
return TransformerVoteResult.NO;
}
}

@Override
public @NonNull Set<Target> targets() {
return this.superclassTargets
.keySet()
.stream()
.map(s -> s.replace('.', '/'))
.map(Target::targetClass)
.collect(Collectors.toSet());
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
org.spongepowered.transformers.modlauncher.SuperclassChanger
org.spongepowered.transformers.modlauncher.AccessWidenerTransformationService
6 changes: 6 additions & 0 deletions src/main/resources/common.superclasschange
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"org.spongepowered.api.event.cause.entity.damage.source.common.AbstractDamageSource": "org.spongepowered.common.event.cause.entity.damage.SpongeCommonDamageSource",
"org.spongepowered.api.event.cause.entity.damage.source.common.AbstractEntityDamageSource": "org.spongepowered.common.event.cause.entity.damage.SpongeCommonEntityDamageSource",
"org.spongepowered.api.event.cause.entity.damage.source.common.AbstractIndirectEntityDamageSource": "org.spongepowered.common.event.cause.entity.damage.SpongeCommonIndirectEntityDamageSource",
"org.spongepowered.api.entity.ai.goal.AbstractGoal": "net.minecraft.world.entity.ai.goal.Goal"
}
Loading

0 comments on commit ed4a0bd

Please sign in to comment.