diff --git a/.editorconfig b/.editorconfig index 4ffbd90..38a89de 100644 --- a/.editorconfig +++ b/.editorconfig @@ -20,3 +20,6 @@ indent_size = 2 [*.lang] trim_trailing_whitespace = false + +[prism-libraries/**.json] +indent_size = 4 diff --git a/addon.gradle b/addon.gradle index cc7ba21..e6b9751 100644 --- a/addon.gradle +++ b/addon.gradle @@ -1,10 +1,17 @@ import org.gradle.jvm.toolchain.internal.DefaultToolchainSpec +SourceSet forgePatchesSet + sourceSets { create("util") { java { } } + forgePatchesSet = create("forgePatches") { + java { + compileClasspath += mcpTasks.patchedMcSources.output + } + } named("main").configure { java { srcDirs += ["src/generated/java"] @@ -12,6 +19,11 @@ sourceSets { } } +configurations { + forgePatchesCompileClasspath.extendsFrom(compileClasspath) + forgePatchesRuntimeClasspath.extendsFrom(runtimeClasspath) +} + dependencies { utilImplementation("org.ow2.asm:asm:9.4") utilImplementation("org.ow2.asm:asm-tree:9.4") @@ -21,6 +33,15 @@ dependencies { utilImplementation("com.google.guava:guava:31.1-jre") } +tasks.register(forgePatchesSet.jarTaskName, Jar) { + from(forgePatchesSet.output) + archiveClassifier.set("forgePatches") +} + +tasks.named("assemble").configure { + dependsOn(forgePatchesSet.jarTaskName) +} + tasks.register("runComparisonTool", JavaExec) { classpath(sourceSets.util.runtimeClasspath) dependsOn("jar") @@ -51,6 +72,11 @@ for (runTask in ["runClient", "runServer", "runObfClient", "runObfServer"]) { jvmArgs( "--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED", "--add-opens", "java.base/java.net=ALL-UNNAMED", + "--add-opens", "java.base/java.nio=ALL-UNNAMED", + "--add-opens", "java.base/java.io=ALL-UNNAMED", + "--add-opens", "java.base/java.lang=ALL-UNNAMED", + "--add-opens", "java.base/java.text=ALL-UNNAMED", + "--add-opens", "java.base/java.util=ALL-UNNAMED", ) } } diff --git a/dependencies.gradle b/dependencies.gradle index 480506b..5800d46 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,10 +3,27 @@ minecraft { lwjglVersion.set("3.3.1") } +// Swap out asm for a newer version for testing in development +def useNewAsm = false + dependencies { // Resolve newer versions of LaunchWrapper to allow java 9+ compat vanilla_minecraft('net.minecraft:launchwrapper:1.13') { transitive = false } patchedMinecraft('net.minecraft:launchwrapper:1.13') { transitive = false } + if (useNewAsm) { + patchedMinecraft('org.ow2.asm:asm:9.4') + patchedMinecraft('org.ow2.asm:asm-commons:9.4') + patchedMinecraft('org.ow2.asm:asm-tree:9.4') + patchedMinecraft('org.ow2.asm:asm-analysis:9.4') + patchedMinecraft('org.ow2.asm:asm-deprecated:7.1') + } + implementation('com.gtnewhorizon:gtnhmixins:2.1.7') } + +if (useNewAsm) { + configurations.patchedMinecraft { + exclude group: 'org.ow2.asm', module: 'asm-debug-all' + } +} diff --git a/prism-libraries/patches/net.minecraft.json b/prism-libraries/patches/net.minecraft.json index b5db4b5..3350b5c 100644 --- a/prism-libraries/patches/net.minecraft.json +++ b/prism-libraries/patches/net.minecraft.json @@ -7,7 +7,8 @@ "url": "https://piston-meta.mojang.com/v1/packages/1863782e33ce7b584fc45b037325a1964e095d3e/1.7.10.json" }, "compatibleJavaMajors": [ - 8 + 11, + 17 ], "formatVersion": 1, "libraries": [ diff --git a/prism-libraries/patches/net.minecraftforge.json b/prism-libraries/patches/net.minecraftforge.json index 28ceb69..14e6883 100644 --- a/prism-libraries/patches/net.minecraftforge.json +++ b/prism-libraries/patches/net.minecraftforge.json @@ -2,6 +2,22 @@ "+tweakers": [ "cpw.mods.fml.common.launcher.FMLTweaker" ], + "+jvmArgs": [ + "--add-opens", + "java.base/jdk.internal.loader=ALL-UNNAMED", + "--add-opens", + "java.base/java.net=ALL-UNNAMED", + "--add-opens", + "java.base/java.nio=ALL-UNNAMED", + "--add-opens", + "java.base/java.io=ALL-UNNAMED", + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "--add-opens", + "java.base/java.text=ALL-UNNAMED", + "--add-opens", + "java.base/java.util=ALL-UNNAMED" + ], "formatVersion": 1, "libraries": [ { @@ -9,7 +25,8 @@ "url": "https://maven.minecraftforge.net/" }, { - "name": "net.minecraft:launchwrapper:1.12" + "name": "net.minecraft:launchwrapper:1.13", + "url": "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" }, { "name": "org.ow2.asm:asm-all:5.0.3" diff --git a/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java b/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java new file mode 100644 index 0000000..38ff29f --- /dev/null +++ b/src/forgePatches/java/cpw/mods/fml/relauncher/CoreModManager.java @@ -0,0 +1,617 @@ +/* + * Forge Mod Loader + * Copyright (c) 2012-2013 cpw. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v2.1 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + * + * Contributors: + * cpw - implementation + * eigenraven - java 9 compatibility + */ + +package cpw.mods.fml.relauncher; + +import com.google.common.base.Strings; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.ObjectArrays; +import com.google.common.primitives.Ints; +import cpw.mods.fml.common.FMLLog; +import cpw.mods.fml.common.asm.transformers.ModAccessTransformer; +import cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker; +import cpw.mods.fml.common.launcher.FMLTweaker; +import cpw.mods.fml.common.toposort.TopologicalSort; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.DependsOn; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.Name; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; +import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions; +import java.io.File; +import java.io.FileFilter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import net.minecraft.launchwrapper.ITweaker; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; +import org.apache.logging.log4j.Level; + +public class CoreModManager { + private static final Attributes.Name COREMODCONTAINSFMLMOD = new Attributes.Name("FMLCorePluginContainsFMLMod"); + private static final Attributes.Name MODTYPE = new Attributes.Name("ModType"); + private static final Attributes.Name MODSIDE = new Attributes.Name("ModSide"); + private static String[] rootPlugins = { + "cpw.mods.fml.relauncher.FMLCorePlugin", "net.minecraftforge.classloading.FMLForgePlugin" + }; + private static List loadedCoremods = Lists.newArrayList(); + private static List loadPlugins; + private static boolean deobfuscatedEnvironment; + private static FMLTweaker tweaker; + private static File mcDir; + private static List reparsedCoremods = Lists.newArrayList(); + private static List accessTransformers = Lists.newArrayList(); + + private static class FMLPluginWrapper implements ITweaker { + public final String name; + public final IFMLLoadingPlugin coreModInstance; + public final List predepends; + public final File location; + public final int sortIndex; + + public FMLPluginWrapper( + String name, IFMLLoadingPlugin coreModInstance, File location, int sortIndex, String... predepends) { + super(); + this.name = name; + this.coreModInstance = coreModInstance; + this.location = location; + this.sortIndex = sortIndex; + this.predepends = Lists.newArrayList(predepends); + } + + @Override + public String toString() { + return String.format("%s {%s}", this.name, this.predepends); + } + + @Override + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + // NO OP + } + + @Override + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + FMLRelaunchLog.fine( + "Injecting coremod %s {%s} class transformers", + name, coreModInstance.getClass().getName()); + if (coreModInstance.getASMTransformerClass() != null) + for (String transformer : coreModInstance.getASMTransformerClass()) { + FMLRelaunchLog.finer("Registering transformer %s", transformer); + classLoader.registerTransformer(transformer); + } + FMLRelaunchLog.fine("Injection complete"); + + FMLRelaunchLog.fine( + "Running coremod plugin for %s {%s}", + name, coreModInstance.getClass().getName()); + Map data = new HashMap(); + data.put("mcLocation", mcDir); + data.put("coremodList", loadPlugins); + data.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); + FMLRelaunchLog.fine("Running coremod plugin %s", name); + data.put("coremodLocation", location); + coreModInstance.injectData(data); + String setupClass = coreModInstance.getSetupClass(); + if (setupClass != null) { + try { + IFMLCallHook call = (IFMLCallHook) + Class.forName(setupClass, true, classLoader).newInstance(); + Map callData = new HashMap(); + callData.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); + callData.put("mcLocation", mcDir); + callData.put("classLoader", classLoader); + callData.put("coremodLocation", location); + callData.put("deobfuscationFileName", FMLInjectionData.debfuscationDataName()); + call.injectData(callData); + call.call(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + FMLRelaunchLog.fine( + "Coremod plugin class %s run successfully", + coreModInstance.getClass().getSimpleName()); + + String modContainer = coreModInstance.getModContainerClass(); + if (modContainer != null) { + FMLInjectionData.containers.add(modContainer); + } + } + + @Override + public String getLaunchTarget() { + return ""; + } + + @Override + public String[] getLaunchArguments() { + return new String[0]; + } + } + + public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker) { + CoreModManager.mcDir = mcDir; + CoreModManager.tweaker = tweaker; + try { + // Are we in a 'decompiled' environment? + byte[] bs = classLoader.getClassBytes("net.minecraft.world.World"); + if (bs != null) { + FMLRelaunchLog.info( + "Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation"); + deobfuscatedEnvironment = true; + } + } catch (IOException e1) { + } + + if (!deobfuscatedEnvironment) { + FMLRelaunchLog.fine("Enabling runtime deobfuscation"); + } + + tweaker.injectCascadingTweak("cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker"); + try { + classLoader.registerTransformer("cpw.mods.fml.common.asm.transformers.PatchingTransformer"); + } catch (Exception e) { + FMLRelaunchLog.log( + Level.ERROR, e, "The patch transformer failed to load! This is critical, loading cannot continue!"); + throw Throwables.propagate(e); + } + + loadPlugins = new ArrayList(); + for (String rootPluginName : rootPlugins) { + loadCoreMod(classLoader, rootPluginName, new File(FMLTweaker.getJarLocation())); + } + + if (loadPlugins.isEmpty()) { + throw new RuntimeException( + "A fatal error has occured - no valid fml load plugin was found - this is a completely corrupt FML installation."); + } + + FMLRelaunchLog.fine("All fundamental core mods are successfully located"); + // Now that we have the root plugins loaded - lets see what else might + // be around + String commandLineCoremods = System.getProperty("fml.coreMods.load", ""); + for (String coreModClassName : commandLineCoremods.split(",")) { + if (coreModClassName.isEmpty()) { + continue; + } + FMLRelaunchLog.info("Found a command line coremod : %s", coreModClassName); + loadCoreMod(classLoader, coreModClassName, null); + } + discoverCoreMods(mcDir, classLoader); + } + + private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) { + ModListHelper.parseModList(mcDir); + FMLRelaunchLog.fine("Discovering coremods"); + File coreMods = setupCoreModDir(mcDir); + FilenameFilter ff = new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith(".jar"); + } + }; + FilenameFilter derpfilter = new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.endsWith(".jar.zip"); + } + }; + File[] derplist = coreMods.listFiles(derpfilter); + if (derplist != null && derplist.length > 0) { + FMLRelaunchLog.severe( + "FML has detected several badly downloaded jar files, which have been named as zip files. You probably need to download them again, or they may not work properly"); + for (File f : derplist) { + FMLRelaunchLog.severe("Problem file : %s", f.getName()); + } + } + FileFilter derpdirfilter = new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory(); + } + }; + File[] derpdirlist = coreMods.listFiles(derpdirfilter); + if (derpdirlist != null && derpdirlist.length > 0) { + FMLRelaunchLog.log + .getLogger() + .log( + Level.FATAL, + "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL"); + FMLRelaunchLog.log + .getLogger() + .log( + Level.FATAL, + "You should place original jars only in the mods directory. NEVER extract them to the mods directory."); + FMLRelaunchLog.log + .getLogger() + .log( + Level.FATAL, + "The directories below appear to be extracted jar files. Fix this before you continue."); + + for (File f : derpdirlist) { + FMLRelaunchLog.log + .getLogger() + .log( + Level.FATAL, + "Directory {} contains {}", + f.getName(), + Arrays.asList(new File(f, "META-INF").list())); + } + + RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue"); + // We're generating a crash report for the launcher to show to the user here + try { + Class crashreportclass = classLoader.loadClass("b"); + Object crashreport = crashreportclass + .getMethod("a", Throwable.class, String.class) + .invoke( + null, + re, + "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided."); + File crashreportfile = new File( + new File(coreMods.getParentFile(), "crash-reports"), + String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance())); + crashreportclass.getMethod("a", File.class).invoke(crashreport, crashreportfile); + System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# " + + crashreportfile.getAbsolutePath()); + } catch (Exception e) { + e.printStackTrace(); + // NOOP - hopefully + } + throw re; + } + File[] coreModList = coreMods.listFiles(ff); + File versionedModDir = new File(coreMods, FMLInjectionData.mccversion); + if (versionedModDir.isDirectory()) { + File[] versionedCoreMods = versionedModDir.listFiles(ff); + coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class); + } + + coreModList = ObjectArrays.concat( + coreModList, ModListHelper.additionalMods.values().toArray(new File[0]), File.class); + + coreModList = FileListHelper.sortFileList(coreModList); + + for (File coreMod : coreModList) { + FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName()); + JarFile jar = null; + Attributes mfAttributes; + try { + jar = new JarFile(coreMod); + if (jar.getManifest() == null) { + // Not a coremod and no access transformer list + continue; + } + ModAccessTransformer.addJar(jar); + mfAttributes = jar.getManifest().getMainAttributes(); + } catch (IOException ioe) { + FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring", coreMod.getName()); + continue; + } finally { + if (jar != null) { + try { + jar.close(); + } catch (IOException e) { + // Noise + } + } + } + String cascadedTweaker = mfAttributes.getValue("TweakClass"); + if (cascadedTweaker != null) { + FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName()); + Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder"))); + sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder); + handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder); + loadedCoremods.add(coreMod.getName()); + continue; + } + List modTypes = mfAttributes.containsKey(MODTYPE) + ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(",")) + : ImmutableList.of("FML"); + + if (!modTypes.contains("FML")) { + FMLRelaunchLog.fine( + "Adding %s to the list of things to skip. It is not an FML mod, it has types %s", + coreMod.getName(), modTypes); + loadedCoremods.add(coreMod.getName()); + continue; + } + String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH"; + if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name().equals(modSide))) { + FMLRelaunchLog.fine( + "Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored", + coreMod.getName(), modSide, FMLLaunchHandler.side.name()); + loadedCoremods.add(coreMod.getName()); + continue; + } + String fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin"); + if (fmlCorePlugin == null) { + // Not a coremod + FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName()); + continue; + } + // Support things that are mod jars, but not FML mod jars + try { + classLoader.addURL(coreMod.toURI().toURL()); + if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) { + FMLRelaunchLog.finer( + "Adding %s to the list of known coremods, it will not be examined again", + coreMod.getName()); + loadedCoremods.add(coreMod.getName()); + } else { + FMLRelaunchLog.finer( + "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances", + coreMod.getName()); + reparsedCoremods.add(coreMod.getName()); + } + } catch (MalformedURLException e) { + FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird"); + continue; + } + loadCoreMod(classLoader, fmlCorePlugin, coreMod); + } + } + + private static Method ADDURL; + + private static void handleCascadingTweak( + File coreMod, JarFile jar, String cascadedTweaker, LaunchClassLoader classLoader, Integer sortingOrder) { + try { + // Have to manually stuff the tweaker into the parent classloader + if (ADDURL == null) { + ADDURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); + ADDURL.setAccessible(true); + } + ADDURL.invoke( + classLoader.getClass().getClassLoader(), coreMod.toURI().toURL()); + classLoader.addURL(coreMod.toURI().toURL()); + CoreModManager.tweaker.injectCascadingTweak(cascadedTweaker); + tweakSorting.put(cascadedTweaker, sortingOrder); + } catch (Exception e) { + FMLRelaunchLog.log( + Level.INFO, + e, + "There was a problem trying to load the mod dir tweaker %s", + coreMod.getAbsolutePath()); + } + } + + /** + * @param mcDir + * the minecraft home directory + * @return the coremod directory + */ + private static File setupCoreModDir(File mcDir) { + File coreModDir = new File(mcDir, "mods"); + try { + coreModDir = coreModDir.getCanonicalFile(); + } catch (IOException e) { + throw new RuntimeException( + String.format("Unable to canonicalize the coremod dir at %s", mcDir.getName()), e); + } + if (!coreModDir.exists()) { + coreModDir.mkdir(); + } else if (coreModDir.exists() && !coreModDir.isDirectory()) { + throw new RuntimeException( + String.format("Found a coremod file in %s that's not a directory", mcDir.getName())); + } + return coreModDir; + } + + public static List getLoadedCoremods() { + return loadedCoremods; + } + + public static List getReparseableCoremods() { + return reparsedCoremods; + } + + private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) { + String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1); + try { + FMLRelaunchLog.fine("Instantiating coremod class %s", coreModName); + classLoader.addTransformerExclusion(coreModClass); + Class coreModClazz = Class.forName(coreModClass, true, classLoader); + Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class); + if (coreModNameAnn != null && !Strings.isNullOrEmpty(coreModNameAnn.value())) { + coreModName = coreModNameAnn.value(); + FMLRelaunchLog.finer("coremod named %s is loading", coreModName); + } + MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class); + if (!Arrays.asList(rootPlugins).contains(coreModClass) + && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value()))) { + FMLRelaunchLog.log( + Level.WARN, + "The coremod %s does not have a MCVersion annotation, it may cause issues with this version of Minecraft", + coreModClass); + } else if (requiredMCVersion != null && !FMLInjectionData.mccversion.equals(requiredMCVersion.value())) { + FMLRelaunchLog.log( + Level.ERROR, + "The coremod %s is requesting minecraft version %s and minecraft is %s. It will be ignored.", + coreModClass, + requiredMCVersion.value(), + FMLInjectionData.mccversion); + return null; + } else if (requiredMCVersion != null) { + FMLRelaunchLog.log( + Level.DEBUG, + "The coremod %s requested minecraft version %s and minecraft is %s. It will be loaded.", + coreModClass, + requiredMCVersion.value(), + FMLInjectionData.mccversion); + } + TransformerExclusions trExclusions = + coreModClazz.getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class); + if (trExclusions != null) { + for (String st : trExclusions.value()) { + classLoader.addTransformerExclusion(st); + } + } + DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class); + String[] dependencies = new String[0]; + if (deplist != null) { + dependencies = deplist.value(); + } + SortingIndex index = coreModClazz.getAnnotation(IFMLLoadingPlugin.SortingIndex.class); + int sortIndex = index != null ? index.value() : 0; + + IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance(); + String accessTransformerClass = plugin.getAccessTransformerClass(); + if (accessTransformerClass != null) { + FMLRelaunchLog.log( + Level.DEBUG, + "Added access transformer class %s to enqueued access transformers", + accessTransformerClass); + accessTransformers.add(accessTransformerClass); + } + FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, sortIndex, dependencies); + loadPlugins.add(wrap); + FMLRelaunchLog.fine("Enqueued coremod %s", coreModName); + return wrap; + } catch (ClassNotFoundException cnfe) { + if (!Lists.newArrayList(rootPlugins).contains(coreModClass)) + FMLRelaunchLog.log( + Level.ERROR, cnfe, "Coremod %s: Unable to class load the plugin %s", coreModName, coreModClass); + else FMLRelaunchLog.fine("Skipping root plugin %s", coreModClass); + } catch (ClassCastException cce) { + FMLRelaunchLog.log( + Level.ERROR, + cce, + "Coremod %s: The plugin %s is not an implementor of IFMLLoadingPlugin", + coreModName, + coreModClass); + } catch (InstantiationException ie) { + FMLRelaunchLog.log( + Level.ERROR, ie, "Coremod %s: The plugin class %s was not instantiable", coreModName, coreModClass); + } catch (IllegalAccessException iae) { + FMLRelaunchLog.log( + Level.ERROR, iae, "Coremod %s: The plugin class %s was not accessible", coreModName, coreModClass); + } + return null; + } + + @SuppressWarnings("unused") + private static void sortCoreMods() { + TopologicalSort.DirectedGraph sortGraph = + new TopologicalSort.DirectedGraph(); + Map pluginMap = Maps.newHashMap(); + for (FMLPluginWrapper plug : loadPlugins) { + sortGraph.addNode(plug); + pluginMap.put(plug.name, plug); + } + + for (FMLPluginWrapper plug : loadPlugins) { + for (String dep : plug.predepends) { + if (!pluginMap.containsKey(dep)) { + FMLRelaunchLog.log( + Level.ERROR, + "Missing coremod dependency - the coremod %s depends on coremod %s which isn't present.", + plug.name, + dep); + throw new RuntimeException(); + } + sortGraph.addEdge(plug, pluginMap.get(dep)); + } + } + try { + loadPlugins = TopologicalSort.topologicalSort(sortGraph); + FMLRelaunchLog.fine("Sorted coremod list %s", loadPlugins); + } catch (Exception e) { + FMLLog.log(Level.ERROR, e, "There was a problem performing the coremod sort"); + throw Throwables.propagate(e); + } + } + + public static void injectTransformers(LaunchClassLoader classLoader) { + + Launch.blackboard.put("fml.deobfuscatedEnvironment", deobfuscatedEnvironment); + tweaker.injectCascadingTweak("cpw.mods.fml.common.launcher.FMLDeobfTweaker"); + tweakSorting.put("cpw.mods.fml.common.launcher.FMLDeobfTweaker", Integer.valueOf(1000)); + } + + public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectionAndSortingTweaker) { + @SuppressWarnings("unchecked") + List tweakers = (List) Launch.blackboard.get("Tweaks"); + // Add the sorting tweaker first- it'll appear twice in the list + tweakers.add(0, fmlInjectionAndSortingTweaker); + for (FMLPluginWrapper wrapper : loadPlugins) { + tweakers.add(wrapper); + } + } + + private static Map tweakSorting = Maps.newHashMap(); + + public static void sortTweakList() { + @SuppressWarnings("unchecked") + List tweakers = (List) Launch.blackboard.get("Tweaks"); + // Basically a copy of Collections.sort pre 8u20, optimized as we know we're an array list. + // Thanks unhelpful fixer of http://bugs.java.com/view_bug.do?bug_id=8032636 + ITweaker[] toSort = tweakers.toArray(new ITweaker[tweakers.size()]); + Arrays.sort(toSort, new Comparator() { + @Override + public int compare(ITweaker o1, ITweaker o2) { + Integer first = null; + Integer second = null; + if (o1 instanceof FMLInjectionAndSortingTweaker) { + first = Integer.MIN_VALUE; + } + if (o2 instanceof FMLInjectionAndSortingTweaker) { + second = Integer.MIN_VALUE; + } + + if (o1 instanceof FMLPluginWrapper) { + first = ((FMLPluginWrapper) o1).sortIndex; + } else if (first == null) { + first = tweakSorting.get(o1.getClass().getName()); + } + if (o2 instanceof FMLPluginWrapper) { + second = ((FMLPluginWrapper) o2).sortIndex; + } else if (second == null) { + second = tweakSorting.get(o2.getClass().getName()); + } + if (first == null) { + first = 0; + } + if (second == null) { + second = 0; + } + + return Ints.saturatedCast((long) first - (long) second); + } + }); + // Basically a copy of Collections.sort, optimized as we know we're an array list. + // Thanks unhelpful fixer of http://bugs.java.com/view_bug.do?bug_id=8032636 + for (int j = 0; j < toSort.length; j++) { + tweakers.set(j, toSort[j]); + } + } + + public static List getAccessTransformers() { + return accessTransformers; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/EventSubscriptionTransformerFixer.java b/src/main/java/me/eigenraven/lwjgl3ify/core/EventSubscriptionTransformerFixer.java new file mode 100644 index 0000000..6ae1234 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/core/EventSubscriptionTransformerFixer.java @@ -0,0 +1,212 @@ +/** + * Copied from FML source code and adapted for compatibility with newer asm versions. + */ +package me.eigenraven.lwjgl3ify.core; + +import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; +import static org.objectweb.asm.Opcodes.ACC_PRIVATE; +import static org.objectweb.asm.Opcodes.ACC_PROTECTED; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.DUP; +import static org.objectweb.asm.Opcodes.F_SAME; +import static org.objectweb.asm.Opcodes.GETSTATIC; +import static org.objectweb.asm.Opcodes.ICONST_1; +import static org.objectweb.asm.Opcodes.IFNULL; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.NEW; +import static org.objectweb.asm.Opcodes.PUTSTATIC; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Type.BOOLEAN_TYPE; +import static org.objectweb.asm.Type.VOID_TYPE; +import static org.objectweb.asm.Type.getMethodDescriptor; + +import cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer; +import cpw.mods.fml.common.eventhandler.Event; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; + +public class EventSubscriptionTransformerFixer extends EventSubscriptionTransformer { + public EventSubscriptionTransformerFixer() {} + + @Override + public byte[] transform(String name, String transformedName, byte[] bytes) { + if (bytes == null + || name.equals("cpw.mods.fml.common.eventhandler.Event") + || name.startsWith("net.minecraft.") + || name.indexOf('.') == -1) { + return bytes; + } + ClassReader cr = new ClassReader(bytes); + ClassNode classNode = new ClassNode(); + cr.accept(classNode, 0); + + try { + if (buildEvents(classNode)) { + ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); + classNode.accept(cw); + return cw.toByteArray(); + } + return bytes; + } catch (ClassNotFoundException ex) { + // Discard silently- it's just noise + } catch (Exception e) { + e.printStackTrace(); + } + + return bytes; + } + + private boolean buildEvents(ClassNode classNode) throws Exception { + // Yes, this recursively loads classes until we get this base class. THIS IS NOT A ISSUE. Coremods should handle + // re-entry just fine. + // If they do not this a COREMOD issue NOT a Forge/LaunchWrapper issue. + Class parent = this.getClass().getClassLoader().loadClass(classNode.superName.replace('/', '.')); + if (!Event.class.isAssignableFrom(parent)) { + return false; + } + + // Class listenerListClazz = Class.forName("cpw.mods.fml.common.eventhandler.ListenerList", false, + // getClass().getClassLoader()); + Type tList = Type.getType("Lcpw/mods/fml/common/eventhandler/ListenerList;"); + + boolean edited = false; + boolean hasSetup = false; + boolean hasGetListenerList = false; + boolean hasDefaultCtr = false; + boolean hasCancelable = false; + boolean hasResult = false; + String voidDesc = Type.getMethodDescriptor(VOID_TYPE); + String boolDesc = Type.getMethodDescriptor(BOOLEAN_TYPE); + String listDesc = tList.getDescriptor(); + String listDescM = Type.getMethodDescriptor(tList); + + for (MethodNode method : classNode.methods) { + if (method.name.equals("setup") + && method.desc.equals(voidDesc) + && (method.access & ACC_PROTECTED) == ACC_PROTECTED) hasSetup = true; + if ((method.access & ACC_PUBLIC) == ACC_PUBLIC) { + if (method.name.equals("getListenerList") && method.desc.equals(listDescM)) hasGetListenerList = true; + if (method.name.equals("isCancelable") && method.desc.equals(boolDesc)) hasCancelable = true; + if (method.name.equals("hasResult") && method.desc.equals(boolDesc)) hasResult = true; + } + if (method.name.equals("") && method.desc.equals(voidDesc)) hasDefaultCtr = true; + } + + if (classNode.visibleAnnotations != null) { + for (AnnotationNode node : classNode.visibleAnnotations) { + if (!hasResult && node.desc.equals("Lcpw/mods/fml/common/eventhandler/Event$HasResult;")) { + /* Add: + * public boolean hasResult() + * { + * return true; + * } + */ + MethodNode method = new MethodNode(ACC_PUBLIC, "hasResult", boolDesc, null, null); + method.instructions.add(new InsnNode(ICONST_1)); + method.instructions.add(new InsnNode(IRETURN)); + classNode.methods.add(method); + edited = true; + } else if (!hasCancelable && node.desc.equals("Lcpw/mods/fml/common/eventhandler/Cancelable;")) { + /* Add: + * public boolean isCancelable() + * { + * return true; + * } + */ + MethodNode method = new MethodNode(ACC_PUBLIC, "isCancelable", boolDesc, null, null); + method.instructions.add(new InsnNode(ICONST_1)); + method.instructions.add(new InsnNode(IRETURN)); + classNode.methods.add(method); + edited = true; + } + } + } + + if (hasSetup) { + if (!hasGetListenerList) + throw new RuntimeException( + "Event class defines setup() but does not define getListenerList! " + classNode.name); + else return edited; + } + + Type tSuper = Type.getObjectType(classNode.superName); + + // Add private static ListenerList LISTENER_LIST + classNode.fields.add(new FieldNode(ACC_PRIVATE | ACC_STATIC, "LISTENER_LIST", listDesc, null, null)); + + /*Add: + * public () + * { + * super(); + * } + */ + if (!hasDefaultCtr) { + MethodNode method = new MethodNode(ACC_PUBLIC, "", voidDesc, null, null); + method.instructions.add(new VarInsnNode(ALOAD, 0)); + method.instructions.add( + new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "", voidDesc, false)); + method.instructions.add(new InsnNode(RETURN)); + classNode.methods.add(method); + } + + /*Add: + * protected void setup() + * { + * super.setup(); + * if (LISTENER_LIST != NULL) + * { + * return; + * } + * LISTENER_LIST = new ListenerList(super.getListenerList()); + * } + */ + MethodNode method = new MethodNode(ACC_PROTECTED, "setup", voidDesc, null, null); + method.instructions.add(new VarInsnNode(ALOAD, 0)); + method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "setup", voidDesc, false)); + method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); + LabelNode initLisitener = new LabelNode(); + method.instructions.add(new JumpInsnNode(IFNULL, initLisitener)); + method.instructions.add(new InsnNode(RETURN)); + method.instructions.add(initLisitener); + method.instructions.add(new FrameNode(F_SAME, 0, null, 0, null)); + method.instructions.add(new TypeInsnNode(NEW, tList.getInternalName())); + method.instructions.add(new InsnNode(DUP)); + method.instructions.add(new VarInsnNode(ALOAD, 0)); + method.instructions.add( + new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "getListenerList", listDescM, false)); + method.instructions.add(new MethodInsnNode( + INVOKESPECIAL, tList.getInternalName(), "", getMethodDescriptor(VOID_TYPE, tList), false)); + method.instructions.add(new FieldInsnNode(PUTSTATIC, classNode.name, "LISTENER_LIST", listDesc)); + method.instructions.add(new InsnNode(RETURN)); + classNode.methods.add(method); + + /*Add: + * public ListenerList getListenerList() + * { + * return this.LISTENER_LIST; + * } + */ + method = new MethodNode(ACC_PUBLIC, "getListenerList", listDescM, null, null); + method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); + method.instructions.add(new InsnNode(ARETURN)); + classNode.methods.add(method); + return true; + } +} diff --git a/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java b/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java index 79807fa..46fb22e 100644 --- a/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java +++ b/src/main/java/me/eigenraven/lwjgl3ify/core/PostMixinTransformInjector.java @@ -1,7 +1,12 @@ package me.eigenraven.lwjgl3ify.core; +import com.google.common.base.Throwables; +import cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer; import java.io.File; +import java.lang.reflect.Field; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; @@ -19,7 +24,25 @@ public class PostMixinTransformInjector implements ITweaker { @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { - // no-op + try { + // Wrap EventSubscriptionTransformer + final Field transformersF = classLoader.getClass().getDeclaredField("transformers"); + transformersF.setAccessible(true); + final List transformers = (List) transformersF.get(classLoader); + + final AtomicInteger replaces = new AtomicInteger(); + transformers.replaceAll(tf -> { + if (tf instanceof EventSubscriptionTransformer) { + replaces.getAndIncrement(); + return new EventSubscriptionTransformerFixer(); + } else { + return tf; + } + }); + Lwjgl3ifyCoremod.LOGGER.info("Replaced {} transformers with more compatible variants", replaces.get()); + } catch (Throwable e) { + Throwables.propagate(e); + } } @Override diff --git a/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/JarDiscoverer.java b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/JarDiscoverer.java new file mode 100644 index 0000000..b469651 --- /dev/null +++ b/src/main/java/me/eigenraven/lwjgl3ify/mixins/fml/JarDiscoverer.java @@ -0,0 +1,30 @@ +package me.eigenraven.lwjgl3ify.mixins.fml; + +import java.util.zip.ZipEntry; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin( + value = {cpw.mods.fml.common.discovery.JarDiscoverer.class}, + remap = false) +public class JarDiscoverer { + @Redirect( + method = { + "Lcpw/mods/fml/common/discovery/JarDiscoverer;discover(Lcpw/mods/fml/common/discovery/ModCandidate;Lcpw/mods/fml/common/discovery/ASMDataTable;)Ljava/util/List;" + }, + at = @At(ordinal = 1, value = "INVOKE", target = "Ljava/util/zip/ZipEntry;getName()Ljava/lang/String;"), + remap = false, + require = 1) + public String getZipEntryName(ZipEntry ze) { + String name = ze.getName(); + if (name == null) { + return null; + } + if (name.contains("module-info.class") || name.startsWith("META-INF/versions/")) { + // Triggers the continue in the loop + return "__MACOSX_ignoreme"; + } + return name; + } +}