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 all 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": {

}
}
64 changes: 17 additions & 47 deletions src/main/java/com/cleanroommc/groovyscript/GroovyScript.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand All @@ -61,7 +62,6 @@

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
Expand All @@ -86,12 +86,8 @@ public class GroovyScript {

public static final Logger LOGGER = LogManager.getLogger(ID);

private static File minecraftHome;
private static File scriptPath;
private static File runConfigFile;
private static File resourcesFile;
private static RunConfig runConfig;
private static GroovyScriptSandbox sandbox;
private static RunConfig runConfig;
private static ModContainer scriptMod;
private static Thread languageServerThread;

Expand All @@ -102,6 +98,10 @@ public class GroovyScript {

@Mod.EventHandler
public void onConstruction(FMLConstructionEvent event) {
if (!SandboxData.isInitialised()) {
LOGGER.throwing(new IllegalStateException("Sandbox data should have been initialised by now, but isn't! Try Initialising again."));
SandboxData.initialize((File) FMLInjectionData.data()[6], LOGGER);
}
MinecraftForge.EVENT_BUS.register(this);
MinecraftForge.EVENT_BUS.register(EventHandler.class);
NetworkHandler.init();
Expand All @@ -110,11 +110,7 @@ public void onConstruction(FMLConstructionEvent event) {
GroovyDeobfMapper.init();
LinkGeneratorHooks.init();
ReloadableRegistryManager.init();
try {
sandbox = new GroovyScriptSandbox(scriptPath, FileUtil.makeFile(FileUtil.getMinecraftHome(), "cache", "groovy"));
} catch (MalformedURLException e) {
throw new IllegalStateException("Error initializing sandbox!");
}
GroovyScript.sandbox = new GroovyScriptSandbox();
ModSupport.INSTANCE.setup(event.getASMHarvestedData());

if (NetworkUtils.isDedicatedClient()) {
Expand Down Expand Up @@ -143,21 +139,7 @@ public void onRegisterItem(RegistryEvent.Register<Item> event) {

@ApiStatus.Internal
public static void initializeRunConfig(File minecraftHome) {
GroovyScript.minecraftHome = minecraftHome;
// 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");
} else {
scriptPath = new File(minecraftHome, "groovy");
}
try {
scriptPath = scriptPath.getCanonicalFile();
} catch (IOException e) {
GroovyLog.get().error("Failed to canonicalize groovy script path '" + scriptPath + "'!");
GroovyLog.get().exception(e);
}
runConfigFile = new File(scriptPath, "runConfig.json");
resourcesFile = new File(scriptPath, "assets");
SandboxData.initialize(minecraftHome, LOGGER);
reloadRunConfig(true);
}

Expand Down Expand Up @@ -224,40 +206,28 @@ public static String getScriptPath() {

@NotNull
public static File getMinecraftHome() {
if (minecraftHome == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return minecraftHome;
return SandboxData.getMinecraftHome();
}

@NotNull
public static File getScriptFile() {
if (scriptPath == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return scriptPath;
return SandboxData.getScriptFile();
}

@NotNull
public static File getResourcesFile() {
if (resourcesFile == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return resourcesFile;
return SandboxData.getResourcesFile();
}

@NotNull
public static File getRunConfigFile() {
if (runConfigFile == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
}
return runConfigFile;
return SandboxData.getRunConfigFile();
}

@NotNull
public static GroovyScriptSandbox getSandbox() {
if (sandbox == null) {
throw new IllegalStateException("GroovyScript is not yet loaded!");
throw new IllegalStateException("GroovyScript is not yet loaded or failed to load!");
}
return sandbox;
}
Expand All @@ -272,11 +242,11 @@ public static RunConfig getRunConfig() {

@ApiStatus.Internal
public static void reloadRunConfig(boolean init) {
JsonElement element = JsonHelper.loadJson(runConfigFile);
JsonElement element = JsonHelper.loadJson(getRunConfigFile());
if (element == null || !element.isJsonObject()) element = new JsonObject();
JsonObject json = element.getAsJsonObject();
if (runConfig == null) {
if (!Files.exists(runConfigFile.toPath())) {
if (!Files.exists(getRunConfigFile().toPath())) {
json = RunConfig.createDefaultJson();
runConfig = createRunConfig(json);
} else {
Expand All @@ -287,8 +257,8 @@ public static void reloadRunConfig(boolean init) {
}

private static RunConfig createRunConfig(JsonObject json) {
JsonHelper.saveJson(runConfigFile, json);
File main = new File(scriptPath.getPath() + File.separator + "postInit" + File.separator + "main.groovy");
JsonHelper.saveJson(getRunConfigFile(), json);
File main = new File(getScriptFile().getPath() + File.separator + "postInit" + File.separator + "main.groovy");
if (!Files.exists(main.toPath())) {
try {
main.getParentFile().mkdirs();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package com.cleanroommc.groovyscript.core;

import com.cleanroommc.groovyscript.sandbox.SandboxData;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import zone.rong.mixinbooter.IEarlyMixinLoader;

Expand All @@ -11,9 +15,11 @@
import java.util.Map;

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

public static final Logger LOG = LogManager.getLogger("GroovyScript-Core");
public static File source;

@Override
Expand All @@ -35,6 +41,8 @@ public String getSetupClass() {
@Override
public void injectData(Map<String, Object> data) {
source = (File) data.getOrDefault("coremodLocation", null);
SandboxData.initialize((File) FMLInjectionData.data()[6], LOG);
SideOnlyConfig.init();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,136 @@
package com.cleanroommc.groovyscript.core;

import com.cleanroommc.groovyscript.core.visitors.*;
import com.cleanroommc.groovyscript.sandbox.security.GroovySecurityManager;
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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

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;

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

// prevent banning of classes which are blacklisted for groovy
if (!GroovySecurityManager.INSTANCE.isValid(classNode)) {
GroovyScriptCore.LOG.warn("Tried to remove class '{}', but class is blacklisted for groovy. Skipping this class...", className);
return bytes;
}

if (bannedProperties.bansClass) {
throw new RuntimeException(
String.format("Attempted to load class %s for invalid side %s", className, FMLLaunchHandler.side().name()));
}

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 + "()") && GroovySecurityManager.INSTANCE.isValidMethod(classNode, method.name)) {
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;
}
}
}
Loading