FML is no more. FML has ceased to be. FML's expired and gone to meet its maker. FML's a stiff! Bereft of life, FML rests in peace.

This commit is contained in:
cpw committed 2015-08-01 23:51:40 -04:00
1 parent 9a859f8d5c
commit 614bbcb0da
356 files changed
+2676 -235

No files matched your search

@@ -0,0 +1,690 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
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.Set;
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 net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.asm.ASMTransformerWrapper;
import net.minecraftforge.fml.common.asm.transformers.ModAccessTransformer;
import net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker;
import net.minecraftforge.fml.common.launcher.FMLTweaker;
import net.minecraftforge.fml.common.toposort.TopologicalSort;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.DependsOn;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.MCVersion;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.Name;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
import org.apache.logging.log4j.Level;
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.collect.Sets;
import com.google.common.primitives.Ints;
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 = { "net.minecraftforge.fml.relauncher.FMLCorePlugin", "net.minecraftforge.classloading.FMLForgePlugin" };
private static List<String> loadedCoremods = Lists.newArrayList();
private static Map<String, List<String>> transformers = Maps.newHashMap();
private static List<FMLPluginWrapper> loadPlugins;
private static boolean deobfuscatedEnvironment;
private static FMLTweaker tweaker;
private static File mcDir;
private static List<String> reparsedCoremods = Lists.newArrayList();
private static List<String> accessTransformers = Lists.newArrayList();
private static Set<String> rootNames = Sets.newHashSet();
static
{
for(String cls : rootPlugins)
{
rootNames.add(cls.substring(cls.lastIndexOf('.') + 1));
}
}
private static class FMLPluginWrapper implements ITweaker {
public final String name;
public final IFMLLoadingPlugin coreModInstance;
public final List<String> 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<String> 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());
List<String> ts = Lists.newArrayList();
if (coreModInstance.getASMTransformerClass() != null) for (String transformer : coreModInstance.getASMTransformerClass())
{
FMLRelaunchLog.finer("Registering transformer %s", transformer);
classLoader.registerTransformer(ASMTransformerWrapper.getTransformerWrapper(classLoader, transformer, name));
ts.add(transformer);
}
if(!rootNames.contains(name))
{
String loc;
if(location == null) loc = "unknown";
else loc = location.getName();
transformers.put(name + " (" + loc + ")", ts);
}
FMLRelaunchLog.fine("Injection complete");
FMLRelaunchLog.fine("Running coremod plugin for %s {%s}", name, coreModInstance.getClass().getName());
Map<String, Object> data = new HashMap<String, Object>();
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<String, Object> callData = new HashMap<String, Object>();
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("net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker");
try
{
classLoader.registerTransformer("net.minecraftforge.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<FMLPluginWrapper>();
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<String> 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<String> getLoadedCoremods()
{
return loadedCoremods;
}
public static Map<String, List<String>> getTransformers()
{
return transformers;
}
public static List<String> 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;
}
private static void sortCoreMods()
{
TopologicalSort.DirectedGraph<FMLPluginWrapper> sortGraph = new TopologicalSort.DirectedGraph<FMLPluginWrapper>();
Map<String, FMLPluginWrapper> 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("net.minecraftforge.fml.common.launcher.FMLDeobfTweaker");
tweakSorting.put("net.minecraftforge.fml.common.launcher.FMLDeobfTweaker", Integer.valueOf(1000));
}
public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectionAndSortingTweaker)
{
@SuppressWarnings("unchecked")
List<ITweaker> tweakers = (List<ITweaker>) 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<String,Integer> tweakSorting = Maps.newHashMap();
public static void sortTweakList()
{
@SuppressWarnings("unchecked")
List<ITweaker> tweakers = (List<ITweaker>) 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<ITweaker>() {
@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<String> getAccessTransformers()
{
return accessTransformers;
}
public static void onCrash(StringBuilder builder)
{
if(!loadedCoremods.isEmpty() || !reparsedCoremods.isEmpty())
{
builder.append("\nWARNING: coremods are present:\n");
for(String coreMod : transformers.keySet())
{
builder.append(" ").append(coreMod).append('\n');
}
builder.append("Contact their authors BEFORE contacting forge\n\n");
}
}
}
@@ -0,0 +1,53 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.util.Map;
public class FMLCorePlugin implements IFMLLoadingPlugin
{
@Override
public String[] getASMTransformerClass()
{
return new String[] {
"net.minecraftforge.fml.common.asm.transformers.BlamingTransformer",
"net.minecraftforge.fml.common.asm.transformers.MarkerTransformer",
"net.minecraftforge.fml.common.asm.transformers.SideTransformer",
"net.minecraftforge.fml.common.asm.transformers.EventSubscriptionTransformer",
"net.minecraftforge.fml.common.asm.transformers.EventSubscriberTransformer",
};
}
@Override
public String getAccessTransformerClass()
{
return "net.minecraftforge.fml.common.asm.transformers.AccessTransformer";
}
@Override
public String getModContainerClass()
{
return "net.minecraftforge.fml.common.FMLContainer";
}
@Override
public String getSetupClass()
{
return "net.minecraftforge.fml.common.asm.FMLSanityChecker";
}
@Override
public void injectData(Map<String, Object> data)
{
// don't care about this data
}
}
@@ -0,0 +1,73 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.logging.log4j.Level;
import net.minecraft.launchwrapper.LaunchClassLoader;
public class FMLInjectionData
{
static File minecraftHome;
static String major;
static String minor;
static String rev;
static String build;
static String mccversion;
static String mcpversion;
static String deobfuscationDataHash;
public static List<String> containers = new ArrayList<String>();
static void build(File mcHome, LaunchClassLoader classLoader)
{
minecraftHome = mcHome;
InputStream stream = classLoader.getResourceAsStream("fmlversion.properties");
Properties properties = new Properties();
if (stream != null)
{
try
{
properties.load(stream);
}
catch (IOException ex)
{
FMLRelaunchLog.log(Level.ERROR, ex, "Could not get FML version information - corrupted installation detected!");
}
}
major = properties.getProperty("fmlbuild.major.number", "missing");
minor = properties.getProperty("fmlbuild.minor.number", "missing");
rev = properties.getProperty("fmlbuild.revision.number", "missing");
build = properties.getProperty("fmlbuild.build.number", "missing");
mccversion = properties.getProperty("fmlbuild.mcversion", "missing");
mcpversion = properties.getProperty("fmlbuild.mcpversion", "missing");
deobfuscationDataHash = properties.getProperty("fmlbuild.deobfuscation.hash","deadbeef");
}
static String debfuscationDataName()
{
return "/deobfuscation_data-"+mccversion+".lzma";
}
public static Object[] data()
{
return new Object[] { major, minor, rev, build, mccversion, mcpversion, minecraftHome, containers };
}
}
@@ -0,0 +1,115 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.io.File;
import org.apache.logging.log4j.Level;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.launcher.FMLTweaker;
import com.google.common.base.Throwables;
public class FMLLaunchHandler
{
private static FMLLaunchHandler INSTANCE;
static Side side;
private LaunchClassLoader classLoader;
private FMLTweaker tweaker;
private File minecraftHome;
public static void configureForClientLaunch(LaunchClassLoader loader, FMLTweaker tweaker)
{
instance(loader, tweaker).setupClient();
}
public static void configureForServerLaunch(LaunchClassLoader loader, FMLTweaker tweaker)
{
instance(loader, tweaker).setupServer();
}
private static FMLLaunchHandler instance(LaunchClassLoader launchLoader, FMLTweaker tweaker)
{
if (INSTANCE == null)
{
INSTANCE = new FMLLaunchHandler(launchLoader, tweaker);
}
return INSTANCE;
}
private FMLLaunchHandler(LaunchClassLoader launchLoader, FMLTweaker tweaker)
{
this.classLoader = launchLoader;
this.tweaker = tweaker;
this.minecraftHome = tweaker.getGameDir();
this.classLoader.addClassLoaderExclusion("net.minecraftforge.fml.relauncher.");
this.classLoader.addClassLoaderExclusion("net.minecraftforge.classloading.");
this.classLoader.addTransformerExclusion("net.minecraftforge.fml.common.asm.transformers.deobf.");
this.classLoader.addTransformerExclusion("net.minecraftforge.fml.common.patcher.");
}
private void setupClient()
{
FMLRelaunchLog.side = Side.CLIENT;
side = Side.CLIENT;
setupHome();
}
private void setupServer()
{
FMLRelaunchLog.side = Side.SERVER;
side = Side.SERVER;
setupHome();
}
private void setupHome()
{
FMLInjectionData.build(minecraftHome, classLoader);
FMLRelaunchLog.minecraftHome = minecraftHome;
FMLRelaunchLog.info("Forge Mod Loader version %s.%s.%s.%s for Minecraft %s loading", FMLInjectionData.major, FMLInjectionData.minor,
FMLInjectionData.rev, FMLInjectionData.build, FMLInjectionData.mccversion, FMLInjectionData.mcpversion);
FMLRelaunchLog.info("Java is %s, version %s, running on %s:%s:%s, installed at %s", System.getProperty("java.vm.name"), System.getProperty("java.version"), System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"), System.getProperty("java.home"));
FMLRelaunchLog.fine("Java classpath at launch is %s", System.getProperty("java.class.path"));
FMLRelaunchLog.fine("Java library path at launch is %s", System.getProperty("java.library.path"));
try
{
CoreModManager.handleLaunch(minecraftHome, classLoader, tweaker);
}
catch (Throwable t)
{
t.printStackTrace();
FMLRelaunchLog.log(Level.ERROR, t, "An error occurred trying to configure the minecraft home at %s for Forge Mod Loader", minecraftHome.getAbsolutePath());
throw Throwables.propagate(t);
}
}
public static Side side()
{
return side;
}
private void injectPostfixTransformers()
{
CoreModManager.injectTransformers(classLoader);
}
public static void appendCoreMods()
{
INSTANCE.injectPostfixTransformers();
}
}
@@ -0,0 +1,115 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.io.File;
import java.util.Locale;
import net.minecraftforge.fml.common.TracingPrintStream;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
public class FMLRelaunchLog {
/**
* Our special logger for logging issues to. We copy various assets from the
* Minecraft logger to achieve a similar appearance.
*/
public static FMLRelaunchLog log = new FMLRelaunchLog();
static File minecraftHome;
private static boolean configured;
private Logger myLog;
static Side side;
private FMLRelaunchLog()
{
}
/**
* Configure the FML logger and inject tracing printstreams.
*/
private static void configureLogging()
{
log.myLog = LogManager.getLogger("FML");
ThreadContext.put("side", side.name().toLowerCase(Locale.ENGLISH));
configured = true;
FMLRelaunchLog.fine("Injecting tracing printstreams for STDOUT/STDERR.");
System.setOut(new TracingPrintStream(LogManager.getLogger("STDOUT"), System.out));
System.setErr(new TracingPrintStream(LogManager.getLogger("STDERR"), System.err));
}
public static void log(String targetLog, Level level, String format, Object... data)
{
LogManager.getLogger(targetLog).log(level, String.format(format, data));
}
public static void log(Level level, String format, Object... data)
{
if (!configured)
{
configureLogging();
}
log.myLog.log(level, String.format(format, data));
}
public static void log(String targetLog, Level level, Throwable ex, String format, Object... data)
{
LogManager.getLogger(targetLog).log(level, String.format(format, data), ex);
}
public static void log(Level level, Throwable ex, String format, Object... data)
{
if (!configured)
{
configureLogging();
}
log.myLog.log(level, String.format(format, data), ex);
}
public static void severe(String format, Object... data)
{
log(Level.ERROR, format, data);
}
public static void warning(String format, Object... data)
{
log(Level.WARN, format, data);
}
public static void info(String format, Object... data)
{
log(Level.INFO, format, data);
}
public static void fine(String format, Object... data)
{
log(Level.DEBUG, format, data);
}
public static void finer(String format, Object... data)
{
log(Level.TRACE, format, data);
}
public Logger getLogger()
{
return myLog;
}
}
@@ -0,0 +1,38 @@
package net.minecraftforge.fml.relauncher;
import java.security.Permission;
/**
* A custom security manager stopping certain events from happening
* unexpectedly.
*
* @author cpw
*
*/
public class FMLSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm)
{
String permName = perm.getName() != null ? perm.getName() : "missing";
if (permName.startsWith("exitVM"))
{
Class<?>[] classContexts = getClassContext();
String callingClass = classContexts.length > 3 ? classContexts[4].getName() : "none";
String callingParent = classContexts.length > 4 ? classContexts[5].getName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button)
if (!(callingClass.startsWith("net.minecraftforge.fml.") || ( "net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent))))
{
throw new ExitTrappedException();
}
}
else if ("setSecurityManager".equals(permName))
{
throw new SecurityException("Cannot replace the FML security manager");
}
return;
}
public static class ExitTrappedException extends SecurityException {
private static final long serialVersionUID = 1L;
}
}
@@ -0,0 +1,29 @@
package net.minecraftforge.fml.relauncher;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;
public final class FileListHelper {
private static enum CaseInsensitiveFileComparator implements Comparator<File>
{
INSTANCE;
@Override
public int compare(File o1, File o2)
{
return o1 != null && o2 != null ? o1.getName().compareToIgnoreCase(o2.getName()) : o1 == null ? -1 : 1;
}
}
public static File[] sortFileList(File[] files)
{
Arrays.sort(files, CaseInsensitiveFileComparator.INSTANCE);
return files;
}
public static File[] sortFileList(File dir, FilenameFilter filter)
{
File[] files = dir.listFiles(filter);
return sortFileList(files);
}
}
@@ -0,0 +1,34 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* This call hook allows for code to execute at the very early stages of
* minecraft initialization. FML uses it to validate that there is a
* safe environment for further loading of FML.
*
* @author cpw
*
*/
public interface IFMLCallHook extends Callable<Void>
{
/**
* Injected with data from the FML environment:
* "classLoader" : The FML Class Loader
* @param data
*/
void injectData(Map<String,Object> data);
}
@@ -0,0 +1,136 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
/**
* The base plugin that provides class name meta information to FML to
* enhance the classloading lifecycle for mods in FML
*
* @author cpw
*
*/
public interface IFMLLoadingPlugin
{
/**
* Return a list of classes that implements the IClassTransformer interface
* @return a list of classes that implements the IClassTransformer interface
*/
String[] getASMTransformerClass();
/**
* Return a class name that implements "ModContainer" for injection into the mod list
* The "getName" function should return a name that other mods can, if need be,
* depend on.
* Trivially, this modcontainer will be loaded before all regular mod containers,
* which means it will be forced to be "immutable" - not susceptible to normal
* sorting behaviour.
* All other mod behaviours are available however- this container can receive and handle
* normal loading events
*/
String getModContainerClass();
/**
* Return the class name of an implementor of "IFMLCallHook", that will be run, in the
* main thread, to perform any additional setup this coremod may require. It will be
* run <strong>prior</strong> to Minecraft starting, so it CANNOT operate on minecraft
* itself. The game will deliberately crash if this code is detected to trigger a
* minecraft class loading (TODO: implement crash ;) )
*/
String getSetupClass();
/**
* Inject coremod data into this coremod
* This data includes:
* "mcLocation" : the location of the minecraft directory,
* "coremodList" : the list of coremods
* "coremodLocation" : the file this coremod loaded from,
*/
void injectData(Map<String, Object> data);
/**
* Return an optional access transformer class for this coremod. It will be injected post-deobf
* so ensure your ATs conform to the new srgnames scheme.
* @return the name of an access transformer class or null if none is provided
*/
String getAccessTransformerClass();
/**
* Annotate your load plugin with a list of package prefixes that will *not* be
* processed by the ASM transformation stack.
*
* Your plugin, and any transformers should *definitely* be in this list, because
* otherwise you can face problems with the classloader trying to transform classes
* with your transformer, whilst it is *loading* your transformer. Not pretty.
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TransformerExclusions
{
public String[] value() default "";
}
/**
* Use this to target a specific minecraft version for your coremod. It will refuse to load with an error if
* minecraft is not this exact version.
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MCVersion
{
public String value() default "";
}
/**
* Name this coremod something other than the "short class name"
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Name
{
public String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DependsOn
{
public String[] value() default {};
}
/**
* A simple sorting index, interleaved with other tweakers from other sources, as well as FML
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SortingIndex
{
public int value() default 0;
}
}
@@ -0,0 +1,128 @@
package net.minecraftforge.fml.relauncher;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.Level;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class ModListHelper {
public static class JsonModList {
public String repositoryRoot;
public List<String> modRef;
public String parentList;
}
private static File mcDirectory;
private static Set<File> visitedFiles = Sets.newHashSet();
public static final Map<String,File> additionalMods = Maps.newLinkedHashMap();
static void parseModList(File minecraftDirectory)
{
FMLRelaunchLog.fine("Attempting to load commandline specified mods, relative to %s", minecraftDirectory.getAbsolutePath());
mcDirectory = minecraftDirectory;
@SuppressWarnings("unchecked")
Map<String,String> args = (Map<String, String>) Launch.blackboard.get("launchArgs");
String listFile = args.get("--modListFile");
if (listFile != null)
{
parseListFile(listFile);
}
String extraMods = args.get("--mods");
if (extraMods != null)
{
String[] split = extraMods.split(",");
for (String modFile : split)
{
tryAddFile(modFile, null, modFile);
}
}
}
private static void parseListFile(String listFile) {
File f;
try
{
f = new File(mcDirectory, listFile).getCanonicalFile();
} catch (IOException e2)
{
FMLRelaunchLog.log(Level.INFO, e2, "Unable to canonicalize path %s relative to %s", listFile, mcDirectory.getAbsolutePath());
return;
}
if (!f.exists())
{
FMLRelaunchLog.info("Failed to find modList file %s", f.getAbsolutePath());
return;
}
if (visitedFiles.contains(f))
{
FMLRelaunchLog.severe("There appears to be a loop in the modListFile hierarchy. You shouldn't do this!");
throw new RuntimeException("Loop detected, impossible to load modlistfile");
}
String json;
try {
json = Files.asCharSource(f, Charsets.UTF_8).read();
} catch (IOException e1) {
FMLRelaunchLog.log(Level.INFO, e1, "Failed to read modList json file %s.", listFile);
return;
}
Gson gsonParser = new Gson();
JsonModList modList;
try {
modList = gsonParser.fromJson(json, JsonModList.class);
} catch (JsonSyntaxException e) {
FMLRelaunchLog.log(Level.INFO, e, "Failed to parse modList json file %s.", listFile);
return;
}
visitedFiles.add(f);
// We visit parents before children, so the additionalMods list is sorted from parent to child
if (modList.parentList != null)
{
parseListFile(modList.parentList);
}
File repoRoot = new File(modList.repositoryRoot);
if (!repoRoot.exists())
{
FMLRelaunchLog.info("Failed to find the specified repository root %s", modList.repositoryRoot);
return;
}
for (String s : modList.modRef)
{
StringBuilder fileName = new StringBuilder();
StringBuilder genericName = new StringBuilder();
String[] parts = s.split(":");
fileName.append(parts[0].replace('.', File.separatorChar));
genericName.append(parts[0]);
fileName.append(File.separatorChar);
fileName.append(parts[1]).append(File.separatorChar);
genericName.append(":").append(parts[1]);
fileName.append(parts[2]).append(File.separatorChar);
fileName.append(parts[1]).append('-').append(parts[2]);
if (parts.length == 4)
{
fileName.append('-').append(parts[3]);
genericName.append(":").append(parts[3]);
}
fileName.append(".jar");
tryAddFile(fileName.toString(), repoRoot, genericName.toString());
}
}
private static void tryAddFile(String modFileName, File repoRoot, String descriptor) {
File modFile = repoRoot != null ? new File(repoRoot,modFileName) : new File(mcDirectory, modFileName);
if (!modFile.exists())
{
FMLRelaunchLog.info("Failed to find mod file %s (%s)", descriptor, modFile.getAbsolutePath());
}
else
{
FMLRelaunchLog.fine("Adding %s (%s) to the mod list", descriptor, modFile.getAbsolutePath());
additionalMods.put(descriptor, modFile);
}
}
}
@@ -0,0 +1,185 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.relauncher;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Some reflection helper code.
*
* @author cpw
*
*/
public class ReflectionHelper
{
public static class UnableToFindMethodException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private String[] methodNames;
public UnableToFindMethodException(String[] methodNames, Exception failed)
{
super(failed);
this.methodNames = methodNames;
}
}
public static class UnableToFindClassException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private String[] classNames;
public UnableToFindClassException(String[] classNames, Exception err)
{
super(err);
this.classNames = classNames;
}
}
public static class UnableToAccessFieldException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private String[] fieldNameList;
public UnableToAccessFieldException(String[] fieldNames, Exception e)
{
super(e);
this.fieldNameList = fieldNames;
}
}
public static class UnableToFindFieldException extends RuntimeException
{
private static final long serialVersionUID = 1L;
private String[] fieldNameList;
public UnableToFindFieldException(String[] fieldNameList, Exception e)
{
super(e);
this.fieldNameList = fieldNameList;
}
}
public static Field findField(Class<?> clazz, String... fieldNames)
{
Exception failed = null;
for (String fieldName : fieldNames)
{
try
{
Field f = clazz.getDeclaredField(fieldName);
f.setAccessible(true);
return f;
}
catch (Exception e)
{
failed = e;
}
}
throw new UnableToFindFieldException(fieldNames, failed);
}
@SuppressWarnings("unchecked")
public static <T, E> T getPrivateValue(Class <? super E > classToAccess, E instance, int fieldIndex)
{
try
{
Field f = classToAccess.getDeclaredFields()[fieldIndex];
f.setAccessible(true);
return (T) f.get(instance);
}
catch (Exception e)
{
throw new UnableToAccessFieldException(new String[0], e);
}
}
@SuppressWarnings("unchecked")
public static <T, E> T getPrivateValue(Class <? super E > classToAccess, E instance, String... fieldNames)
{
try
{
return (T) findField(classToAccess, fieldNames).get(instance);
}
catch (Exception e)
{
throw new UnableToAccessFieldException(fieldNames, e);
}
}
public static <T, E> void setPrivateValue(Class <? super T > classToAccess, T instance, E value, int fieldIndex)
{
try
{
Field f = classToAccess.getDeclaredFields()[fieldIndex];
f.setAccessible(true);
f.set(instance, value);
}
catch (Exception e)
{
throw new UnableToAccessFieldException(new String[0] , e);
}
}
public static <T, E> void setPrivateValue(Class <? super T > classToAccess, T instance, E value, String... fieldNames)
{
try
{
findField(classToAccess, fieldNames).set(instance, value);
}
catch (Exception e)
{
throw new UnableToAccessFieldException(fieldNames, e);
}
}
@SuppressWarnings("unchecked")
public static Class<? super Object> getClass(ClassLoader loader, String... classNames)
{
Exception err = null;
for (String className : classNames)
{
try
{
return (Class<? super Object>) Class.forName(className, false, loader);
}
catch (Exception e)
{
err = e;
}
}
throw new UnableToFindClassException(classNames, err);
}
public static <E> Method findMethod(Class<? super E> clazz, E instance, String[] methodNames, Class<?>... methodTypes)
{
Exception failed = null;
for (String methodName : methodNames)
{
try
{
Method m = clazz.getDeclaredMethod(methodName, methodTypes);
m.setAccessible(true);
return m;
}
catch (Exception e)
{
failed = e;
}
}
throw new UnableToFindMethodException(methodNames, failed);
}
}
@@ -0,0 +1,53 @@
package net.minecraftforge.fml.relauncher;
import java.lang.reflect.Method;
public class ServerLaunchWrapper {
/**
* @param args
*/
public static void main(String[] args)
{
new ServerLaunchWrapper().run(args);
}
private ServerLaunchWrapper()
{
}
private void run(String[] args)
{
Class<?> launchwrapper = null;
try
{
launchwrapper = Class.forName("net.minecraft.launchwrapper.Launch",true,getClass().getClassLoader());
Class.forName("org.objectweb.asm.Type",true,getClass().getClassLoader());
}
catch (Exception e)
{
System.err.printf("We appear to be missing one or more essential library files.\n" +
"You will need to add them to your server before FML and Forge will run successfully.");
e.printStackTrace(System.err);
System.exit(1);
}
try
{
Method main = launchwrapper.getMethod("main", String[].class);
String[] allArgs = new String[args.length + 2];
allArgs[0] = "--tweakClass";
allArgs[1] = "net.minecraftforge.fml.common.launcher.FMLServerTweaker";
System.arraycopy(args, 0, allArgs, 2, args.length);
main.invoke(null,(Object)allArgs);
}
catch (Exception e)
{
System.err.printf("A problem occurred running the Server launcher.");
e.printStackTrace(System.err);
System.exit(1);
}
}
}
@@ -0,0 +1,43 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
public enum Side {
/**
* The client side. Specifically, an environment where rendering capability exists.
* Usually in the game client.
*/
CLIENT,
/**
* The server side. Specifically, an environment where NO rendering capability exists.
* Usually on the dedicated server.
*/
SERVER;
/**
* @return If this is the server environment
*/
public boolean isServer()
{
return !isClient();
}
/**
* @return if this is the Client environment
*/
public boolean isClient()
{
return this == CLIENT;
}
}
@@ -0,0 +1,41 @@
/*
* 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
*/
package net.minecraftforge.fml.relauncher;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.minecraftforge.fml.common.SidedProxy;
/**
* Marks the associated element as being only available on a certain {@link Side}. This is
* generally meant for internal Forge and FML use only and should only be used on mod classes
* when other more common mechanisms, such as using a {@link SidedProxy} fail to work.
*
* Note, this will <em>only</em> apply to the direct element marked. This code:
* <code> @SideOnly public MyField field = new MyField();</code> will <strong>not</strong> work, as the initializer
* is a separate piece of code to the actual field declaration, and will not be able to find
* it's field on the wrong side.
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface SideOnly
{
public Side value();
}