Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Config for method removal via asm #239

Merged
merged 10 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/classes/GenericRecipeCategory.groovy
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// side: client

package classes

import classes.SimpleConversionRecipe
Expand Down
10 changes: 10 additions & 0 deletions examples/sideOnly.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"client": {
"classes": [
"net.minecraftforge.fml.client.config.GuiConfig1"
]
},
"server": {

}
}
11 changes: 8 additions & 3 deletions src/main/java/com/cleanroommc/groovyscript/GroovyScript.java
Original file line number Diff line number Diff line change
Expand Up @@ -142,12 +142,17 @@ public void onRegisterItem(RegistryEvent.Register<Item> event) {

@ApiStatus.Internal
public static void initializeRunConfig(File minecraftHome) {
GroovyScript.minecraftHome = minecraftHome;
try {
GroovyScript.minecraftHome = minecraftHome.getCanonicalFile();
} catch (IOException e) {
GroovyLog.get().errorMC("Failed to canonicalize minecraft home path '" + minecraftHome + "'!");
throw new RuntimeException(e);
}
// If we are launching with the environment variable set to use the examples folder, use the examples folder for easy and consistent testing.
if (Boolean.parseBoolean(System.getProperty("groovyscript.use_examples_folder"))) {
scriptPath = new File(minecraftHome.getParentFile(), "examples");
scriptPath = new File(GroovyScript.minecraftHome.getParentFile(), "examples");
} else {
scriptPath = new File(minecraftHome, "groovy");
scriptPath = new File(GroovyScript.minecraftHome, "groovy");
}
try {
scriptPath = scriptPath.getCanonicalFile();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.Map;

@IFMLLoadingPlugin.Name("GroovyScript-Core")
@IFMLLoadingPlugin.SortingIndex(Integer.MIN_VALUE + 10)
@IFMLLoadingPlugin.MCVersion(ForgeVersion.mcVersion)
public class GroovyScriptCore implements IFMLLoadingPlugin, IEarlyMixinLoader {

Expand All @@ -35,6 +36,7 @@ public String getSetupClass() {
@Override
public void injectData(Map<String, Object> data) {
source = (File) data.getOrDefault("coremodLocation", null);
SideOnlyConfig.init();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,123 @@

import com.cleanroommc.groovyscript.core.visitors.*;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import org.objectweb.asm.*;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;

import java.util.*;

public class GroovyScriptTransformer implements IClassTransformer {

@Override
public byte[] transform(String name, String transformedName, byte[] classBytes) {
public byte[] transform(String name, String transformedName, byte[] bytes) {
if (bytes == null) return null;
switch (name) {
case InvokerHelperVisitor.CLASS_NAME: {
ClassWriter classWriter = new ClassWriter(0);
new ClassReader(classBytes).accept(new InvokerHelperVisitor(classWriter), 0);
new ClassReader(bytes).accept(new InvokerHelperVisitor(classWriter), 0);
return classWriter.toByteArray();
}
case CachedClassMethodsVisitor.CLASS_NAME: {
ClassWriter classWriter = new ClassWriter(0);
new ClassReader(classBytes).accept(new CachedClassMethodsVisitor(classWriter), 0);
new ClassReader(bytes).accept(new CachedClassMethodsVisitor(classWriter), 0);
return classWriter.toByteArray();
}
case CachedClassFieldsVisitor.CLASS_NAME: {
ClassWriter classWriter = new ClassWriter(0);
new ClassReader(classBytes).accept(new CachedClassFieldsVisitor(classWriter), 0);
new ClassReader(bytes).accept(new CachedClassFieldsVisitor(classWriter), 0);
return classWriter.toByteArray();
}
case CachedClassConstructorsVisitor.CLASS_NAME: {
ClassWriter classWriter = new ClassWriter(0);
new ClassReader(classBytes).accept(new CachedClassConstructorsVisitor(classWriter), 0);
new ClassReader(bytes).accept(new CachedClassConstructorsVisitor(classWriter), 0);
return classWriter.toByteArray();
}
case StaticVerifierVisitor.CLASS_NAME: {
ClassWriter classWriter = new ClassWriter(0);
new ClassReader(classBytes).accept(new StaticVerifierVisitor(classWriter), 0);
new ClassReader(bytes).accept(new StaticVerifierVisitor(classWriter), 0);
return classWriter.toByteArray();
}
}
return classBytes;
return transformSideOnly(transformedName, bytes);
}

private byte[] transformSideOnly(String className, byte[] bytes) {
SideOnlyConfig.MethodSet bannedProperties = SideOnlyConfig.getRemovedProperties(FMLLaunchHandler.side(), className);
if (bannedProperties == null) return bytes;
if (bannedProperties.bannsClass) {
throw new RuntimeException(String.format("Attempted to load class %s for invalid side %s", className, FMLLaunchHandler.side().name()));
}

ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);

classNode.fields.removeIf(field -> bannedProperties.contains(field.name));

LambdaGatherer lambdaGatherer = new LambdaGatherer();
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
if (bannedProperties.contains(method.name + "()")) {
brachy84 marked this conversation as resolved.
Show resolved Hide resolved
methods.remove();
lambdaGatherer.accept(method);
}
}

// remove dynamic synthetic lambda methods that are inside of removed methods
for (List<Handle> dynamicLambdaHandles = lambdaGatherer.getDynamicLambdaHandles(); !dynamicLambdaHandles.isEmpty(); dynamicLambdaHandles = lambdaGatherer.getDynamicLambdaHandles()) {
lambdaGatherer = new LambdaGatherer();
methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
if ((method.access & Opcodes.ACC_SYNTHETIC) == 0) continue;
for (Handle dynamicLambdaHandle : dynamicLambdaHandles) {
if (method.name.equals(dynamicLambdaHandle.getName()) && method.desc.equals(dynamicLambdaHandle.getDesc())) {
methods.remove();
lambdaGatherer.accept(method);
}
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}

private static class LambdaGatherer extends MethodVisitor {

private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
false);
private final List<Handle> dynamicLambdaHandles = new ArrayList<Handle>();

public LambdaGatherer() {
super(Opcodes.ASM5);
}

public void accept(MethodNode method) {
ListIterator<AbstractInsnNode> insnNodeIterator = method.instructions.iterator();
while (insnNodeIterator.hasNext()) {
AbstractInsnNode insnNode = insnNodeIterator.next();
if (insnNode.getType() == AbstractInsnNode.INVOKE_DYNAMIC_INSN) {
insnNode.accept(this);
}
}
}

@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
if (META_FACTORY.equals(bsm)) {
Handle dynamicLambdaHandle = (Handle) bsmArgs[1];
dynamicLambdaHandles.add(dynamicLambdaHandle);
}
}

public List<Handle> getDynamicLambdaHandles() {
return dynamicLambdaHandles;
}
}
}
120 changes: 120 additions & 0 deletions src/main/java/com/cleanroommc/groovyscript/core/SideOnlyConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package com.cleanroommc.groovyscript.core;

import com.cleanroommc.groovyscript.GroovyScript;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
import net.minecraftforge.fml.relauncher.Side;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class SideOnlyConfig {

private static final MethodSet CLASS_MARKER = new MethodSet(true);
private static final Map<String, MethodSet> clientRemovals = new Object2ObjectOpenHashMap<>();
private static final Map<String, MethodSet> serverRemovals = new Object2ObjectOpenHashMap<>();

public static void clientOnly(String className, String member) {
serverRemovals.computeIfAbsent(className, k -> new MethodSet(false)).add(member);
brachy84 marked this conversation as resolved.
Show resolved Hide resolved
}

public static void serverOnly(String className, String member) {
clientRemovals.computeIfAbsent(className, k -> new MethodSet(false)).add(member);
}

static void init() {
clientOnly("net.minecraftforge.common.config.Configuration", "setCategoryConfigEntryClass()");

initConfig((File) FMLInjectionData.data()[6]);
}

private static void initConfig(File minecraftHome) {
File scriptPath;
if (Boolean.parseBoolean(System.getProperty("groovyscript.use_examples_folder"))) {
scriptPath = new File(minecraftHome.getParentFile(), "examples");
} else {
scriptPath = new File(minecraftHome, "groovy");
}
File sideOnlyConfig = new File(scriptPath, "sideOnly.json");
brachy84 marked this conversation as resolved.
Show resolved Hide resolved
JsonObject json;
try {
if (!sideOnlyConfig.isFile()) return;
Reader reader = new InputStreamReader(new FileInputStream(sideOnlyConfig), StandardCharsets.UTF_8);
JsonElement jsonElement = new JsonParser().parse(new JsonReader(reader));
reader.close();
if (jsonElement instanceof JsonObject jsonObject) {
json = jsonObject;
} else {
return;
}
} catch (Exception e) {
GroovyScript.LOGGER.error("Failed to read file on path {}", sideOnlyConfig, e);
return;
}
if (json.has("client")) {
readConfig(serverRemovals, json.getAsJsonObject("client"));
}
if (json.has("server")) {
readConfig(clientRemovals, json.getAsJsonObject("server"));
}
for (String key : new String[]{"common", "both", "all"}) {
brachy84 marked this conversation as resolved.
Show resolved Hide resolved
if (json.has(key)) {
Map<String, MethodSet> commonRemovals = new Object2ObjectOpenHashMap<>();
readConfig(commonRemovals, json.getAsJsonObject(key));
for (var entry : commonRemovals.entrySet()) {
if (entry.getValue().bannsClass) {
clientRemovals.put(entry.getKey(), CLASS_MARKER);
serverRemovals.put(entry.getKey(), CLASS_MARKER);
} else {
clientRemovals.computeIfAbsent(entry.getKey(), k -> new MethodSet(false)).addAll(entry.getValue());
serverRemovals.computeIfAbsent(entry.getKey(), k -> new MethodSet(false)).addAll(entry.getValue());
}
}
break;
}
}
}

private static void readConfig(Map<String, MethodSet> removals, JsonObject json) {
if (json.size() == 0) return;
for (var entry : json.entrySet()) {
if ("classes".equals(entry.getKey())) {
for (JsonElement je : entry.getValue().getAsJsonArray()) {
removals.put(je.getAsString(), CLASS_MARKER);
}
continue;
}
MethodSet properties = removals.computeIfAbsent(entry.getKey(), k -> new MethodSet(false));
if (properties.bannsClass) continue;
if (entry.getValue().isJsonArray()) {
for (JsonElement je : entry.getValue().getAsJsonArray()) {
properties.add(je.getAsString());
}
} else if (entry.getValue().isJsonPrimitive()) {
properties.add(entry.getValue().getAsString());
}
}
}

public static MethodSet getRemovedProperties(Side side, String clazz) {
return side.isClient() ? clientRemovals.get(clazz) : serverRemovals.get(clazz);
}

public static class MethodSet extends ObjectOpenHashSet<String> {

public final boolean bannsClass;
brachy84 marked this conversation as resolved.
Show resolved Hide resolved

public MethodSet(boolean bannsClass) {
this.bannsClass = bannsClass;
}
}
}