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,14 @@
package net.minecraftforge.fml.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface API {
String owner();
String provides();
String apiVersion();
}
@@ -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.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declare a variable to be populated by a Bukkit Plugin proxy instance if the bukkit coremod
* is available. It can only be applied to field typed as {@link BukkitProxy}
* Generally it should be used in conjunction with {@link Mod#bukkitPlugin()} specifying the
* plugin to load.
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BukkitPluginRef
{
/**
* A reference (possibly version specific) to a Bukkit Plugin by name, using the name@versionbound
* specification. If this is a bukkit enabled environment the field annotated by this
* will be populated with a {@link BukkitProxy} instance if possible. This proxy will be gotten by
* reflectively calling the "getModProxy" method on the bukkit plugin instance.
* @return The name of the plugin which we will inject into this field
*/
String value();
}
@@ -0,0 +1,24 @@
/*
* 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.common;
/**
* A marker interface for retrieving a proxy to a bukkit plugin.
* Fields associated with {@link BukkitPluginRef} annotations should
* declare this type and cast down if the target is available (not null)
* @author cpw
*
*/
public interface BukkitProxy
{
}
@@ -0,0 +1,68 @@
/*
* 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.common;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.cert.Certificate;
public class CertificateHelper {
private static final String HEXES = "0123456789abcdef";
public static String getFingerprint(Certificate certificate)
{
if (certificate == null)
{
return "NO VALID CERTIFICATE FOUND";
}
try
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = certificate.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
catch (Exception e)
{
return null;
}
}
public static String getFingerprint(ByteBuffer buffer)
{
try
{
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(buffer);
byte[] chksum = digest.digest();
return hexify(chksum);
}
catch (Exception e)
{
return null;
}
}
private static String hexify(byte[] chksum)
{
final StringBuilder hex = new StringBuilder( 2 * chksum.length );
for ( final byte b : chksum ) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
}
@@ -0,0 +1,10 @@
package net.minecraftforge.fml.common;
public class ClassNameUtils
{
public static String shortName(Class<?> clz)
{
String nm = clz.getName();
return nm.indexOf('.') > -1 ? nm.substring(nm.lastIndexOf('.')+1) : nm;
}
}
@@ -0,0 +1,209 @@
/*
* 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.common;
import java.io.File;
import java.security.cert.Certificate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
public class DummyModContainer implements ModContainer
{
private ModMetadata md;
private ArtifactVersion processedVersion;
private String label;
public DummyModContainer(ModMetadata md)
{
this.md = md;
}
public DummyModContainer(String label)
{
this.label = label;
}
public DummyModContainer()
{
}
@Override
public void bindMetadata(MetadataCollection mc)
{
}
@Override
public List<ArtifactVersion> getDependants()
{
return Collections.emptyList();
}
@Override
public List<ArtifactVersion> getDependencies()
{
return Collections.emptyList();
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return Collections.emptySet();
}
@Override
public ModMetadata getMetadata()
{
return md;
}
@Override
public Object getMod()
{
return null;
}
@Override
public String getModId()
{
return md.modId;
}
@Override
public String getName()
{
return md.name;
}
@Override
public String getSortingRules()
{
return "";
}
@Override
public File getSource()
{
return null;
}
@Override
public String getVersion()
{
return md.version;
}
@Override
public boolean matches(Object mod)
{
return false;
}
@Override
public void setEnabledState(boolean enabled)
{
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return false;
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public String getDisplayVersion()
{
return md.version;
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
@Override
public Certificate getSigningCertificate()
{
return null;
}
@Override
public String toString()
{
return md != null ? getModId() : "Dummy Container ("+label+") @" + System.identityHashCode(this);
}
@Override
public Map<String, String> getCustomModProperties()
{
return EMPTY_PROPERTIES;
}
@Override
public Class<?> getCustomResourcePackClass()
{
return null;
}
@Override
public Map<String, String> getSharedModDescriptor()
{
return null;
}
@Override
public Disableable canBeDisabled()
{
return Disableable.NEVER;
}
@Override
public String getGuiClassName()
{
return null;
}
@Override
public List<String> getOwnedPackages()
{
return ImmutableList.of();
}
@Override
public boolean shouldLoadInEnvironment()
{
return true;
}
}
@@ -0,0 +1,40 @@
/*
* 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.common;
import java.io.File;
import java.util.Map.Entry;
import net.minecraftforge.fml.common.EnhancedRuntimeException.WrappedPrintStream;
import com.google.common.collect.SetMultimap;
public class DuplicateModsFoundException extends LoaderException {
private static final long serialVersionUID = 1L;
public SetMultimap<ModContainer,File> dupes;
public DuplicateModsFoundException(SetMultimap<ModContainer, File> dupes) {
this.dupes = dupes;
}
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
stream.println("Duplicate Mods:");
for (Entry<ModContainer, File> e : dupes.entries())
{
stream.println(String.format("\t%s : %s", e.getKey().getModId(), e.getValue().getAbsolutePath()));
}
stream.println("");
}
}
@@ -0,0 +1,89 @@
/*
* Forge Mod Loader
* Copyright (c) 2012-2016 Forge Dev LLC.
* 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
*/
package net.minecraftforge.fml.common;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* RuntimeException that gives subclasses the simple opportunity to write extra data when printing the stack trace.
* Mainly a helper class as printsStackTrace has multiple signatures.
*/
public abstract class EnhancedRuntimeException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public EnhancedRuntimeException() { super(); }
public EnhancedRuntimeException(String message) { super(message); }
public EnhancedRuntimeException(String message, Throwable cause) { super(message, cause); }
public EnhancedRuntimeException(Throwable cause) { super(cause); }
@Override
public String getMessage()
{
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length > 2 && stack[2].getClassName().startsWith("org.apache.logging.log4j."))
{
// This is a bit of a hack to force ourselves to be able to give a extended description when log4j prints this out.
// Sadly this text is displayed AFTER the initial exception line, and before the stack trace. But as the intention
// is to print this to the end user this is what we need to do.
final StringWriter buf = new StringWriter();
String msg = super.getMessage();
if (msg != null)
buf.append(msg);
buf.append('\n');
this.printStackTrace(new WrappedPrintStream()
{
@Override
public void println(String line)
{
buf.append(line).append('\n');
}
});
return buf.toString();
}
return super.getMessage();
}
@Override
public void printStackTrace(final PrintWriter s)
{
printStackTrace(new WrappedPrintStream()
{
@Override
public void println(String line)
{
s.println(line);
}
});
super.printStackTrace(s);
}
public void printStackTrace(final PrintStream s)
{
printStackTrace(new WrappedPrintStream()
{
@Override
public void println(String line)
{
s.println(line);
}
});
super.printStackTrace(s);
}
protected abstract void printStackTrace(WrappedPrintStream stream);
public static abstract class WrappedPrintStream
{
public abstract void println(String line);
}
}
@@ -0,0 +1,771 @@
/*
* 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.common;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.EnumConnectionState;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.handshake.client.C00Handshake;
import net.minecraft.network.login.server.S00PacketDisconnect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IThreadListener;
import net.minecraft.world.World;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.server.FMLServerHandler;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* The main class for non-obfuscated hook handling code
*
* Anything that doesn't require obfuscated or client/server specific code should
* go in this handler
*
* It also contains a reference to the sided handler instance that is valid
* allowing for common code to access specific properties from the obfuscated world
* without a direct dependency
*
* @author cpw
*
*/
public class FMLCommonHandler
{
/**
* The singleton
*/
private static final FMLCommonHandler INSTANCE = new FMLCommonHandler();
/**
* The delegate for side specific data and functions
*/
private IFMLSidedHandler sidedDelegate;
private Class<?> forge;
private boolean noForge;
private List<String> brandings;
private List<String> brandingsNoMC;
private List<ICrashCallable> crashCallables = Lists.newArrayList(Loader.instance().getCallableCrashInformation());
private Set<SaveHandler> handlerSet = Sets.newSetFromMap(new MapMaker().weakKeys().<SaveHandler,Boolean>makeMap());
private WeakReference<SaveHandler> handlerToCheck;
private EventBus eventBus = new EventBus();
private volatile CountDownLatch exitLatch = null;
private FMLCommonHandler()
{
registerCrashCallable(new ICrashCallable()
{
public String call() throws Exception
{
StringBuilder builder = new StringBuilder();
Joiner joiner = Joiner.on("\n ");
for(String coreMod : CoreModManager.getTransformers().keySet())
{
builder.append("\n" + coreMod + "\n ").append(joiner.join(CoreModManager.getTransformers().get(coreMod)));
}
return builder.toString();
}
public String getLabel()
{
return "Loaded coremods (and transformers)";
}
});
}
/**
* The FML event bus. Subscribe here for FML related events
*
* @return the event bus
*/
public EventBus bus()
{
return eventBus;
}
public void beginLoading(IFMLSidedHandler handler)
{
sidedDelegate = handler;
FMLLog.log("MinecraftForge", Level.INFO, "Attempting early MinecraftForge initialization");
callForgeMethod("initialize");
callForgeMethod("registerCrashCallable");
FMLLog.log("MinecraftForge", Level.INFO, "Completed early MinecraftForge initialization");
}
/**
* @return the instance
*/
public static FMLCommonHandler instance()
{
return INSTANCE;
}
/**
* Find the container that associates with the supplied mod object
* @param mod
*/
public ModContainer findContainerFor(Object mod)
{
if (mod instanceof String)
{
return Loader.instance().getIndexedModList().get(mod);
}
else
{
return Loader.instance().getReversedModObjectList().get(mod);
}
}
/**
* Get the forge mod loader logging instance (goes to the forgemodloader log file)
* @return The log instance for the FML log file
*/
public Logger getFMLLogger()
{
return FMLLog.getLogger();
}
public Side getSide()
{
return sidedDelegate.getSide();
}
/**
* Return the effective side for the context in the game. This is dependent
* on thread analysis to try and determine whether the code is running in the
* server or not. Use at your own risk
*/
public Side getEffectiveSide()
{
Thread thr = Thread.currentThread();
if (thr.getName().equals("Server thread") || thr.getName().startsWith("Netty Server IO"))
{
return Side.SERVER;
}
return Side.CLIENT;
}
/**
* Raise an exception
*/
public void raiseException(Throwable exception, String message, boolean stopGame)
{
FMLLog.log(Level.ERROR, exception, "Something raised an exception. The message was '%s'. 'stopGame' is %b", message, stopGame);
if (stopGame)
{
getSidedDelegate().haltGame(message,exception);
}
}
private Class<?> findMinecraftForge()
{
if (forge==null && !noForge)
{
try {
forge = Class.forName("net.minecraftforge.common.MinecraftForge");
} catch (Exception ex) {
noForge = true;
}
}
return forge;
}
private Object callForgeMethod(String method)
{
if (noForge)
return null;
try
{
return findMinecraftForge().getMethod(method).invoke(null);
}
catch (Exception e)
{
// No Forge installation
return null;
}
}
public void computeBranding()
{
if (brandings == null)
{
Builder<String> brd = ImmutableList.<String>builder();
brd.add(Loader.instance().getMCVersionString());
brd.add(Loader.instance().getMCPVersionString());
brd.add("FML v"+Loader.instance().getFMLVersionString());
String forgeBranding = (String) callForgeMethod("getBrandingVersion");
if (!Strings.isNullOrEmpty(forgeBranding))
{
brd.add(forgeBranding);
}
if (sidedDelegate!=null)
{
brd.addAll(sidedDelegate.getAdditionalBrandingInformation());
}
if (Loader.instance().getFMLBrandingProperties().containsKey("fmlbranding"))
{
brd.add(Loader.instance().getFMLBrandingProperties().get("fmlbranding"));
}
int tModCount = Loader.instance().getModList().size();
int aModCount = Loader.instance().getActiveModList().size();
brd.add(String.format("%d mod%s loaded, %d mod%s active", tModCount, tModCount!=1 ? "s" :"", aModCount, aModCount!=1 ? "s" :"" ));
brandings = brd.build();
brandingsNoMC = brandings.subList(1, brandings.size());
}
}
public List<String> getBrandings(boolean includeMC)
{
if (brandings == null)
{
computeBranding();
}
return includeMC ? ImmutableList.copyOf(brandings) : ImmutableList.copyOf(brandingsNoMC);
}
public IFMLSidedHandler getSidedDelegate()
{
return sidedDelegate;
}
public void onPostServerTick()
{
bus().post(new TickEvent.ServerTickEvent(Phase.END));
}
/**
* Every tick just after world and other ticks occur
*/
public void onPostWorldTick(World world)
{
bus().post(new TickEvent.WorldTickEvent(Side.SERVER, Phase.END, world));
}
public void onPreServerTick()
{
bus().post(new TickEvent.ServerTickEvent(Phase.START));
}
/**
* Every tick just before world and other ticks occur
*/
public void onPreWorldTick(World world)
{
bus().post(new TickEvent.WorldTickEvent(Side.SERVER, Phase.START, world));
}
public boolean handleServerAboutToStart(MinecraftServer server)
{
return Loader.instance().serverAboutToStart(server);
}
public boolean handleServerStarting(MinecraftServer server)
{
return Loader.instance().serverStarting(server);
}
public void handleServerStarted()
{
Loader.instance().serverStarted();
sidedDelegate.allowLogins();
}
public void handleServerStopping()
{
Loader.instance().serverStopping();
}
public File getSavesDirectory() {
return sidedDelegate.getSavesDirectory();
}
public MinecraftServer getMinecraftServerInstance()
{
return sidedDelegate.getServer();
}
public void showGuiScreen(Object clientGuiElement)
{
sidedDelegate.showGuiScreen(clientGuiElement);
}
public void queryUser(StartupQuery query) throws InterruptedException
{
sidedDelegate.queryUser(query);
}
public void onServerStart(MinecraftServer dedicatedServer)
{
FMLServerHandler.instance();
sidedDelegate.beginServerLoading(dedicatedServer);
}
public void onServerStarted()
{
sidedDelegate.finishServerLoading();
}
public void onPreClientTick()
{
bus().post(new TickEvent.ClientTickEvent(Phase.START));
}
public void onPostClientTick()
{
bus().post(new TickEvent.ClientTickEvent(Phase.END));
}
public void onRenderTickStart(float timer)
{
bus().post(new TickEvent.RenderTickEvent(Phase.START, timer));
}
public void onRenderTickEnd(float timer)
{
bus().post(new TickEvent.RenderTickEvent(Phase.END, timer));
}
public void onPlayerPreTick(EntityPlayer player)
{
bus().post(new TickEvent.PlayerTickEvent(Phase.START, player));
}
public void onPlayerPostTick(EntityPlayer player)
{
bus().post(new TickEvent.PlayerTickEvent(Phase.END, player));
}
public void registerCrashCallable(ICrashCallable callable)
{
crashCallables.add(callable);
}
public void enhanceCrashReport(CrashReport crashReport, CrashReportCategory category)
{
for (ICrashCallable call: crashCallables)
{
category.addCrashSectionCallable(call.getLabel(), call);
}
}
public void handleWorldDataSave(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
{
for (ModContainer mc : Loader.instance().getModList())
{
if (mc instanceof InjectedModContainer)
{
WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
if (wac != null)
{
NBTTagCompound dataForWriting = wac.getDataForWriting(handler, worldInfo);
tagCompound.setTag(mc.getModId(), dataForWriting);
}
}
}
}
public void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
{
if (getEffectiveSide()!=Side.SERVER)
{
return;
}
if (handlerSet.contains(handler))
{
return;
}
handlerSet.add(handler);
handlerToCheck = new WeakReference<SaveHandler>(handler); // for confirmBackupLevelDatUse
Map<String,NBTBase> additionalProperties = Maps.newHashMap();
worldInfo.setAdditionalProperties(additionalProperties);
for (ModContainer mc : Loader.instance().getModList())
{
if (mc instanceof InjectedModContainer)
{
WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
if (wac != null)
{
wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(mc.getModId()));
}
}
}
}
public void confirmBackupLevelDatUse(SaveHandler handler)
{
if (handlerToCheck == null || handlerToCheck.get() != handler) {
// only run if the save has been initially loaded
handlerToCheck = null;
return;
}
String text = "Forge Mod Loader detected that the backup level.dat is being used.\n\n" +
"This may happen due to a bug or corruption, continuing can damage\n" +
"your world beyond repair or lose data / progress.\n\n" +
"It's recommended to create a world backup before continuing.";
boolean confirmed = StartupQuery.confirm(text);
if (!confirmed) StartupQuery.abort();
}
public boolean shouldServerBeKilledQuietly()
{
if (sidedDelegate == null)
{
return false;
}
return sidedDelegate.shouldServerShouldBeKilledQuietly();
}
/**
* Make handleExit() wait for handleServerStopped().
*
* For internal use only!
*/
public void expectServerStopped()
{
exitLatch = new CountDownLatch(1);
}
/**
* Delayed System.exit() until the server is actually stopped/done saving.
*
* For internal use only!
*
* @param retVal Exit code for System.exit()
*/
public void handleExit(int retVal)
{
CountDownLatch latch = exitLatch;
if (latch != null)
{
try
{
FMLLog.info("Waiting for the server to terminate/save.");
if (!latch.await(10, TimeUnit.SECONDS))
{
FMLLog.warning("The server didn't stop within 10 seconds, exiting anyway.");
}
else
{
FMLLog.info("Server terminated.");
}
}
catch (InterruptedException e)
{
FMLLog.warning("Interrupted wait, exiting.");
}
}
System.exit(retVal);
}
public void handleServerStopped()
{
sidedDelegate.serverStopped();
MinecraftServer server = getMinecraftServerInstance();
Loader.instance().serverStopped();
// FORCE the internal server to stop: hello optifine workaround!
if (server!=null) ObfuscationReflectionHelper.setPrivateValue(MinecraftServer.class, server, false, "field_71316"+"_v", "u", "serverStopped");
// allow any pending exit to continue, clear exitLatch
CountDownLatch latch = exitLatch;
if (latch != null)
{
latch.countDown();
exitLatch = null;
}
}
public String getModName()
{
List<String> modNames = Lists.newArrayListWithExpectedSize(3);
modNames.add("fml");
if (!noForge)
{
modNames.add("forge");
}
if (Loader.instance().getFMLBrandingProperties().containsKey("snooperbranding"))
{
modNames.add(Loader.instance().getFMLBrandingProperties().get("snooperbranding"));
}
return Joiner.on(',').join(modNames);
}
public void addModToResourcePack(ModContainer container)
{
sidedDelegate.addModAsResource(container);
}
public String getCurrentLanguage()
{
return sidedDelegate.getCurrentLanguage();
}
public void bootstrap()
{
}
public NetworkManager getClientToServerNetworkManager()
{
return sidedDelegate.getClientToServerNetworkManager();
}
public void fireMouseInput()
{
bus().post(new InputEvent.MouseInputEvent());
}
public void fireKeyInput()
{
bus().post(new InputEvent.KeyInputEvent());
}
public void firePlayerChangedDimensionEvent(EntityPlayer player, int fromDim, int toDim)
{
bus().post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim));
}
public void firePlayerLoggedIn(EntityPlayer player)
{
bus().post(new PlayerEvent.PlayerLoggedInEvent(player));
}
public void firePlayerLoggedOut(EntityPlayer player)
{
bus().post(new PlayerEvent.PlayerLoggedOutEvent(player));
}
public void firePlayerRespawnEvent(EntityPlayer player)
{
bus().post(new PlayerEvent.PlayerRespawnEvent(player));
}
public void firePlayerItemPickupEvent(EntityPlayer player, EntityItem item)
{
bus().post(new PlayerEvent.ItemPickupEvent(player, item));
}
public void firePlayerCraftingEvent(EntityPlayer player, ItemStack crafted, IInventory craftMatrix)
{
bus().post(new PlayerEvent.ItemCraftedEvent(player, crafted, craftMatrix));
}
public void firePlayerSmeltedEvent(EntityPlayer player, ItemStack smelted)
{
bus().post(new PlayerEvent.ItemSmeltedEvent(player, smelted));
}
public INetHandler getClientPlayHandler()
{
return sidedDelegate.getClientPlayHandler();
}
public void fireNetRegistrationEvent(NetworkManager manager, Set<String> channelSet, String channel, Side side)
{
sidedDelegate.fireNetRegistrationEvent(bus(), manager, channelSet, channel, side);
}
public boolean shouldAllowPlayerLogins()
{
return sidedDelegate.shouldAllowPlayerLogins();
}
/**
* Process initial Handshake packet, kicks players from the server if they are connecting while we are starting up.
* Also verifies the client has the FML marker.
*
* @param packet Handshake Packet
* @param manager Network connection
* @return True to allow connection, otherwise False.
*/
public boolean handleServerHandshake(C00Handshake packet, NetworkManager manager)
{
if (!shouldAllowPlayerLogins())
{
ChatComponentText text = new ChatComponentText("Server is still starting! Please wait before reconnecting.");
FMLLog.info("Disconnecting Player: " + text.getUnformattedText());
manager.sendPacket(new S00PacketDisconnect(text));
manager.closeChannel(text);
return false;
}
if (packet.getRequestedState() == EnumConnectionState.LOGIN && (!NetworkRegistry.INSTANCE.isVanillaAccepted(Side.CLIENT) && !packet.hasFMLMarker()))
{
manager.setConnectionState(EnumConnectionState.LOGIN);
ChatComponentText text = new ChatComponentText("This server requires FML/Forge to be installed. Contact your server admin for more details.");
FMLLog.info("Disconnecting Player: " + text.getUnformattedText());
manager.sendPacket(new S00PacketDisconnect(text));
manager.closeChannel(text);
return false;
}
manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.hasFMLMarker());
return true;
}
public void processWindowMessages()
{
if (sidedDelegate == null) return;
sidedDelegate.processWindowMessages();
}
/**
* Used to exit from java, with system exit preventions in place. Will be tidy about it and just log a message,
* unless debugging is enabled
*
* @param exitCode The exit code
* @param hardExit Perform a halt instead of an exit (only use when the world is unsavable) - read the warnings at {@link Runtime#halt(int)}
*/
public void exitJava(int exitCode, boolean hardExit)
{
FMLLog.log(Level.INFO, "Java has been asked to exit (code %d) by %s.", exitCode, Thread.currentThread().getStackTrace()[1]);
if (hardExit)
{
FMLLog.log(Level.INFO, "This is an abortive exit and could cause world corruption or other things");
}
if (Boolean.parseBoolean(System.getProperty("fml.debugExit", "false")))
{
FMLLog.log(Level.INFO, new Throwable(), "Exit trace");
}
else
{
FMLLog.log(Level.INFO, "If this was an unexpected exit, use -Dfml.debugExit=true as a JVM argument to find out where it was called");
}
if (hardExit)
{
Runtime.getRuntime().halt(exitCode);
}
else
{
Runtime.getRuntime().exit(exitCode);
}
}
public IThreadListener getWorldThread(INetHandler net)
{
return sidedDelegate.getWorldThread(net);
}
public static void callFuture(FutureTask task)
{
try
{
task.run();
task.get(); // Forces the exception to be thrown if any
}
catch (InterruptedException e)
{
FMLLog.log(Level.FATAL, e, "Exception caught executing FutureTask: " + e.toString());
}
catch (ExecutionException e)
{
FMLLog.log(Level.FATAL, e, "Exception caught executing FutureTask: " + e.toString());
}
}
/**
* Loads a lang file, first searching for a marker to enable the 'extended' format {escape charaters}
* If the marker is not found it simply returns and let the vanilla code load things.
* The Marker is 'PARSE_ESCAPES' by itself on a line starting with '#' as such:
* #PARSE_ESCAPES
*
* @param table The Map to load each key/value pair into.
* @param inputstream Input stream containing the lang file.
* @return A new InputStream that vanilla uses to load normal Lang files, Null if this is a 'enhanced' file and loading is done.
*/
public InputStream loadLanguage(Map<String, String> table, InputStream inputstream) throws IOException
{
byte[] data = IOUtils.toByteArray(inputstream);
boolean isEnhanced = false;
for (String line : IOUtils.readLines(new ByteArrayInputStream(data), Charsets.UTF_8))
{
if (!line.isEmpty() && line.charAt(0) == '#')
{
line = line.substring(1).trim();
if (line.equals("PARSE_ESCAPES"))
{
isEnhanced = true;
break;
}
}
}
if (!isEnhanced)
return new ByteArrayInputStream(data);
Properties props = new Properties();
props.load(new InputStreamReader(new ByteArrayInputStream(data), Charsets.UTF_8));
for (Entry e : props.entrySet())
{
table.put((String)e.getKey(), (String)e.getValue());
}
props.clear();
return null;
}
public String stripSpecialChars(String message)
{
return sidedDelegate != null ? sidedDelegate.stripSpecialChars(message) : message;
}
}
@@ -0,0 +1,375 @@
/*
* 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.common;
import java.io.File;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.fml.client.FMLFileResourcePack;
import net.minecraftforge.fml.client.FMLFolderResourcePack;
import net.minecraftforge.fml.common.asm.FMLSanityChecker;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkCheckHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.common.registry.GameData;
import net.minecraftforge.fml.common.registry.VillagerRegistry;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Level;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
/**
* @author cpw
*
*/
public class FMLContainer extends DummyModContainer implements WorldAccessContainer
{
public FMLContainer()
{
super(new ModMetadata());
ModMetadata meta = getMetadata();
meta.modId="FML";
meta.name="Forge Mod Loader";
meta.version=Loader.instance().getFMLVersionString();
meta.credits="Made possible with help from many people";
meta.authorList=Arrays.asList("cpw", "LexManos", "Player");
meta.description="The Forge Mod Loader provides the ability for systems to load mods " +
"from the file system. It also provides key capabilities for mods to be able " +
"to cooperate and provide a good modding environment. ";
meta.url="https://github.com/MinecraftForge/FML/wiki";
meta.updateUrl="https://github.com/MinecraftForge/FML/wiki";
meta.screenshots=new String[0];
meta.logoFile="";
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
bus.register(this);
return true;
}
@Subscribe
public void modConstruction(FMLConstructionEvent evt)
{
NetworkRegistry.INSTANCE.register(this, this.getClass(), null, evt.getASMHarvestedData());
FMLNetworkHandler.registerChannel(this, evt.getSide());
}
@Subscribe
public void modPreinitialization(FMLPreInitializationEvent evt)
{
// Initialize the villager registry
VillagerRegistry.instance();
}
@NetworkCheckHandler
public boolean checkModLists(Map<String,String> modList, Side side)
{
return Loader.instance().checkRemoteModList(modList,side);
}
@Override
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound fmlData = new NBTTagCompound();
NBTTagList modList = new NBTTagList();
for (ModContainer mc : Loader.instance().getActiveModList())
{
NBTTagCompound mod = new NBTTagCompound();
mod.setString("ModId", mc.getModId());
mod.setString("ModVersion", mc.getVersion());
modList.appendTag(mod);
}
fmlData.setTag("ModList", modList);
NBTTagCompound registries = new NBTTagCompound();
fmlData.setTag("Registries", registries);
FMLLog.fine("Gathering id map for writing to world save %s", info.getWorldName());
GameData.GameDataSnapshot dataSnapshot = GameData.takeSnapshot();
for (Map.Entry<String, GameData.GameDataSnapshot.Entry> e : dataSnapshot.entries.entrySet())
{
NBTTagCompound data = new NBTTagCompound();
registries.setTag(e.getKey(), data);
NBTTagList ids = new NBTTagList();
for (Entry<String, Integer> item : e.getValue().ids.entrySet())
{
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", item.getKey());
tag.setInteger("V", item.getValue());
ids.appendTag(tag);
}
data.setTag("ids", ids);
NBTTagList aliases = new NBTTagList();
for (Entry<String, String> entry : e.getValue().aliases.entrySet())
{
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", entry.getKey());
tag.setString("V", entry.getValue());
aliases.appendTag(tag);
}
data.setTag("aliases", aliases);
NBTTagList subs = new NBTTagList();
for (String entry : e.getValue().substitutions)
{
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", entry);
subs.appendTag(tag);
}
data.setTag("substitutions", subs);
int[] blocked = new int[e.getValue().blocked.size()];
int idx = 0;
for (Integer i : e.getValue().blocked)
{
blocked[idx++] = i;
}
data.setIntArray("blocked", blocked);
}
return fmlData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag)
{
if (tag.hasKey("ModList"))
{
NBTTagList modList = tag.getTagList("ModList", (byte)10);
for (int i = 0; i < modList.tagCount(); i++)
{
NBTTagCompound mod = modList.getCompoundTagAt(i);
String modId = mod.getString("ModId");
String modVersion = mod.getString("ModVersion");
ModContainer container = Loader.instance().getIndexedModList().get(modId);
if (container == null)
{
FMLLog.log("fml.ModTracker", Level.ERROR, "This world was saved with mod %s which appears to be missing, things may not work well", modId);
continue;
}
if (!modVersion.equals(container.getVersion()))
{
FMLLog.log("fml.ModTracker", Level.INFO, "This world was saved with mod %s version %s and it is now at version %s, things may not work well", modId, modVersion, container.getVersion());
}
}
}
List<String> failedElements = null;
if (tag.hasKey("ModItemData")) // Pre 1.7
{
GameData.GameDataSnapshot snapshot = new GameData.GameDataSnapshot();
GameData.GameDataSnapshot.Entry items = new GameData.GameDataSnapshot.Entry();
snapshot.entries.put("fml:blocks", new GameData.GameDataSnapshot.Entry());
snapshot.entries.put("fml:items", items);
FMLLog.info("Attempting to convert old world data to new system. This may be trouble!");
NBTTagList modList = tag.getTagList("ModItemData", (byte)10);
for (int i = 0; i < modList.tagCount(); i++)
{
NBTTagCompound data = modList.getCompoundTagAt(i);
String forcedModId = data.hasKey("ForcedModId") ? data.getString("ForcedModId") : null;
String forcedName = data.hasKey("ForcedName") ? data.getString("ForcedName") : null;
if (forcedName == null)
{
FMLLog.warning("Found unlabelled item in world save, this may cause problems. The item type %s:%d will not be present", data.getString("ItemType"), data.getInteger("ordinal"));
}
else
{
// all entries are Items, blocks were only saved through their ItemBlock
String itemLabel = String.format("%s:%s", forcedModId != null ? forcedModId : data.getString("ModId"), forcedName);
items.ids.put(itemLabel, data.getInteger("ItemId"));
}
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
else if (tag.hasKey("ItemData")) // 1.7
{
GameData.GameDataSnapshot snapshot = new GameData.GameDataSnapshot();
GameData.GameDataSnapshot.Entry blocks = new GameData.GameDataSnapshot.Entry();
GameData.GameDataSnapshot.Entry items = new GameData.GameDataSnapshot.Entry();
snapshot.entries.put("fml:blocks", blocks);
snapshot.entries.put("fml:items", items);
NBTTagList list = tag.getTagList("ItemData", 10);
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound e = list.getCompoundTagAt(i);
String name = e.getString("K");
if (name.charAt(0) == '\u0001')
blocks.ids.put(name.substring(1), e.getInteger("V"));
else if (name.charAt(0) == '\u0002')
items.ids.put(name.substring(1), e.getInteger("V"));
}
Set<Integer> blockedIds = new HashSet<Integer>();
if (!tag.hasKey("BlockedItemIds")) // no blocked id info -> old 1.7 save
{
// old early 1.7 save potentially affected by the registry mapping bug
// fix the ids the best we can...
GameData.fixBrokenIds(blocks, items, blockedIds);
}
else
{
for (int id : tag.getIntArray("BlockedItemIds"))
{
blockedIds.add(id);
}
}
blocks.blocked.addAll(blockedIds);
items.blocked.addAll(blockedIds);
list = tag.getTagList("BlockAliases", 10);
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound dataTag = list.getCompoundTagAt(i);
blocks.aliases.put(dataTag.getString("K"), dataTag.getString("V"));
}
if (tag.hasKey("BlockSubstitutions", 9))
{
list = tag.getTagList("BlockSubstitutions", 10);
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound dataTag = list.getCompoundTagAt(i);
blocks.substitutions.add(dataTag.getString("K"));
}
}
list = tag.getTagList("ItemAliases", 10);
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound dataTag = list.getCompoundTagAt(i);
items.aliases.put(dataTag.getString("K"), dataTag.getString("V"));
}
if (tag.hasKey("ItemSubstitutions", 9))
{
list = tag.getTagList("ItemSubstitutions", 10);
for (int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound dataTag = list.getCompoundTagAt(i);
items.substitutions.add(dataTag.getString("K"));
}
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list
{
GameData.GameDataSnapshot snapshot = new GameData.GameDataSnapshot();
NBTTagCompound regs = tag.getCompoundTag("Registries");
for (String key : (Set<String>)regs.getKeySet())
{
GameData.GameDataSnapshot.Entry entry = new GameData.GameDataSnapshot.Entry();
snapshot.entries.put(key, entry);
NBTTagList list = regs.getCompoundTag(key).getTagList("ids", 10);
for (int x = 0; x < list.tagCount(); x++)
{
NBTTagCompound e = list.getCompoundTagAt(x);
entry.ids.put(e.getString("K"), e.getInteger("V"));
}
list = regs.getCompoundTag(key).getTagList("aliases", 10);
for (int x = 0; x < list.tagCount(); x++)
{
NBTTagCompound e = list.getCompoundTagAt(x);
entry.aliases.put(e.getString("K"), e.getString("V"));
}
list = regs.getCompoundTag(key).getTagList("substitutions", 10);
for (int x = 0; x < list.tagCount(); x++)
{
NBTTagCompound e = list.getCompoundTagAt(x);
entry.substitutions.add(e.getString("K"));
}
int[] blocked = regs.getCompoundTag(key).getIntArray("blocked");
for (int i : blocked)
{
entry.blocked.add(i);
}
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
if (failedElements != null && !failedElements.isEmpty())
{
String text = "Forge Mod Loader could not load this save.\n\n" +
"There are "+failedElements.size()+" unassigned blocks and items in this save.\n" +
"You will not be able to load until they are present again.\n\n" +
"Missing Blocks/Items:\n";
for (String s : failedElements) text += s + "\n";
StartupQuery.notify(text);
StartupQuery.abort();
}
}
@Override
public Certificate getSigningCertificate()
{
Certificate[] certificates = getClass().getProtectionDomain().getCodeSource().getCertificates();
return certificates != null ? certificates[0] : null;
}
@Override
public File getSource()
{
return FMLSanityChecker.fmlLocation;
}
@Override
public Class<?> getCustomResourcePackClass()
{
return getSource().isDirectory() ? FMLFolderResourcePack.class : FMLFileResourcePack.class;
}
@Override
public String getGuiClassName()
{
return "net.minecraftforge.fml.client.FMLConfigGuiFactory";
}
@Override
public Object getMod()
{
return this;
}
}
@@ -0,0 +1,6 @@
package net.minecraftforge.fml.common;
public interface FMLContainerHolder
{
ModContainer getFMLContainer();
}
@@ -0,0 +1,84 @@
/*
* 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.common;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
@SuppressWarnings("static-access")
public class FMLLog
{
private static net.minecraftforge.fml.relauncher.FMLRelaunchLog coreLog = net.minecraftforge.fml.relauncher.FMLRelaunchLog.log;
public static void log(String targetLog, Level level, String format, Object... data)
{
coreLog.log(targetLog, level, format, data);
}
public static void log(Level level, String format, Object... data)
{
coreLog.log(level, format, data);
}
public static void log(String targetLog, Level level, Throwable ex, String format, Object... data)
{
coreLog.log(targetLog, level, ex, format, data);
}
public static void log(Level level, Throwable ex, String format, Object... data)
{
coreLog.log(level, ex, format, data);
}
public static void severe(String format, Object... data)
{
log(Level.ERROR, format, data);
}
public static void bigWarning(String format, Object... data)
{
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
log(Level.WARN, "****************************************");
log(Level.WARN, "* "+format, data);
for (int i = 2; i < 8 && i < trace.length; i++)
{
log(Level.WARN, "* at %s%s", trace[i].toString(), i == 7 ? "..." : "");
}
log(Level.WARN, "****************************************");
}
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 static Logger getLogger()
{
return coreLog.getLogger();
}
}
@@ -0,0 +1,666 @@
/*
* 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.common;
import java.io.File;
import java.io.FileInputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.Mod.Metadata;
import net.minecraftforge.fml.common.asm.transformers.BlamingTransformer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLEvent;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class FMLModContainer implements ModContainer
{
private Object modInstance;
private File source;
private ModMetadata modMetadata;
private String className;
private Map<String, Object> descriptor;
private boolean enabled = true;
private String internalVersion;
private boolean overridesMetadata;
private EventBus eventBus;
private LoadController controller;
private DefaultArtifactVersion processedVersion;
private String annotationDependencies;
private VersionRange minecraftAccepted;
private boolean fingerprintNotPresent;
private Set<String> sourceFingerprints;
private Certificate certificate;
private String modLanguage;
private ILanguageAdapter languageAdapter;
private Disableable disableability;
private ListMultimap<Class<? extends FMLEvent>,Method> eventMethods;
private Map<String, String> customModProperties;
private ModCandidate candidate;
public FMLModContainer(String className, ModCandidate container, Map<String,Object> modDescriptor)
{
this.className = className;
this.source = container.getModContainer();
this.candidate = container;
this.descriptor = modDescriptor;
this.eventMethods = ArrayListMultimap.create();
this.modLanguage = (String) modDescriptor.get("modLanguage");
String languageAdapterType = (String)modDescriptor.get("modLanguageAdapter");
if (Strings.isNullOrEmpty(languageAdapterType))
{
this.languageAdapter = "scala".equals(modLanguage) ? new ILanguageAdapter.ScalaAdapter() : new ILanguageAdapter.JavaAdapter();
}
else
{
try
{
this.languageAdapter = (ILanguageAdapter)Class.forName(languageAdapterType, true, Loader.instance().getModClassLoader()).newInstance();
FMLLog.finer("Using custom language adapter %s (type %s) for %s (modid %s)", this.languageAdapter, languageAdapterType, this.className, getModId());
}
catch (Exception ex)
{
FMLLog.log(Level.ERROR, ex, "Error constructing custom mod language adapter %s (referenced by %s) (modid: %s)", languageAdapterType, this.className, getModId());
throw new LoaderException(ex);
}
}
}
private ILanguageAdapter getLanguageAdapter()
{
return languageAdapter;
}
@Override
public String getModId()
{
return (String) descriptor.get("modid");
}
@Override
public String getName()
{
return modMetadata.name;
}
@Override
public String getVersion()
{
return internalVersion;
}
@Override
public File getSource()
{
return source;
}
@Override
public ModMetadata getMetadata()
{
return modMetadata;
}
@Override
public void bindMetadata(MetadataCollection mc)
{
modMetadata = mc.getMetadataForId(getModId(), descriptor);
if (descriptor.containsKey("useMetadata"))
{
overridesMetadata = !((Boolean)descriptor.get("useMetadata")).booleanValue();
}
if (overridesMetadata || !modMetadata.useDependencyInformation)
{
Set<ArtifactVersion> requirements = Sets.newHashSet();
List<ArtifactVersion> dependencies = Lists.newArrayList();
List<ArtifactVersion> dependants = Lists.newArrayList();
annotationDependencies = (String) descriptor.get("dependencies");
Loader.instance().computeDependencies(annotationDependencies, requirements, dependencies, dependants);
dependants.addAll(Loader.instance().getInjectedBefore(getModId()));
dependencies.addAll(Loader.instance().getInjectedAfter(getModId()));
modMetadata.requiredMods = requirements;
modMetadata.dependencies = dependencies;
modMetadata.dependants = dependants;
FMLLog.log(getModId(), Level.TRACE, "Parsed dependency info : %s %s %s", requirements, dependencies, dependants);
}
else
{
FMLLog.log(getModId(), Level.TRACE, "Using mcmod dependency info : %s %s %s", modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants);
}
if (Strings.isNullOrEmpty(modMetadata.name))
{
FMLLog.log(getModId(), Level.INFO,"Mod %s is missing the required element 'name'. Substituting %s", getModId(), getModId());
modMetadata.name = getModId();
}
internalVersion = (String) descriptor.get("version");
if (Strings.isNullOrEmpty(internalVersion))
{
Properties versionProps = searchForVersionProperties();
if (versionProps != null)
{
internalVersion = versionProps.getProperty(getModId()+".version");
FMLLog.log(getModId(), Level.DEBUG, "Found version %s for mod %s in version.properties, using", internalVersion, getModId());
}
}
if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version))
{
FMLLog.log(getModId(), Level.WARN, "Mod %s is missing the required element 'version' and a version.properties file could not be found. Falling back to metadata version %s", getModId(), modMetadata.version);
internalVersion = modMetadata.version;
}
if (Strings.isNullOrEmpty(internalVersion))
{
FMLLog.log(getModId(), Level.WARN, "Mod %s is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId());
modMetadata.version = internalVersion = "1.0";
}
String mcVersionString = (String) descriptor.get("acceptedMinecraftVersions");
if (!Strings.isNullOrEmpty(mcVersionString))
{
minecraftAccepted = VersionParser.parseRange(mcVersionString);
}
else
{
minecraftAccepted = Loader.instance().getMinecraftModContainer().getStaticVersionRange();
}
}
public Properties searchForVersionProperties()
{
try
{
FMLLog.log(getModId(), Level.DEBUG,"Attempting to load the file version.properties from %s to locate a version number for %s", getSource().getName(), getModId());
Properties version = null;
if (getSource().isFile())
{
ZipFile source = new ZipFile(getSource());
ZipEntry versionFile = source.getEntry("version.properties");
if (versionFile!=null)
{
version = new Properties();
version.load(source.getInputStream(versionFile));
}
source.close();
}
else if (getSource().isDirectory())
{
File propsFile = new File(getSource(),"version.properties");
if (propsFile.exists() && propsFile.isFile())
{
version = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
version.load(fis);
fis.close();
}
}
return version;
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log(getModId(), Level.TRACE, "Failed to find a usable version.properties file");
return null;
}
}
@Override
public void setEnabledState(boolean enabled)
{
this.enabled = enabled;
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return modMetadata.requiredMods;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return modMetadata.dependencies;
}
@Override
public List<ArtifactVersion> getDependants()
{
return modMetadata.dependants;
}
@Override
public String getSortingRules()
{
return ((overridesMetadata || !modMetadata.useDependencyInformation) ? Strings.nullToEmpty(annotationDependencies) : modMetadata.printableSortingRules());
}
@Override
public boolean matches(Object mod)
{
return mod == modInstance;
}
@Override
public Object getMod()
{
return modInstance;
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
if (this.enabled)
{
FMLLog.log(getModId(), Level.DEBUG, "Enabling mod %s", getModId());
this.eventBus = bus;
this.controller = controller;
eventBus.register(this);
return true;
}
else
{
return false;
}
}
@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception
{
Method factoryMethod = null;
for (Method m : clazz.getDeclaredMethods())
{
for (Annotation a : m.getAnnotations())
{
if (a.annotationType().equals(Mod.EventHandler.class))
{
if (m.getParameterTypes().length == 1 && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0]))
{
m.setAccessible(true);
eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0],m);
}
else
{
FMLLog.log(getModId(), Level.ERROR,"The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName());
}
}
else if (a.annotationType().equals(Mod.InstanceFactory.class))
{
if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && factoryMethod == null)
{
m.setAccessible(true);
factoryMethod = m;
}
else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0))
{
FMLLog.log(getModId(), Level.ERROR, "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)", m.getName(), Arrays.asList(m.getParameterTypes()));
}
else if (factoryMethod != null)
{
FMLLog.log(getModId(), Level.ERROR, "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes()));
}
}
}
}
return factoryMethod;
}
private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception
{
SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this);
parseSimpleFieldAnnotation(annotations, Instance.class.getName(), new Function<ModContainer, Object>()
{
@Override
public Object apply(ModContainer mc)
{
return mc.getMod();
}
});
parseSimpleFieldAnnotation(annotations, Metadata.class.getName(), new Function<ModContainer, Object>()
{
@Override
public Object apply(ModContainer mc)
{
return mc.getMetadata();
}
});
}
private void parseSimpleFieldAnnotation(SetMultimap<String, ASMData> annotations, String annotationClassName, Function<ModContainer, Object> retreiver) throws IllegalAccessException
{
String[] annName = annotationClassName.split("\\.");
String annotationName = annName[annName.length - 1];
for (ASMData targets : annotations.get(annotationClassName))
{
String targetMod = (String) targets.getAnnotationInfo().get("value");
Field f = null;
Object injectedMod = null;
ModContainer mc = this;
boolean isStatic = false;
Class<?> clz = modInstance.getClass();
if (!Strings.isNullOrEmpty(targetMod))
{
if (Loader.isModLoaded(targetMod))
{
mc = Loader.instance().getIndexedModList().get(targetMod);
}
else
{
mc = null;
}
}
if (mc != null)
{
try
{
clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader());
f = clz.getDeclaredField(targets.getObjectName());
f.setAccessible(true);
isStatic = Modifier.isStatic(f.getModifiers());
injectedMod = retreiver.apply(mc);
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
FMLLog.log(getModId(), Level.WARN, e, "Attempting to load @%s in class %s for %s and failing", annotationName, targets.getClassName(), mc.getModId());
}
}
if (f != null)
{
Object target = null;
if (!isStatic)
{
target = modInstance;
if (!modInstance.getClass().equals(clz))
{
FMLLog.log(getModId(), Level.WARN, "Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId());
continue;
}
}
f.set(target, injectedMod);
}
}
}
@Subscribe
public void constructMod(FMLConstructionEvent event)
{
try
{
BlamingTransformer.addClasses(getModId(), candidate.getClassList());
ModClassLoader modClassLoader = event.getModClassLoader();
modClassLoader.addFile(source);
modClassLoader.clearNegativeCacheFor(candidate.getClassList());
Class<?> clazz = Class.forName(className, true, modClassLoader);
Certificate[] certificates = clazz.getProtectionDomain().getCodeSource().getCertificates();
int len = 0;
if (certificates != null)
{
len = certificates.length;
}
Builder<String> certBuilder = ImmutableList.<String>builder();
for (int i = 0; i < len; i++)
{
certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
}
ImmutableList<String> certList = certBuilder.build();
sourceFingerprints = ImmutableSet.copyOf(certList);
String expectedFingerprint = (String) descriptor.get("certificateFingerprint");
fingerprintNotPresent = true;
if (expectedFingerprint != null && !expectedFingerprint.isEmpty())
{
if (!sourceFingerprints.contains(expectedFingerprint))
{
Level warnLevel = Level.ERROR;
if (source.isDirectory())
{
warnLevel = Level.TRACE;
}
FMLLog.log(getModId(), warnLevel, "The mod %s is expecting signature %s for source %s, however there is no signature matching that description", getModId(), expectedFingerprint, source.getName());
}
else
{
certificate = certificates[certList.indexOf(expectedFingerprint)];
fingerprintNotPresent = false;
}
}
@SuppressWarnings("unchecked")
List<Map<String,Object>> props = (List<Map<String, Object>>) descriptor.get("customProperties");
if (props != null)
{
com.google.common.collect.ImmutableMap.Builder<String, String> builder = ImmutableMap.<String,String>builder();
for (Map<String, Object> p : props)
{
builder.put((String)p.get("k"),(String)p.get("v"));
}
customModProperties = builder.build();
}
else
{
customModProperties = EMPTY_PROPERTIES;
}
Boolean hasDisableableFlag = (Boolean) descriptor.get("canBeDeactivated");
boolean hasReverseDepends = !event.getReverseDependencies().get(getModId()).isEmpty();
if (hasDisableableFlag != null && hasDisableableFlag)
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.YES;
}
else
{
disableability = hasReverseDepends ? Disableable.DEPENDENCIES : Disableable.RESTART;
}
Method factoryMethod = gatherAnnotations(clazz);
modInstance = getLanguageAdapter().getNewInstance(this,clazz, modClassLoader, factoryMethod);
NetworkRegistry.INSTANCE.register(this, clazz, (String)(descriptor.containsKey("acceptableRemoteVersions") ? descriptor.get("acceptableRemoteVersions") : null), event.getASMHarvestedData());
if (fingerprintNotPresent)
{
eventBus.post(new FMLFingerprintViolationEvent(source.isDirectory(), source, ImmutableSet.copyOf(this.sourceFingerprints), expectedFingerprint));
}
ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide(), getLanguageAdapter());
processFieldAnnotations(event.getASMHarvestedData());
}
catch (Throwable e)
{
controller.errorOccurred(this, e);
}
}
@Subscribe
public void handleModStateEvent(FMLEvent event)
{
if (!eventMethods.containsKey(event.getClass()))
{
return;
}
try
{
for (Method m : eventMethods.get(event.getClass()))
{
m.invoke(modInstance, event);
}
}
catch (Throwable t)
{
controller.errorOccurred(this, t);
}
}
@Override
public ArtifactVersion getProcessedVersion()
{
if (processedVersion == null)
{
processedVersion = new DefaultArtifactVersion(getModId(), getVersion());
}
return processedVersion;
}
@Override
public boolean isImmutable()
{
return false;
}
@Override
public String getDisplayVersion()
{
return modMetadata.version;
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return minecraftAccepted;
}
@Override
public Certificate getSigningCertificate()
{
return certificate;
}
@Override
public String toString()
{
return "FMLMod:"+getModId()+"{"+getVersion()+"}";
}
@Override
public Map<String, String> getCustomModProperties()
{
return customModProperties;
}
@Override
public Class<?> getCustomResourcePackClass()
{
try
{
return getSource().isDirectory() ? Class.forName("net.minecraftforge.fml.client.FMLFolderResourcePack", true, getClass().getClassLoader()) : Class.forName("net.minecraftforge.fml.client.FMLFileResourcePack",true, getClass().getClassLoader());
}
catch (ClassNotFoundException e)
{
return null;
}
}
@Override
public Map<String, String> getSharedModDescriptor()
{
Map<String,String> descriptor = Maps.newHashMap();
descriptor.put("modsystem", "FML");
descriptor.put("id", getModId());
descriptor.put("version",getDisplayVersion());
descriptor.put("name", getName());
descriptor.put("url", modMetadata.url);
descriptor.put("authors", modMetadata.getAuthorList());
descriptor.put("description", modMetadata.description);
return descriptor;
}
@Override
public Disableable canBeDisabled()
{
return disableability;
}
@Override
public String getGuiClassName()
{
return (String) descriptor.get("guiFactory");
}
@Override
public List<String> getOwnedPackages()
{
return candidate.getContainedPackages();
}
private boolean isTrue(Boolean value)
{
if (value == null) return false;
return value.booleanValue();
}
@Override
public boolean shouldLoadInEnvironment()
{
boolean clientSideOnly = isTrue((Boolean)descriptor.get("clientSideOnly"));
boolean serverSideOnly = isTrue((Boolean)descriptor.get("serverSideOnly"));
if (clientSideOnly && serverSideOnly)
throw new RuntimeException("Mod annotation claims to be both client and server side only!");
Side side = FMLCommonHandler.instance().getSide();
if (clientSideOnly && side != Side.CLIENT)
{
FMLLog.info("Disabling mod %s it is client side only.", getModId());
return false;
}
if (serverSideOnly && side != Side.SERVER)
{
FMLLog.info("Disabling mod %s it is server side only.", getModId());
return false;
}
return true;
}
}
@@ -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.common;
import org.objectweb.asm.tree.ClassNode;
public interface IASMHook {
/**
* Inject the {@link Mod} class node into this instance. This allows retrieval from custom
* attributes or other artifacts in your mod class
*
* @param modClassNode The mod class
* @return optionally some code generated classes that will be injected into the classloader
*/
ClassNode[] inject(ClassNode modClassNode);
/**
* Allow mods to manipulate classes loaded from this {@link Mod}'s jar file. The {@link Mod}
* class is always guaranteed to be called first.
* The node state should be changed in place.
*
* @param node The class being loaded
*/
void modifyClass(String className, ClassNode node);
}
@@ -0,0 +1,20 @@
/*
* 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.common;
import java.util.concurrent.Callable;
public interface ICrashCallable extends Callable<String>
{
String getLabel();
}
@@ -0,0 +1,18 @@
/*
* 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.common;
public interface IFMLHandledException
{
}
@@ -0,0 +1,69 @@
/*
* 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.common;
import java.io.File;
import java.util.List;
import java.util.Set;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetworkManager;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.IThreadListener;
import net.minecraftforge.fml.common.eventhandler.EventBus;
import net.minecraftforge.fml.relauncher.Side;
public interface IFMLSidedHandler
{
List<String> getAdditionalBrandingInformation();
Side getSide();
void haltGame(String message, Throwable exception);
void showGuiScreen(Object clientGuiElement);
void queryUser(StartupQuery query) throws InterruptedException;
void beginServerLoading(MinecraftServer server);
void finishServerLoading();
File getSavesDirectory();
MinecraftServer getServer();
boolean shouldServerShouldBeKilledQuietly();
void addModAsResource(ModContainer container);
String getCurrentLanguage();
void serverStopped();
NetworkManager getClientToServerNetworkManager();
INetHandler getClientPlayHandler();
void fireNetRegistrationEvent(EventBus bus, NetworkManager manager, Set<String> channelSet, String channel, Side side);
boolean shouldAllowPlayerLogins();
void allowLogins();
IThreadListener getWorldThread(INetHandler net);
void processWindowMessages();
String stripSpecialChars(String message);
}
@@ -0,0 +1,20 @@
/*
* 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.common;
import net.minecraft.item.ItemStack;
public interface IFuelHandler
{
int getBurnTime(ItemStack fuel);
}
@@ -0,0 +1,197 @@
package net.minecraftforge.fml.common;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Level;
public interface ILanguageAdapter {
public Object getNewInstance(FMLModContainer container, Class<?> objectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception;
public boolean supportsStatics();
public void setProxy(Field target, Class<?> proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException;
public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader);
public static class ScalaAdapter implements ILanguageAdapter {
@Override
public Object getNewInstance(FMLModContainer container, Class<?> scalaObjectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception
{
Class<?> sObjectClass = Class.forName(scalaObjectClass.getName()+"$",true,classLoader);
return sObjectClass.getField("MODULE$").get(null);
}
@Override
public boolean supportsStatics()
{
return false;
}
@Override
public void setProxy(Field target, Class<?> proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException
{
try
{
// Get the actual singleton class. The two variants are from
// whether the @SidedProxy is declared in a the class block
// of the object directly, or in the object block, i.e.
// whether it's:
// class ModName {
// @SidedProxy ...
// }
// object ModName extends ModName {}
// which leads to us getting the outer class, or
// object ModName {
// @SidedProxy ...
// }
// which leads to us getting the inner class.
if (!proxyTarget.getName().endsWith("$"))
{
// Get internal class generated by Scala.
proxyTarget = Class.forName(proxyTarget.getName() + "$", true, proxyTarget.getClassLoader());
}
}
catch (ClassNotFoundException e)
{
// Not a singleton, look for @Instance field as a fallback.
FMLLog.log(Level.INFO, e, "An error occured trying to load a proxy into %s.%s. Did you declare your mod as 'class' instead of 'object'?", proxyTarget.getSimpleName(), target.getName());
return;
}
// Get the instance via the MODULE$ field which is
// automatically generated by the Scala compiler for
// singletons.
Object targetInstance = proxyTarget.getField("MODULE$").get(null);
try
{
// Find setter function. We do it this way because we can't
// necessarily use proxyTarget.getMethod(proxy.getClass()), as
// it might be a subclass and not the exact parameter type.
// All fields are private in Scala, wrapped by a getter and
// setter named <fieldname> and <fieldname>_$eq. To those
// familiar with scala.reflect.BeanProperty: these will always
// be there, set<Fieldname> and get<Fieldname> will always
// only be generated *additionally*.
final String setterName = target.getName() + "_$eq";
for (Method setter : proxyTarget.getMethods())
{
Class<?>[] setterParameters = setter.getParameterTypes();
if (setterName.equals(setter.getName()) &&
// Some more validation.
setterParameters.length == 1 &&
setterParameters[0].isAssignableFrom(proxy.getClass()))
{
// Here goes nothing...
setter.invoke(targetInstance, proxy);
return;
}
}
}
catch (InvocationTargetException e)
{
FMLLog.log(Level.ERROR, e, "An error occured trying to load a proxy into %s.%s", proxyTarget.getSimpleName(), target.getName());
throw new LoaderException(e);
}
// If we come here we could not find a setter for this proxy.
FMLLog.severe("Failed loading proxy into %s.%s, could not find setter function. Did you declare the field with 'val' instead of 'var'?", proxyTarget.getSimpleName(), target.getName());
throw new LoaderException(String.format("Failed loading proxy into %s.%s, could not find setter function. Did you declare the field with 'val' instead of 'var'?", proxyTarget.getSimpleName(), target.getName()));
}
@Override
public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader)
{
// For Scala mods, we want to enable authors to write them like so:
// object ModName {
// @SidedProxy(...)
// var proxy: ModProxy = null
// }
// For this to work, we have to search inside the inner class Scala
// generates for singletons, which is in called ModName$. These are
// not automatically handled, because the mod discovery code ignores
// internal classes.
// Note that it is alternatively possible to write this like so:
// class ModName {
// @SidedProxy(...)
// var proxy: ModProxy = null
// }
// object ModName extends ModName { ... }
// which will fall back to the normal injection code which calls
// setProxy in turn.
// Get the actual mod implementation, which will be the inner class
// if we have a singleton.
Class<?> proxyTarget = mod.getMod().getClass();
if (proxyTarget.getName().endsWith("$"))
{
// So we have a singleton class, check if there are targets.
for (Field target : proxyTarget.getDeclaredFields())
{
// This will not turn up anything if the alternative
// approach was taken (manually declaring the class).
// So we don't initialize the field twice.
if (target.getAnnotation(SidedProxy.class) != null)
{
String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide();
try
{
Object proxy = Class.forName(targetType, true, loader).newInstance();
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName());
throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName()));
}
setProxy(target, proxyTarget, proxy);
}
catch (Exception e) {
FMLLog.log(Level.ERROR, e, "An error occured trying to load a proxy into %s.%s", proxyTarget.getSimpleName(), target.getName());
throw new LoaderException(e);
}
}
}
}
else
{
FMLLog.finer("Mod does not appear to be a singleton.");
}
}
}
public static class JavaAdapter implements ILanguageAdapter {
@Override
public Object getNewInstance(FMLModContainer container, Class<?> objectClass, ClassLoader classLoader, Method factoryMarkedMethod) throws Exception
{
if (factoryMarkedMethod != null)
{
return factoryMarkedMethod.invoke(null);
}
else
{
return objectClass.newInstance();
}
}
@Override
public boolean supportsStatics()
{
return true;
}
@Override
public void setProxy(Field target, Class<?> proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,
SecurityException
{
target.set(null, proxy);
}
@Override
public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader)
{
// Nothing to do here.
}
}
}
@@ -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.common;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
/**
* This is called back during world generation.
*
* @author cpw
*
*/
public interface IWorldGenerator
{
/**
* Generate some world
*
* @param random the chunk specific {@link Random}.
* @param chunkX the chunk X coordinate of this chunk.
* @param chunkZ the chunk Z coordinate of this chunk.
* @param world : additionalData[0] The minecraft {@link World} we're generating for.
* @param chunkGenerator : additionalData[1] The {@link IChunkProvider} that is generating.
* @param chunkProvider : additionalData[2] {@link IChunkProvider} that is requesting the world generation.
*
*/
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider);
}
@@ -0,0 +1,210 @@
/*
* 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.common;
import java.io.File;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.eventbus.EventBus;
public class InjectedModContainer implements ModContainer
{
private File source;
public final ModContainer wrappedContainer;
public InjectedModContainer(ModContainer mc, File source)
{
this.source = source != null ? source : new File("minecraft.jar");
this.wrappedContainer = mc;
}
@Override
public String getModId()
{
return wrappedContainer.getModId();
}
@Override
public String getName()
{
return wrappedContainer.getName();
}
@Override
public String getVersion()
{
return wrappedContainer.getVersion();
}
@Override
public File getSource()
{
return source;
}
@Override
public ModMetadata getMetadata()
{
return wrappedContainer.getMetadata();
}
@Override
public void bindMetadata(MetadataCollection mc)
{
wrappedContainer.bindMetadata(mc);
}
@Override
public void setEnabledState(boolean enabled)
{
wrappedContainer.setEnabledState(enabled);
}
@Override
public Set<ArtifactVersion> getRequirements()
{
return wrappedContainer.getRequirements();
}
@Override
public List<ArtifactVersion> getDependencies()
{
return wrappedContainer.getDependencies();
}
@Override
public List<ArtifactVersion> getDependants()
{
return wrappedContainer.getDependants();
}
@Override
public String getSortingRules()
{
return wrappedContainer.getSortingRules();
}
@Override
public boolean registerBus(EventBus bus, LoadController controller)
{
return wrappedContainer.registerBus(bus, controller);
}
@Override
public boolean matches(Object mod)
{
return wrappedContainer.matches(mod);
}
@Override
public Object getMod()
{
return wrappedContainer.getMod();
}
@Override
public ArtifactVersion getProcessedVersion()
{
return wrappedContainer.getProcessedVersion();
}
@Override
public boolean isImmutable()
{
return true;
}
@Override
public String getDisplayVersion()
{
return wrappedContainer.getDisplayVersion();
}
@Override
public VersionRange acceptableMinecraftVersionRange()
{
return wrappedContainer.acceptableMinecraftVersionRange();
}
public WorldAccessContainer getWrappedWorldAccessContainer()
{
if (wrappedContainer instanceof WorldAccessContainer)
{
return (WorldAccessContainer) wrappedContainer;
}
else
{
return null;
}
}
@Override
public Certificate getSigningCertificate()
{
return wrappedContainer.getSigningCertificate();
}
@Override
public String toString()
{
return "Wrapped{"+wrappedContainer.toString()+"}";
}
@Override
public Map<String, String> getCustomModProperties()
{
return wrappedContainer.getCustomModProperties();
}
@Override
public Class<?> getCustomResourcePackClass()
{
return wrappedContainer.getCustomResourcePackClass();
}
@Override
public Map<String, String> getSharedModDescriptor()
{
return wrappedContainer.getSharedModDescriptor();
}
@Override
public Disableable canBeDisabled()
{
return wrappedContainer.canBeDisabled();
}
@Override
public String getGuiClassName()
{
return wrappedContainer.getGuiClassName();
}
@Override
public List<String> getOwnedPackages()
{
return wrappedContainer.getOwnedPackages();
}
@Override
public boolean shouldLoadInEnvironment()
{
return true;
}
}
@@ -0,0 +1,367 @@
/*
* 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.common;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.common.ProgressManager.ProgressBar;
import net.minecraftforge.fml.common.event.FMLEvent;
import net.minecraftforge.fml.common.event.FMLLoadEvent;
import net.minecraftforge.fml.common.event.FMLModDisabledEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLStateEvent;
import net.minecraftforge.fml.common.functions.ArtifactVersionNameFunction;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.ThreadContext;
import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
public class LoadController
{
private Loader loader;
private EventBus masterChannel;
private ImmutableMap<String,EventBus> eventChannels;
private LoaderState state;
private Multimap<String, ModState> modStates = ArrayListMultimap.create();
private Multimap<String, Throwable> errors = ArrayListMultimap.create();
private List<ModContainer> activeModList = Lists.newArrayList();
private ModContainer activeContainer;
private BiMap<ModContainer, Object> modObjectList;
private ListMultimap<String, ModContainer> packageOwners;
public LoadController(Loader loader)
{
this.loader = loader;
this.masterChannel = new EventBus("FMLMainChannel");
this.masterChannel.register(this);
state = LoaderState.NOINIT;
packageOwners = ArrayListMultimap.create();
}
void disableMod(ModContainer mod)
{
HashMap<String, EventBus> temporary = Maps.newHashMap(eventChannels);
String modId = mod.getModId();
EventBus bus = temporary.remove(modId);
bus.post(new FMLModDisabledEvent());
if (errors.get(modId).isEmpty())
{
eventChannels = ImmutableMap.copyOf(temporary);
modStates.put(modId, ModState.DISABLED);
modObjectList.remove(mod);
activeModList.remove(mod);
}
}
@Subscribe
public void buildModList(FMLLoadEvent event)
{
Builder<String, EventBus> eventBus = ImmutableMap.builder();
for (ModContainer mod : loader.getModList())
{
//Create mod logger, and make the EventBus logger a child of it.
EventBus bus = new EventBus(mod.getModId());
boolean isActive = mod.registerBus(bus, this);
if (isActive)
{
activeModList.add(mod);
modStates.put(mod.getModId(), ModState.UNLOADED);
eventBus.put(mod.getModId(), bus);
FMLCommonHandler.instance().addModToResourcePack(mod);
}
else
{
FMLLog.log(mod.getModId(), Level.WARN, "Mod %s has been disabled through configuration", mod.getModId());
modStates.put(mod.getModId(), ModState.UNLOADED);
modStates.put(mod.getModId(), ModState.DISABLED);
}
}
eventChannels = eventBus.build();
}
public void distributeStateMessage(LoaderState state, Object... eventData)
{
if (state.hasEvent())
{
masterChannel.post(state.getEvent(eventData));
}
}
public void transition(LoaderState desiredState, boolean forceState)
{
LoaderState oldState = state;
state = state.transition(!errors.isEmpty());
if (state != desiredState && !forceState)
{
Throwable toThrow = null;
FMLLog.severe("Fatal errors were detected during the transition from %s to %s. Loading cannot continue", oldState, desiredState);
StringBuilder sb = new StringBuilder();
printModStates(sb);
FMLLog.severe("%s", sb.toString());
if (errors.size()>0)
{
FMLLog.severe("The following problems were captured during this phase");
for (Entry<String, Throwable> error : errors.entries())
{
FMLLog.log(Level.ERROR, error.getValue(), "Caught exception from %s", error.getKey());
if (error.getValue() instanceof IFMLHandledException)
{
toThrow = error.getValue();
}
else if (toThrow == null)
{
toThrow = error.getValue();
}
}
}
else
{
FMLLog.severe("The ForgeModLoader state engine has become corrupted. Probably, a state was missed by and invalid modification to a base class" +
"ForgeModLoader depends on. This is a critical error and not recoverable. Investigate any modifications to base classes outside of" +
"ForgeModLoader, especially Optifine, to see if there are fixes available.");
throw new RuntimeException("The ForgeModLoader state engine is invalid");
}
if (toThrow != null && toThrow instanceof RuntimeException)
{
throw (RuntimeException)toThrow;
}
else
{
throw new LoaderException(toThrow);
}
}
else if (state != desiredState && forceState)
{
FMLLog.info("The state engine was in incorrect state %s and forced into state %s. Errors may have been discarded.", state, desiredState);
forceState(desiredState);
}
}
public ModContainer activeContainer()
{
return activeContainer != null ? activeContainer : findActiveContainerFromStack();
}
@Subscribe
public void propogateStateMessage(FMLEvent stateEvent)
{
if (stateEvent instanceof FMLPreInitializationEvent)
{
modObjectList = buildModObjectList();
}
ProgressBar bar = ProgressManager.push(stateEvent.description(), activeModList.size(), true);
for (ModContainer mc : activeModList)
{
bar.step(mc.getName());
sendEventToModContainer(stateEvent, mc);
}
ProgressManager.pop(bar);
}
private void sendEventToModContainer(FMLEvent stateEvent, ModContainer mc)
{
String modId = mc.getModId();
Collection<String> requirements = Collections2.transform(mc.getRequirements(),new ArtifactVersionNameFunction());
for (ArtifactVersion av : mc.getDependencies())
{
if (av.getLabel()!= null && requirements.contains(av.getLabel()) && modStates.containsEntry(av.getLabel(),ModState.ERRORED))
{
FMLLog.log(modId, Level.ERROR, "Skipping event %s and marking errored mod %s since required dependency %s has errored", stateEvent.getEventType(), modId, av.getLabel());
modStates.put(modId, ModState.ERRORED);
return;
}
}
activeContainer = mc;
stateEvent.applyModContainer(activeContainer());
ThreadContext.put("mod", modId);
FMLLog.log(modId, Level.TRACE, "Sending event %s to mod %s", stateEvent.getEventType(), modId);
eventChannels.get(modId).post(stateEvent);
FMLLog.log(modId, Level.TRACE, "Sent event %s to mod %s", stateEvent.getEventType(), modId);
ThreadContext.remove("mod");
activeContainer = null;
if (stateEvent instanceof FMLStateEvent)
{
if (!errors.containsKey(modId))
{
modStates.put(modId, ((FMLStateEvent)stateEvent).getModState());
}
else
{
modStates.put(modId, ModState.ERRORED);
}
}
}
public ImmutableBiMap<ModContainer, Object> buildModObjectList()
{
ImmutableBiMap.Builder<ModContainer, Object> builder = ImmutableBiMap.<ModContainer, Object>builder();
for (ModContainer mc : activeModList)
{
if (!mc.isImmutable() && mc.getMod()!=null)
{
builder.put(mc, mc.getMod());
List<String> packages = mc.getOwnedPackages();
for (String pkg : packages)
{
packageOwners.put(pkg, mc);
}
}
if (mc.getMod()==null && !mc.isImmutable() && state!=LoaderState.CONSTRUCTING)
{
FMLLog.severe("There is a severe problem with %s - it appears not to have constructed correctly", mc.getModId());
if (state != LoaderState.CONSTRUCTING)
{
this.errorOccurred(mc, new RuntimeException());
}
}
}
return builder.build();
}
public void errorOccurred(ModContainer modContainer, Throwable exception)
{
if (exception instanceof InvocationTargetException)
{
errors.put(modContainer.getModId(), ((InvocationTargetException)exception).getCause());
}
else
{
errors.put(modContainer.getModId(), exception);
}
}
public void printModStates(StringBuilder ret)
{
ret.append("\n\tStates:");
for (ModState state : ModState.values())
ret.append(" '").append(state.getMarker()).append("' = ").append(state.toString());
for (ModContainer mc : loader.getModList())
{
ret.append("\n\t");
for (ModState state : modStates.get(mc.getModId()))
ret.append(state.getMarker());
ret.append("\t").append(mc.getModId()).append("{").append(mc.getVersion()).append("} [").append(mc.getName()).append("] (").append(mc.getSource().getName()).append(") ");
}
}
public List<ModContainer> getActiveModList()
{
return activeModList;
}
public ModState getModState(ModContainer selectedMod)
{
return Iterables.getLast(modStates.get(selectedMod.getModId()), ModState.AVAILABLE);
}
public void distributeStateMessage(Class<?> customEvent)
{
try
{
masterChannel.post(customEvent.newInstance());
}
catch (Exception e)
{
FMLLog.log(Level.ERROR, e, "An unexpected exception");
throw new LoaderException(e);
}
}
public BiMap<ModContainer, Object> getModObjectList()
{
if (modObjectList == null)
{
FMLLog.severe("Detected an attempt by a mod %s to perform game activity during mod construction. This is a serious programming error.", activeContainer);
return buildModObjectList();
}
return ImmutableBiMap.copyOf(modObjectList);
}
public boolean isInState(LoaderState state)
{
return this.state == state;
}
boolean hasReachedState(LoaderState state) {
return this.state.ordinal()>=state.ordinal() && this.state!=LoaderState.ERRORED;
}
void forceState(LoaderState newState)
{
this.state = newState;
}
private ModContainer findActiveContainerFromStack()
{
for (Class<?> c : getCallingStack())
{
int idx = c.getName().lastIndexOf('.');
if (idx == -1)
{
continue;
}
String pkg = c.getName().substring(0,idx);
if (packageOwners.containsKey(pkg))
{
return packageOwners.get(pkg).get(0);
}
}
return null;
}
private FMLSecurityManager accessibleManager = new FMLSecurityManager();
class FMLSecurityManager extends SecurityManager
{
Class<?>[] getStackClasses()
{
return getClassContext();
}
}
Class<?>[] getCallingStack()
{
return accessibleManager.getStackClasses();
}
LoaderState getState()
{
return state;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,36 @@
/*
* 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.common;
public class LoaderException extends EnhancedRuntimeException
{
/**
*
*/
private static final long serialVersionUID = -5675297950958861378L;
public LoaderException(Throwable wrapped)
{
super(wrapped);
}
public LoaderException()
{
}
public LoaderException(String message)
{
super(message);
}
@Override protected void printStackTrace(WrappedPrintStream stream){}
}
@@ -0,0 +1,127 @@
/*
* 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.common;
import net.minecraftforge.fml.common.event.FMLConstructionEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppedEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent;
import net.minecraftforge.fml.common.event.FMLStateEvent;
import com.google.common.base.Throwables;
/**
* The state enum used to help track state progression for the loader
* @author cpw
*
*/
public enum LoaderState
{
NOINIT("Uninitialized",null),
LOADING("Loading",null),
CONSTRUCTING("Constructing mods",FMLConstructionEvent.class),
PREINITIALIZATION("Pre-initializing mods", FMLPreInitializationEvent.class),
INITIALIZATION("Initializing mods", FMLInitializationEvent.class),
POSTINITIALIZATION("Post-initializing mods", FMLPostInitializationEvent.class),
AVAILABLE("Mod loading complete", FMLLoadCompleteEvent.class),
SERVER_ABOUT_TO_START("Server about to start", FMLServerAboutToStartEvent.class),
SERVER_STARTING("Server starting", FMLServerStartingEvent.class),
SERVER_STARTED("Server started", FMLServerStartedEvent.class),
SERVER_STOPPING("Server stopping", FMLServerStoppingEvent.class),
SERVER_STOPPED("Server stopped", FMLServerStoppedEvent.class),
ERRORED("Mod Loading errored",null);
private Class<? extends FMLStateEvent> eventClass;
private String name;
private LoaderState(String name, Class<? extends FMLStateEvent> event)
{
this.name = name;
this.eventClass = event;
}
public LoaderState transition(boolean errored)
{
if (errored)
{
return ERRORED;
}
// stopping -> available
if (this == SERVER_STOPPED)
{
return AVAILABLE;
}
return values()[ordinal() < values().length ? ordinal()+1 : ordinal()];
}
public boolean hasEvent()
{
return eventClass != null;
}
public FMLStateEvent getEvent(Object... eventData)
{
try
{
return eventClass.getConstructor(Object[].class).newInstance((Object)eventData);
}
catch (Exception e)
{
throw Throwables.propagate(e);
}
}
public LoaderState requiredState()
{
if (this == NOINIT) return NOINIT;
return LoaderState.values()[this.ordinal()-1];
}
public enum ModState
{
UNLOADED ("Unloaded", "U"),
LOADED ("Loaded", "L"),
CONSTRUCTED ("Constructed", "C"),
PREINITIALIZED ("Pre-initialized", "H"),
INITIALIZED ("Initialized", "I"),
POSTINITIALIZED("Post-initialized", "J"),
AVAILABLE ("Available", "A"),
DISABLED ("Disabled", "D"),
ERRORED ("Errored", "E");
private String label;
private String marker;
private ModState(String label, String marker)
{
this.label = label;
this.marker = marker;
}
@Override
public String toString()
{
return this.label;
}
public String getMarker()
{
return this.marker;
}
}
}
@@ -0,0 +1,32 @@
/*
* 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.common;
import com.google.common.eventbus.EventBus;
public class MCPDummyContainer extends DummyModContainer {
public MCPDummyContainer(ModMetadata metadata) {
super(metadata);
}
@Override
public boolean registerBus(EventBus bus, LoadController controller) {
return true;
}
@Override
public Disableable canBeDisabled()
{
return Disableable.YES;
}
}
@@ -0,0 +1,125 @@
/*
* 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.common;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionParser;
import org.apache.logging.log4j.Level;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class MetadataCollection
{
private String modListVersion;
private ModMetadata[] modList;
private Map<String, ModMetadata> metadatas = Maps.newHashMap();
public static MetadataCollection from(InputStream inputStream, String sourceName)
{
if (inputStream == null)
{
return new MetadataCollection();
}
InputStreamReader reader = new InputStreamReader(inputStream);
try
{
MetadataCollection collection;
Gson gson = new GsonBuilder().registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionAdapter()).create();
JsonParser parser = new JsonParser();
JsonElement rootElement = parser.parse(reader);
if (rootElement.isJsonArray())
{
collection = new MetadataCollection();
JsonArray jsonList = rootElement.getAsJsonArray();
collection.modList = new ModMetadata[jsonList.size()];
int i = 0;
for (JsonElement mod : jsonList)
{
collection.modList[i++]=gson.fromJson(mod, ModMetadata.class);
}
}
else
{
collection = gson.fromJson(rootElement, MetadataCollection.class);
}
collection.parseModMetadataList();
return collection;
}
catch (JsonParseException e)
{
FMLLog.log(Level.ERROR, e, "The mcmod.info file in %s cannot be parsed as valid JSON. It will be ignored", sourceName);
return new MetadataCollection();
}
catch (Exception e)
{
throw Throwables.propagate(e);
}
}
private void parseModMetadataList()
{
for (ModMetadata modMetadata : modList)
{
metadatas.put(modMetadata.modId, modMetadata);
}
}
public ModMetadata getMetadataForId(String modId, Map<String, Object> extraData)
{
if (!metadatas.containsKey(modId))
{
ModMetadata dummy = new ModMetadata();
dummy.modId = modId;
dummy.name = (String) extraData.get("name");
dummy.version = (String) extraData.get("version");
dummy.autogenerated = true;
metadatas.put(modId, dummy);
}
return metadatas.get(modId);
}
public static class ArtifactVersionAdapter extends TypeAdapter<ArtifactVersion>
{
@Override
public void write(JsonWriter out, ArtifactVersion value) throws IOException
{
// no op - we never write these out
}
@Override
public ArtifactVersion read(JsonReader in) throws IOException
{
return VersionParser.parseVersionReference(in.nextString());
}
}
}
@@ -0,0 +1,56 @@
/*
* 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.common;
import java.security.cert.Certificate;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.common.versioning.VersionRange;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.Side;
public class MinecraftDummyContainer extends DummyModContainer
{
private VersionRange staticRange;
public MinecraftDummyContainer(String actualMCVersion)
{
super(new ModMetadata());
getMetadata().modId = "Minecraft";
getMetadata().name = "Minecraft";
getMetadata().version = actualMCVersion;
staticRange = VersionParser.parseRange("["+actualMCVersion+"]");
}
public VersionRange getStaticVersionRange()
{
return staticRange;
}
@Override
public Certificate getSigningCertificate()
{
if (FMLLaunchHandler.side() != Side.CLIENT)
return null;
try
{
Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, getClass().getClassLoader());
Certificate[] certificates = cbr.getProtectionDomain().getCodeSource().getCertificates();
return certificates != null ? certificates[0] : null;
}
catch (Exception e){} // Errors don't matter just return null.
return null;
}
}
@@ -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.common;
import java.util.Set;
import net.minecraftforge.fml.common.EnhancedRuntimeException.WrappedPrintStream;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
public class MissingModsException extends EnhancedRuntimeException
{
private static final long serialVersionUID = 1L;
public final Set<ArtifactVersion> missingMods;
public MissingModsException(Set<ArtifactVersion> missingMods, String id, String name)
{
super(String.format("Mod %s (%s) requires %s", id, name, missingMods));
this.missingMods = missingMods;
}
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
stream.println("Missing Mods:");
for (ArtifactVersion v : missingMods)
{
stream.println(String.format("\t%s : %s", v.getLabel(), v.getRangeString()));
}
stream.println("");
}
}
@@ -0,0 +1,308 @@
/*
* 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.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.minecraftforge.fml.client.IModGuiFactory;
import net.minecraftforge.fml.common.event.FMLEvent;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent;
import net.minecraftforge.fml.common.event.FMLServerStartedEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppedEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent;
import net.minecraftforge.fml.common.network.NetworkCheckHandler;
import net.minecraftforge.fml.common.registry.GameRegistry;
/**
* This defines a Mod to FML.
* Any class found with this annotation applied will be loaded as a Mod. The instance that is loaded will
* represent the mod to other Mods in the system. It will be sent various subclasses of {@link FMLEvent}
* at pre-defined times during the loading of the game, based on where you have applied the {@link EventHandler}
* annotation.
*
* <p>This is a simple example of a Mod. It has the modId of "MyModId", the name of "My example mod", it is
* version 1.0, and depends on FML being loaded.
* <pre>{@code
* package mymod;
* // Declare that this is a mod with modId "MyModId", name "My example mod", version "1.0" and dependency on FML.
* {@literal @}Mod(modId="MyModId",name="My example mod",version="1.0",dependencies="required-after:FML")
* public class MyMod {
* // Populate this field with the instance of the mod created by FML
* {@literal @}Instance("MyModId")
* public MyMod instance;
*
* // Mark this method for receiving an {@link FMLEvent} (in this case, it's the {@link FMLPreInitializationEvent})
* {@literal @}EventHandler public void preInit(FMLPreInitializationEvent event)
* {
* // Do stuff in pre-init phase (read config, create blocks and items, register them)
* }
* }
* }
* </pre>
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Mod
{
/**
* The unique mod identifier for this mod
*/
String modid();
/**
* A user friendly name for the mod
*/
String name() default "";
/**
* A version string for this mod
*/
String version() default "";
/**
* A simple dependency string for this mod (see modloader's "priorities" string specification)
*/
String dependencies() default "";
/**
* Whether to use the mcmod.info metadata by default for this mod.
* If true, settings in the mcmod.info file will override settings in these annotations.
*/
boolean useMetadata() default false;
/**
* If true, this mod will not be loaded on the Dedicated Server environment.
* Will crash if both serverSideOnly and clientSideOnly are set to true.
*/
boolean clientSideOnly() default false;
/**
* If true, this mod will not be loaded on the Client environment.
* Will crash if both serverSideOnly and clientSideOnly are set to true.
*/
boolean serverSideOnly() default false;
/**
* The acceptable range of minecraft versions that this mod will load and run in
* The default ("empty string") indicates that the currently RUNNING minecraft version is acceptable.
* This means ANY version that the end user adds the mod to. Modders PLEASS set this.
* FML will refuse to run with an error if the minecraft version is not in this range across all mods.
* @return A version range as specified by the maven version range specification or the empty string
*/
String acceptedMinecraftVersions() default "";
/**
* A replacement for the no-longer-existing "versionRange" of NetworkMod. Specify a remote version range
* that this mod will accept as valid. Defaults to nothing, which is interpreted as "only this version".
* Another special value is '*' which means accept all versions.
*
* This is ignored if there is a {@link NetworkCheckHandler} annotation on a method in this class.
*
* @return A version range as specified by the maven version range specification or the empty string
*/
String acceptableRemoteVersions() default "";
/**
* A version range specifying compatible save version information. If your mod follows good version numbering
* practice <a href="http://semver.org/">Like this (http://semver.org/)</a> then this should be sufficient.
*
* Advanced users can specify a {@link SaveInspectionHandler} instead.
* @return A version range as specified by the maven version range specification or the empty string
*/
String acceptableSaveVersions() default "";
/**
* An optional bukkit plugin that will be injected into the bukkit plugin framework if
* this mod is loaded into the FML framework and the bukkit coremod is present.
* Instances of the bukkit plugin can be obtained via the {@link BukkitPluginRef} annotation on fields.
*
* This may be implemented by a bukkit integration. It is not provided with vanilla FML or MinecraftForge.
*
* @return The name of the plugin to load for this mod
*/
String bukkitPlugin() default "";
/**
* Specifying this field allows for a mod to expect a signed jar with a fingerprint matching this value.
* The fingerprint should be SHA-1 encoded, lowercase with ':' removed. An empty value indicates that
* the mod is not expecting to be signed.
*
* Any incorrectness of the fingerprint, be it missing or wrong, will result in the {@link FMLFingerprintViolationEvent}
* event firing <i>prior to any other event on the mod</i>.
*
* @return A certificate fingerprint that is expected for this mod.
*/
String certificateFingerprint() default "";
/**
* The language the mod is authored in. This will be used to control certain compatibility behaviours for this mod.
* Valid values are currently "java", "scala"
*
* @return The language the mod is authored in
*/
String modLanguage() default "java";
/**
* The language adapter to be used to load this mod. This overrides the value of modLanguage. The class must have a
* public zero variable constructor and implement {@link ILanguageAdapter} just like the Java and Scala adapters.
*
* A class with an invalid constructor or that doesn't implement {@link ILanguageAdapter} will throw an exception and
* halt loading.
*
* @return The full class name of the language adapter
*/
String modLanguageAdapter() default "";
/**
* NOT YET IMPLEMENTED. </br>
* An optional ASM hook class, that can be used to apply ASM to classes loaded from this mod. It is also given
* the ASM tree of the class declaring {@link Mod} to do with what it will.
*
* @return The name of a class to be loaded and executed. Must implement {@link IASMHook}.
*/
@Deprecated
String asmHookClass() default "";
/**
* If your mod doesn't have a runtime persistent effect on the state of the game, and can be disabled without side effects
* (minimap mods, graphical tweak mods) then you can set true here and receive the FMLDeactivationEvent to perform deactivation
* tasks.
* This does not affect administrative disabling through the system property fml.modStates or the config file fmlModState.properties.
* The mod will only be deactivated outside of a running game world - FML will never allow mod deactivation whilst a game server
* is running.
*
* @return if this mod can be deactivated whilst the game is open.
*/
boolean canBeDeactivated() default false;
/**
* An optional GUI factory for this mod. This is the name of a class implementing {@link IModGuiFactory} that will be instantiated
* on the client side, and will have certain configuration/options guis requested from it.
*
* @return The name of a class implementing {@link IModGuiFactory}
*/
String guiFactory() default "";
/**
* A list of custom properties for this mod. Completely up to the mod author if/when they
* want to put anything in here.
* @return an optional list of custom properties
*/
CustomProperty[] customProperties() default {};
/**
* A custom key => value property pair for use with {@link Mod#customProperties()}
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface CustomProperty
{
/**
* A key. Should be unique.
* @return A key
*/
String k();
/**
* A value. Can be anything.
* @return A value
*/
String v();
}
/**
* Marks the associated method as handling an FML lifecycle event.
* The method must have a single parameter, one of the following types. This annotation
* replaces the multiple different annotations that previously were used.
*
* Current event classes. This first section is standard lifecycle events. They are dispatched
* at various phases as the game starts. Each event should have information useful to that
* phase of the lifecycle. They are fired in this order.
*
* These suggestions are mostly just suggestions on what to do in each event.
* <ul>
* <li> {@link FMLPreInitializationEvent} : Run before anything else. Read your config, create blocks,
* items, etc, and register them with the {@link GameRegistry}.</li>
* <li> {@link FMLInitializationEvent} : Do your mod setup. Build whatever data structures you care about. Register recipes,
* send {@link FMLInterModComms} messages to other mods.</li>
* <li> {@link FMLPostInitializationEvent} : Handle interaction with other mods, complete your setup based on this.</li>
* </ul>
* <p>These are the server lifecycle events. They are fired whenever a server is running, or about to run. Each time a server
* starts they will be fired in this sequence.
* <ul>
* <li> {@link FMLServerAboutToStartEvent} : Use if you need to handle something before the server has even been created.</li>
* <li> {@link FMLServerStartingEvent} : Do stuff you need to do to set up the server. register commands, tweak the server.</li>
* <li> {@link FMLServerStartedEvent} : Do what you need to with the running server.</li>
* <li> {@link FMLServerStoppingEvent} : Do what you need to before the server has started it's shutdown sequence.</li>
* <li> {@link FMLServerStoppedEvent} : Do whatever cleanup you need once the server has shutdown. Generally only useful
* on the integrated server.</li>
* </ul>
* The second set of events are more specialized, for receiving notification of specific
* information.
* <ul>
* <li> {@link FMLFingerprintViolationEvent} : Sent just before {@link FMLPreInitializationEvent}
* if something is wrong with your mod signature</li>
* <li> {@link IMCEvent} : Sent just after {@link FMLInitializationEvent} if you have IMC messages waiting
* from other mods</li>
* </ul>
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EventHandler{}
/**
* Populate the annotated field with the mod instance based on the specified ModId. This can be used
* to retrieve instances of other mods.
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Instance {
/**
* The mod object to inject into this field
*/
String value() default "";
}
/**
* Populate the annotated field with the mod's metadata.
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Metadata {
/**
* The mod id specifying the metadata to load here
*/
String value() default "";
}
/**
* Mod instance factory method. Should return an instance of the mod. Applies only to static methods on the same class as {@link Mod}.
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface InstanceFactory {
}
}
@@ -0,0 +1,232 @@
package net.minecraftforge.fml.common;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.asm.transformers.ModAPITransformer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.ModDiscoverer;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.functions.ModIdFunction;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionParser;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
public class ModAPIManager {
public static final ModAPIManager INSTANCE = new ModAPIManager();
private ModAPITransformer transformer;
private ASMDataTable dataTable;
private Map<String,APIContainer> apiContainers;
private static class APIContainer extends DummyModContainer {
private List<ArtifactVersion> referredMods;
private ArtifactVersion ownerMod;
private ArtifactVersion ourVersion;
private String providedAPI;
private File source;
private String version;
private Set<String> currentReferents;
private Set<String> packages;
private boolean selfReferenced;
public APIContainer(String providedAPI, String apiVersion, File source, ArtifactVersion ownerMod)
{
this.providedAPI = providedAPI;
this.version = apiVersion;
this.ownerMod = ownerMod;
this.ourVersion = new DefaultArtifactVersion(providedAPI, apiVersion);
this.referredMods = Lists.newArrayList();
this.source = source;
this.currentReferents = Sets.newHashSet();
this.packages = Sets.newHashSet();
}
@Override
public File getSource()
{
return source;
}
@Override
public String getVersion()
{
return version;
}
@Override
public String getName()
{
return "API: "+providedAPI;
}
@Override
public String getModId()
{
return providedAPI;
}
@Override
public List<ArtifactVersion> getDependants()
{
return referredMods;
}
@Override
public List<ArtifactVersion> getDependencies()
{
return selfReferenced ? ImmutableList.<ArtifactVersion>of() : ImmutableList.of(ownerMod);
}
@Override
public ArtifactVersion getProcessedVersion()
{
return ourVersion;
}
public void validate(String providedAPI, String apiOwner, String apiVersion)
{
// TODO Compare this annotation data to the one we first found. Maybe barf if there is inconsistency?
}
@Override
public String toString()
{
return "APIContainer{"+providedAPI+":"+version+"}";
}
public void addAPIReference(String embedded)
{
if (currentReferents.add(embedded))
{
referredMods.add(VersionParser.parseVersionReference(embedded));
}
}
public void addOwnedPackage(String apiPackage)
{
packages.add(apiPackage);
}
public void addAPIReferences(List<String> candidateIds)
{
for (String modId : candidateIds)
{
addAPIReference(modId);
}
}
void markSelfReferenced()
{
selfReferenced = true;
}
}
public void registerDataTableAndParseAPI(ASMDataTable dataTable)
{
this.dataTable = dataTable;
Set<ASMData> apiList = dataTable.getAll("net.minecraftforge.fml.common.API");
apiContainers = Maps.newHashMap();
for (ASMData data : apiList)
{
Map<String, Object> annotationInfo = data.getAnnotationInfo();
String apiPackage = data.getClassName().substring(0,data.getClassName().indexOf(".package-info"));
String providedAPI = (String) annotationInfo.get("provides");
String apiOwner = (String) annotationInfo.get("owner");
String apiVersion = (String) annotationInfo.get("apiVersion");
APIContainer container = apiContainers.get(providedAPI);
if (container == null)
{
container = new APIContainer(providedAPI, apiVersion, data.getCandidate().getModContainer(), VersionParser.parseVersionReference(apiOwner));
apiContainers.put(providedAPI, container);
}
else
{
container.validate(providedAPI, apiOwner, apiVersion);
}
container.addOwnedPackage(apiPackage);
for (ModContainer mc : data.getCandidate().getContainedMods())
{
String embeddedIn = mc.getModId();
if (container.currentReferents.contains(embeddedIn))
{
continue;
}
FMLLog.fine("Found API %s (owned by %s providing %s) embedded in %s",apiPackage, apiOwner, providedAPI, embeddedIn);
if (!embeddedIn.equals(apiOwner))
{
container.addAPIReference(embeddedIn);
}
}
}
for (APIContainer container : apiContainers.values())
{
for (String pkg : container.packages)
{
Set<ModCandidate> candidates = dataTable.getCandidatesFor(pkg);
for (ModCandidate candidate : candidates)
{
List<String> candidateIds = Lists.transform(candidate.getContainedMods(), new ModIdFunction());
if (!candidateIds.contains(container.ownerMod.getLabel()) && !container.currentReferents.containsAll(candidateIds))
{
FMLLog.info("Found mod(s) %s containing declared API package %s (owned by %s) without associated API reference",candidateIds, pkg, container.ownerMod);
container.addAPIReferences(candidateIds);
}
}
}
if (apiContainers.containsKey(container.ownerMod.getLabel()))
{
ArtifactVersion owner = container.ownerMod;
do
{
APIContainer parent = apiContainers.get(owner.getLabel());
if (parent == container)
{
FMLLog.finer("APIContainer %s is it's own parent. skipping", owner);
container.markSelfReferenced();
break;
}
FMLLog.finer("Removing upstream parent %s from %s", parent.ownerMod.getLabel(), container);
container.currentReferents.remove(parent.ownerMod.getLabel());
container.referredMods.remove(parent.ownerMod);
owner = parent.ownerMod;
}
while (apiContainers.containsKey(owner.getLabel()));
}
FMLLog.fine("Creating API container dummy for API %s: owner: %s, dependents: %s", container.providedAPI, container.ownerMod, container.referredMods);
}
}
public void manageAPI(ModClassLoader modClassLoader, ModDiscoverer discoverer)
{
registerDataTableAndParseAPI(discoverer.getASMTable());
transformer = modClassLoader.addModAPITransformer(dataTable);
}
public void injectAPIModContainers(List<ModContainer> mods, Map<String, ModContainer> nameLookup)
{
mods.addAll(apiContainers.values());
nameLookup.putAll(apiContainers);
}
public void cleanupAPIContainers(List<ModContainer> mods)
{
mods.removeAll(apiContainers.values());
}
public boolean hasAPI(String modId)
{
return apiContainers.containsKey(modId);
}
public Iterable<? extends ModContainer> getAPIList()
{
return apiContainers.values();
}
}
@@ -0,0 +1,151 @@
/*
* 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.common;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.asm.transformers.ModAPITransformer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import org.apache.logging.log4j.Level;
import com.google.common.collect.ImmutableList;
/**
* A simple delegating class loader used to load mods into the system
*
*
* @author cpw
*
*/
public class ModClassLoader extends URLClassLoader
{
private static final List<String> STANDARD_LIBRARIES = ImmutableList.of("jinput.jar", "lwjgl.jar", "lwjgl_util.jar", "rt.jar");
private LaunchClassLoader mainClassLoader;
public ModClassLoader(ClassLoader parent) {
super(new URL[0], null);
this.mainClassLoader = (LaunchClassLoader)parent;
}
public void addFile(File modFile) throws MalformedURLException
{
URL url = modFile.toURI().toURL();
mainClassLoader.addURL(url);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException
{
return mainClassLoader.loadClass(name);
}
public File[] getParentSources() {
try
{
List<File> files=new ArrayList<File>();
for(URL url : mainClassLoader.getSources())
{
URI uri = url.toURI();
if(uri.getScheme().equals("file"))
{
files.add(new File(uri));
}
}
return files.toArray(new File[]{});
}
catch (URISyntaxException e)
{
FMLLog.log(Level.ERROR, e, "Unable to process our input to locate the minecraft code");
throw new LoaderException(e);
}
}
public List<String> getDefaultLibraries()
{
return STANDARD_LIBRARIES;
}
public boolean isDefaultLibrary(File file)
{
// Should really pull this from the json somehow, but we dont have that at runtime.
String name = file.getName();
if (!name.endsWith(".jar")) return false;
String[] prefixes =
{
"launchwrapper-",
"asm-all-",
"akka-actor_2.11-",
"config-",
"scala-",
"jopt-simple-",
"lzma-",
"realms-",
"httpclient-",
"httpcore-",
"vecmath-",
"trove4j-",
"icu4j-core-mojang-",
"codecjorbis-",
"codecwav-",
"libraryjavawound-",
"librarylwjglopenal-",
"soundsystem-",
"netty-all-",
"quava-",
"commons-lang3-",
"commons-compress-",
"commons-logging-",
"commons-io-",
"commons-codec-",
"jinput-",
"jutils-",
"gson-",
"authlib-",
"log4j-api-",
"log4j-core-",
"lwjgl-",
"lwjgl_util-",
"twitch-"
};
for (String s : prefixes)
{
if (name.startsWith(s)) return true;
}
return false;
}
public void clearNegativeCacheFor(Set<String> classList)
{
mainClassLoader.clearNegativeEntries(classList);
}
public ModAPITransformer addModAPITransformer(ASMDataTable dataTable)
{
mainClassLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ModAPITransformer");
List<IClassTransformer> transformers = mainClassLoader.getTransformers();
ModAPITransformer modAPI = (ModAPITransformer) transformers.get(transformers.size()-1);
modAPI.initTable(dataTable);
return modAPI;
}
}
@@ -0,0 +1,152 @@
/*
* 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.common;
import java.io.File;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.VersionRange;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
/**
* The container that wraps around mods in the system.
* <p>
* The philosophy is that individual mod implementation technologies should not
* impact the actual loading and management of mod code. This interface provides
* a mechanism by which we can wrap actual mod code so that the loader and other
* facilities can treat mods at arms length.
* </p>
*
* @author cpw
*
*/
public interface ModContainer
{
public static enum Disableable {
YES, RESTART, NEVER, DEPENDENCIES;
}
/**
* The globally unique modid for this mod
*/
String getModId();
/**
* A human readable name
*/
String getName();
/**
* A human readable version identifier
*/
String getVersion();
/**
* The location on the file system which this mod came from
*/
File getSource();
/**
* The metadata for this mod
*/
ModMetadata getMetadata();
/**
* Attach this mod to it's metadata from the supplied metadata collection
*/
void bindMetadata(MetadataCollection mc);
/**
* Set the enabled/disabled state of this mod
*/
void setEnabledState(boolean enabled);
/**
* A list of the modids that this mod requires loaded prior to loading
*/
Set<ArtifactVersion> getRequirements();
/**
* A list of modids that should be loaded prior to this one. The special
* value <strong>*</strong> indicates to load <em>after</em> any other mod.
*/
List<ArtifactVersion> getDependencies();
/**
* A list of modids that should be loaded <em>after</em> this one. The
* special value <strong>*</strong> indicates to load <em>before</em> any
* other mod.
*/
List<ArtifactVersion> getDependants();
/**
* A representative string encapsulating the sorting preferences for this
* mod
*/
String getSortingRules();
/**
* Register the event bus for the mod and the controller for error handling
* Returns if this bus was successfully registered - disabled mods and other
* mods that don't need real events should return false and avoid further
* processing
*
* @param bus
* @param controller
*/
boolean registerBus(EventBus bus, LoadController controller);
/**
* Does this mod match the supplied mod
*
* @param mod
*/
boolean matches(Object mod);
/**
* Get the actual mod object
*/
Object getMod();
ArtifactVersion getProcessedVersion();
boolean isImmutable();
String getDisplayVersion();
VersionRange acceptableMinecraftVersionRange();
Certificate getSigningCertificate();
public static final Map<String,String> EMPTY_PROPERTIES = ImmutableMap.of();
Map<String,String> getCustomModProperties();
public Class<?> getCustomResourcePackClass();
Map<String, String> getSharedModDescriptor();
Disableable canBeDisabled();
String getGuiClassName();
List<String> getOwnedPackages();
boolean shouldLoadInEnvironment();
}
@@ -0,0 +1,95 @@
/*
* 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.common;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.regex.Pattern;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import net.minecraftforge.fml.common.discovery.asm.ModAnnotation;
import org.apache.logging.log4j.Level;
import org.objectweb.asm.Type;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
public class ModContainerFactory
{
public static Map<Type, Constructor<? extends ModContainer>> modTypes = Maps.newHashMap();
private static Pattern modClass = Pattern.compile(".*(\\.|)(mod\\_[^\\s$]+)$");
private static ModContainerFactory INSTANCE = new ModContainerFactory();
private ModContainerFactory() {
// We always know about Mod type
registerContainerType(Type.getType(Mod.class), FMLModContainer.class);
}
public static ModContainerFactory instance() {
return INSTANCE;
}
public void registerContainerType(Type type, Class<? extends ModContainer> container)
{
try {
Constructor<? extends ModContainer> constructor = container.getConstructor(new Class<?>[] { String.class, ModCandidate.class, Map.class });
modTypes.put(type, constructor);
} catch (Exception e) {
FMLLog.log(Level.ERROR, e, "Critical error : cannot register mod container type %s, it has an invalid constructor");
Throwables.propagate(e);
}
}
public ModContainer build(ASMModParser modParser, File modSource, ModCandidate container)
{
String className = modParser.getASMType().getClassName();
if (modParser.isBaseMod(container.getRememberedBaseMods()) && modClass.matcher(className).find())
{
FMLLog.severe("Found a BaseMod type mod %s", className);
FMLLog.severe("This will not be loaded and will be ignored. ModLoader mechanisms are no longer available.");
}
else if (modClass.matcher(className).find())
{
FMLLog.fine("Identified a class %s following modloader naming convention but not directly a BaseMod or currently seen subclass", className);
container.rememberModCandidateType(modParser);
}
else if (modParser.isBaseMod(container.getRememberedBaseMods()))
{
FMLLog.fine("Found a basemod %s of non-standard naming format", className);
container.rememberBaseModType(className);
}
for (ModAnnotation ann : modParser.getAnnotations())
{
if (modTypes.containsKey(ann.getASMType()))
{
FMLLog.fine("Identified a mod of type %s (%s) - loading", ann.getASMType(), className);
try {
ModContainer ret = modTypes.get(ann.getASMType()).newInstance(className, container, ann.getValues());
if (!ret.shouldLoadInEnvironment())
{
FMLLog.fine("Skipping mod %s, container opted to not load.", className);
return null;
}
return ret;
} catch (Exception e) {
FMLLog.log(Level.ERROR, e, "Unable to construct %s container", ann.getASMType().getClassName());
return null;
}
}
}
return null;
}
}
@@ -0,0 +1,82 @@
/*
* 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.common;
import java.util.List;
import java.util.Set;
import net.minecraftforge.fml.common.functions.ModNameFunction;
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.annotations.SerializedName;
/**
* @author cpw
*
*/
public class ModMetadata
{
@SerializedName("modid")
public String modId;
public String name;
public String description = "";
public String url = "";
public String updateUrl = "";
public String logoFile = "";
public String version = "";
public List<String> authorList = Lists.newArrayList();
public String credits = "";
public String parent = "";
public String[] screenshots;
// this field is not for use in the json
public transient ModContainer parentMod;
// this field is not for use in the json
public transient List<ModContainer> childMods = Lists.newArrayList();
public boolean useDependencyInformation;
public Set<ArtifactVersion> requiredMods = Sets.newHashSet();
public List<ArtifactVersion> dependencies = Lists.newArrayList();
public List<ArtifactVersion> dependants = Lists.newArrayList();
// this field is not for use in the json
public transient boolean autogenerated;
public ModMetadata()
{
}
public String getChildModCountString()
{
return String.format("%d child mod%s", childMods.size(), childMods.size() != 1 ? "s" : "");
}
public String getAuthorList()
{
return Joiner.on(", ").join(authorList);
}
public String getChildModList()
{
return Joiner.on(", ").join(Lists.transform(childMods, new ModNameFunction()));
}
public String printableSortingRules()
{
return "";
}
}
@@ -0,0 +1,105 @@
/*
* 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.common;
import java.util.Arrays;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToAccessFieldException;
import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToFindFieldException;
import org.apache.logging.log4j.Level;
/**
* Some reflection helper code.
*
* @author cpw
*
*/
public class ObfuscationReflectionHelper
{
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, int fieldIndex)
{
try
{
return ReflectionHelper.getPrivateValue(classToAccess, instance, fieldIndex);
}
catch (UnableToAccessFieldException e)
{
FMLLog.log(Level.ERROR, e, "There was a problem getting field index %d from %s", fieldIndex, classToAccess.getName());
throw e;
}
}
public static String[] remapFieldNames(String className, String... fieldNames)
{
String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(className.replace('.', '/'));
String[] mappedNames = new String[fieldNames.length];
int i = 0;
for (String fName : fieldNames)
{
mappedNames[i++] = FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fName, null);
}
return mappedNames;
}
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, String... fieldNames)
{
try
{
return ReflectionHelper.getPrivateValue(classToAccess, instance, remapFieldNames(classToAccess.getName(),fieldNames));
}
catch (UnableToFindFieldException e)
{
FMLLog.log(Level.ERROR,e,"Unable to locate any field %s on type %s", Arrays.toString(fieldNames), classToAccess.getName());
throw e;
}
catch (UnableToAccessFieldException e)
{
FMLLog.log(Level.ERROR, e, "Unable to access any field %s on type %s", Arrays.toString(fieldNames), classToAccess.getName());
throw e;
}
}
public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T instance, E value, int fieldIndex)
{
try
{
ReflectionHelper.setPrivateValue(classToAccess, instance, value, fieldIndex);
}
catch (UnableToAccessFieldException e)
{
FMLLog.log(Level.ERROR, e, "There was a problem setting field index %d on type %s", fieldIndex, classToAccess.getName());
throw e;
}
}
public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T instance, E value, String... fieldNames)
{
try
{
ReflectionHelper.setPrivateValue(classToAccess, instance, value, remapFieldNames(classToAccess.getName(), fieldNames));
}
catch (UnableToFindFieldException e)
{
FMLLog.log(Level.ERROR, e, "Unable to locate any field %s on type %s", Arrays.toString(fieldNames), classToAccess.getName());
throw e;
}
catch (UnableToAccessFieldException e)
{
FMLLog.log(Level.ERROR, e, "Unable to set any field %s on type %s", Arrays.toString(fieldNames), classToAccess.getName());
throw e;
}
}
}
@@ -0,0 +1,76 @@
package net.minecraftforge.fml.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Classes annotated with this will have the named interface or method removed from the runtime definition of the class
* if the modid specified is missing.
*
* @author cpw
*
*/
public final class Optional {
/**
* Not constructable
*/
private Optional() {}
/**
* Mark a list of interfaces as removable
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InterfaceList {
/**
* Mark a list of interfaces for optional removal.
* @return
*/
public Interface[] value();
}
/**
* Used to remove optional interfaces
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Interface {
/**
* The fully qualified name of the interface to be stripped
* @return the interface name
*/
public String iface();
/**
* The modid that is required to be present for stripping NOT to occur
* @return the modid
*/
public String modid();
/**
* Strip references to this interface in method declarations? (Useful to kill synthetic methods from scala f.e.)
*
* @return if references should be stripped
*/
public boolean striprefs() default false;
}
/**
* Used to remove optional methods
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Method {
/**
* The modid that is required to be present for stripping NOT to occur
* @return the modid
*/
public String modid();
}
}
@@ -0,0 +1,134 @@
package net.minecraftforge.fml.common;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.common.base.Joiner;
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public class ProgressManager
{
private static final List<ProgressBar> bars = new CopyOnWriteArrayList<ProgressBar>();
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static ProgressBar push(String title, int steps)
{
return push(title, steps, false);
}
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static ProgressBar push(String title, int steps, boolean timeEachStep)
{
ProgressBar bar = new ProgressBar(title, steps);
bars.add(bar);
if (timeEachStep)
{
bar.timeEachStep();
}
FMLCommonHandler.instance().processWindowMessages();
return bar;
}
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static void pop(ProgressBar bar)
{
if(bar.getSteps() != bar.getStep()) throw new IllegalStateException("can't pop unfinished ProgressBar " + bar.getTitle());
bars.remove(bar);
if (bar.getSteps() != 0)
{
long newTime = System.nanoTime();
if (bar.timeEachStep)
FMLLog.fine("Bar Step: %s - %s took %.3fs", bar.getTitle(), bar.getMessage(), ((float)(newTime - bar.lastTime) / 1000000 / 1000));
if (bar.getSteps() == 1)
FMLLog.fine("Bar Finished: %s - %s took %.3fs", bar.getTitle(), bar.getMessage(), ((float)(newTime - bar.startTime) / 1000000 / 1000));
else
FMLLog.fine("Bar Finished: %s took %.3fs", bar.getTitle(), ((float)(newTime - bar.startTime) / 1000000 / 1000));
}
FMLCommonHandler.instance().processWindowMessages();
}
/*
* Internal use only.
*/
public static Iterator<ProgressBar> barIterator()
{
return bars.iterator();
}
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static class ProgressBar
{
private final String title;
private final int steps;
private volatile int step = 0;
private volatile String message = "";
private boolean timeEachStep = false;
private long startTime = System.nanoTime();
private long lastTime = startTime;
private ProgressBar(String title, int steps)
{
this.title = title;
this.steps = steps;
}
public void step(Class<?> classToName, String... extra)
{
step(ClassNameUtils.shortName(classToName)+Joiner.on(' ').join(extra));
}
public void step(String message)
{
if(step >= steps) throw new IllegalStateException("too much steps for ProgressBar " + title);
if (timeEachStep && step != 0)
{
long newTime = System.nanoTime();
FMLLog.fine("Bar Step: %s - %s took %.3fs", getTitle(), getMessage(), ((float)(newTime - lastTime) / 1000000 / 1000));
lastTime = newTime;
}
step++;
this.message = FMLCommonHandler.instance().stripSpecialChars(message);
FMLCommonHandler.instance().processWindowMessages();
}
public String getTitle()
{
return title;
}
public int getSteps()
{
return steps;
}
public int getStep()
{
return step;
}
public String getMessage()
{
return message;
}
public void timeEachStep()
{
this.timeEachStep = true;
}
}
}
@@ -0,0 +1,84 @@
/*
* 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.common;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Set;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.logging.log4j.Level;
import com.google.common.base.Strings;
/**
* @author cpw
*
*/
public class ProxyInjector
{
public static void inject(ModContainer mod, ASMDataTable data, Side side, ILanguageAdapter languageAdapter)
{
FMLLog.fine("Attempting to inject @SidedProxy classes into %s", mod.getModId());
Set<ASMData> targets = data.getAnnotationsFor(mod).get(SidedProxy.class.getName());
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.severe("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName());
throw new LoaderException(String.format("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName()));
}
target.setAccessible(true);
SidedProxy annotation = target.getAnnotation(SidedProxy.class);
if (!Strings.isNullOrEmpty(annotation.modId()) && !annotation.modId().equals(mod.getModId()))
{
FMLLog.fine("Skipping proxy injection for %s.%s since it is not for mod %s", targ.getClassName(), targ.getObjectName(), mod.getModId());
continue;
}
String targetType = side.isClient() ? annotation.clientSide() : annotation.serverSide();
Object proxy=Class.forName(targetType, true, mcl).newInstance();
if (languageAdapter.supportsStatics() && (target.getModifiers() & Modifier.STATIC) == 0 )
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName()));
}
if (!target.getType().isAssignableFrom(proxy.getClass()))
{
FMLLog.severe("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName());
throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName()));
}
languageAdapter.setProxy(target, proxyTarget, proxy);
}
catch (Exception e)
{
FMLLog.log(Level.ERROR, e, "An error occured trying to load a proxy into %s.%s", targ.getAnnotationInfo(), targ.getClassName(), targ.getObjectName());
throw new LoaderException(e);
}
}
// Allow language specific proxy injection.
languageAdapter.setInternalProxies(mod, side, mcl);
}
}
@@ -0,0 +1,20 @@
package net.minecraftforge.fml.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A method annotated with this on the {@link Mod} will be called whenever a local save is listed in
* the save games list.
*
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SaveInspectionHandler
{
}
@@ -0,0 +1,68 @@
/*
* 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.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Sided proxies are loaded based on the specific environment they find themselves loaded into.
* They are used to ensure that client-specific code (such as GUIs) is only loaded into the game
* on the client side.
* It is applied to static fields of a class, anywhere in your mod code. FML will scan
* and load any classes with this annotation at mod construction time.
*
* <p>
* This example will load a CommonProxy on the server side, and a ClientProxy on the client side.
*
* <pre>{@code
* public class MySidedProxyHolder {
* {@literal @}SidedProxy(modId="MyModId",clientSide="mymod.ClientProxy", serverSide="mymod.CommonProxy")
* public static CommonProxy proxy;
* }
*
* public class CommonProxy {
* // Common or server stuff here that needs to be overridden on the client
* }
*
* public class ClientProxy extends CommonProxy {
* // Override common stuff with client specific stuff here
* }
* }
* </pre>
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SidedProxy
{
/**
* The name of the client side class to load and populate
*/
String clientSide() default "";
/**
* The name of the server side class to load and populate
*/
String serverSide() default "";
/**
* The (optional) name of a mod to load this proxy for. This will help ensure correct behaviour when loading a combined
* scala/java mod package. It is almost never going to be required, unless you ship both Scala and Java {@link Mod} content
* in a single jar.
*/
String modId() default "";
}
@@ -0,0 +1,160 @@
package net.minecraftforge.fml.common;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import net.minecraft.server.MinecraftServer;
public class StartupQuery {
// internal class/functionality, do not use
public static boolean confirm(String text)
{
StartupQuery query = new StartupQuery(text, new AtomicBoolean());
query.execute();
return query.getResult();
}
public static void notify(String text)
{
StartupQuery query = new StartupQuery(text, null);
query.execute();
}
public static void abort()
{
MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
if (server != null) server.initiateShutdown();
aborted = true; // to abort loading and go back to the main menu
throw new AbortedException(); // to halt the server
}
public static void reset()
{
pending = null;
aborted = false;
}
public static boolean check()
{
if (pending != null)
{
try
{
FMLCommonHandler.instance().queryUser(pending);
}
catch (InterruptedException e)
{
FMLLog.warning("query interrupted");
abort();
}
pending = null;
}
return !aborted;
}
private static volatile StartupQuery pending;
private static volatile boolean aborted = false;
private StartupQuery(String text, AtomicBoolean result)
{
this.text = text;
this.result = result;
}
public Boolean getResult()
{
return result == null ? null : result.get();
}
public void setResult(boolean result)
{
this.result.set(result);
}
public String getText()
{
return text;
}
public boolean isSynchronous()
{
return synchronous;
}
public void finish()
{
signal.countDown();
}
private void execute()
{
String prop = System.getProperty("fml.queryResult");
if (result != null && prop != null)
{
FMLLog.info("Using fml.queryResult %s to answer the following query:\n%s", prop, text);
if (prop.equalsIgnoreCase("confirm"))
{
setResult(true);
return;
}
else if (prop.equalsIgnoreCase("cancel"))
{
setResult(false);
return;
}
FMLLog.warning("Invalid value for fml.queryResult: %s, expected confirm or cancel", prop);
}
synchronous = false;
pending = this; // let the other thread start the query
// from the integrated server thread: the client will eventually check pending and execute the query
// from the client thread: synchronous execution
// dedicated server: command handling in mc is synchronous, execute the server-side query directly
if (FMLCommonHandler.instance().getSide().isServer() ||
FMLCommonHandler.instance().getEffectiveSide().isClient())
{
synchronous = true;
check();
}
try
{
signal.await();
reset();
}
catch (InterruptedException e)
{
FMLLog.warning("query interrupted");
abort();
}
}
private String text;
private AtomicBoolean result;
private CountDownLatch signal = new CountDownLatch(1);
private volatile boolean synchronous;
/**
* Exception not being caught by the crash report generation logic.
*/
public static class AbortedException extends RuntimeException
{
private static final long serialVersionUID = -5933665223696833921L;
private AbortedException()
{
super();
}
}
}
@@ -0,0 +1,50 @@
/*
* 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
*/
package net.minecraftforge.fml.common;
import java.io.PrintStream;
import org.apache.logging.log4j.Logger;
/**
* PrintStream which redirects it's output to a given logger.
*
* @author Arkan
*/
public class TracingPrintStream extends PrintStream {
private Logger logger;
private int BASE_DEPTH = 3;
public TracingPrintStream(Logger logger, PrintStream original) {
super(original);
this.logger = logger;
}
@Override
public void println(Object o) {
logger.info(getPrefix() + o);
}
@Override
public void println(String s) {
logger.info(getPrefix() + s);
}
private String getPrefix() {
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
StackTraceElement elem = elems[BASE_DEPTH]; // The caller is always at BASE_DEPTH, including this call.
if (elem.getClassName().startsWith("kotlin.io.")) {
elem = elems[BASE_DEPTH + 2]; // Kotlins IoPackage masks origins 2 deeper in the stack.
}
return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: ";
}
}
@@ -0,0 +1,25 @@
/*
* 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.common;
import java.util.Map;
import net.minecraft.nbt.*;
import net.minecraft.world.storage.*;
public interface WorldAccessContainer
{
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info);
public void readData(SaveHandler handler, WorldInfo info, Map<String,NBTBase> propertyMap, NBTTagCompound tag);
}
@@ -0,0 +1,26 @@
/*
* 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.common;
public class WrongMinecraftVersionException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public ModContainer mod;
public WrongMinecraftVersionException(ModContainer mod)
{
super(String.format("Wrong Minecraft version for %s", mod.getModId()));
this.mod = mod;
}
}
@@ -0,0 +1,92 @@
package net.minecraftforge.fml.common;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Deque;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.logging.log4j.Level;
import com.google.common.io.Files;
/**
* Copied from http://stackoverflow.com/questions/1399126/java-util-zip-recreating-directory-structure
* because the code looked very tidy and neat. Thanks, McDowell!
*
* @author McDowell
*
*/
public class ZipperUtil {
public static void zip(File directory, File zipfile) throws IOException
{
URI base = directory.toURI();
Deque<File> queue = new LinkedList<File>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = null;
try
{
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty())
{
directory = queue.pop();
for (File kid : directory.listFiles())
{
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory())
{
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else
{
zout.putNextEntry(new ZipEntry(name));
Files.copy(kid, zout);
zout.closeEntry();
}
}
}
} finally
{
res.close();
}
}
public static void backupWorld() throws IOException
{
String dirName = FMLCommonHandler.instance().getMinecraftServerInstance().getFolderName();
backupWorld(dirName);
}
@Deprecated
public static void backupWorld(String dirName, String saveName) throws IOException
{
backupWorld(dirName);
}
public static void backupWorld(String dirName) throws IOException
{
File dstFolder = FMLCommonHandler.instance().getSavesDirectory();
File zip = new File(dstFolder, String.format("%s-%2$tY%2$tm%2$td-%2$tH%2$tM%2$tS.zip", dirName, System.currentTimeMillis()));
try
{
ZipperUtil.zip(new File(dstFolder, dirName), zip);
}
catch (IOException e)
{
FMLLog.log(Level.WARN, e, "World backup failed.");
throw e;
}
FMLLog.info("World backup created at %s.", zip.getCanonicalPath());
}
}
@@ -0,0 +1,256 @@
package net.minecraftforge.fml.common.asm;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.security.Permission;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
public class ASMTransformerWrapper
{
private static final Map<String, String> wrapperModMap = Maps.newHashMap();
private static final Map<String, String> wrapperParentMap = Maps.newHashMap();
private static final LoadingCache<String, byte[]> wrapperCache = CacheBuilder.newBuilder()
.maximumSize(30)
.weakValues()
.build(new CacheLoader<String, byte[]>()
{
public byte[] load(String file) throws Exception
{
return makeWrapper(file);
}
});
private static final URL asmGenRoot;
private static boolean injected = false;
static
{
try
{
asmGenRoot = new URL("asmgen", null, -1, "/", new ASMGenHandler());
}
catch(MalformedURLException e)
{
throw new RuntimeException(e);
}
}
private static class ASMGenHandler extends URLStreamHandler
{
protected URLConnection openConnection(URL url) throws IOException
{
String file = url.getFile();
if(file.equals("/"))
{
return new URLConnection(url)
{
public void connect() throws IOException
{
throw new UnsupportedOperationException();
}
};
}
if(!file.startsWith("/")) throw new RuntimeException("Malformed URL: " + url);
file = file.substring(1);
if(wrapperModMap.containsKey(file))
{
return new ASMGenConnection(url, file);
}
return null;
}
}
private static class ASMGenConnection extends URLConnection
{
private final String file;
protected ASMGenConnection(URL url, String file)
{
super(url);
this.file = file;
}
public void connect() throws IOException
{
throw new UnsupportedOperationException();
}
@Override
public InputStream getInputStream()
{
return new ByteArrayInputStream(wrapperCache.getUnchecked(file));
}
@Override
public Permission getPermission()
{
return null;
}
}
public static String getTransformerWrapper(LaunchClassLoader launchLoader, String parentClass, String coreMod)
{
if(!injected)
{
injected = true;
launchLoader.addURL(asmGenRoot);
}
String name = getWrapperName(parentClass);
String fileName = name.replace('.', '/') + ".class";
wrapperModMap.put(fileName, coreMod);
wrapperParentMap.put(fileName, parentClass);
return name;
}
private static byte[] makeWrapper(String fileName)
{
if(!wrapperModMap.containsKey(fileName) || !wrapperParentMap.containsKey(fileName) || !fileName.endsWith(".class"))
{
throw new IllegalArgumentException("makeWrapper called with strange argument: " + fileName);
}
String name = fileName.substring(0, fileName.length() - ".class".length());
try
{
Type wrapper = Type.getType(TransformerWrapper.class);
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, name, null, wrapper.getInternalName(), null);
Method m = Method.getMethod("void <init> ()");
GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, m, null, null, writer);
mg.loadThis();
mg.invokeConstructor(wrapper, m);
mg.returnValue();
mg.endMethod();
m = Method.getMethod("java.lang.String getParentClass ()");
mg = new GeneratorAdapter(Opcodes.ACC_PROTECTED, m, null, null, writer);
mg.push(wrapperParentMap.get(fileName));
mg.returnValue();
mg.endMethod();
m = Method.getMethod("java.lang.String getCoreMod ()");
mg = new GeneratorAdapter(Opcodes.ACC_PROTECTED, m, null, null, writer);
mg.push(wrapperModMap.get(fileName));
mg.returnValue();
mg.endMethod();
writer.visitEnd();
return writer.toByteArray();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private static String getWrapperName(String parentClass)
{
return "$wrapper." + parentClass;
}
private static class WrapperVisitor extends ClassVisitor
{
private final String name;
private final String parentClass;
public WrapperVisitor(ClassVisitor cv, String name, String parentClass)
{
super(Opcodes.ASM5, cv);
this.name = name.replace('.', '/');
this.parentClass = parentClass;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
{
super.visit(version, access, this.name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value)
{
if(name.equals("parentClass"))
{
return super.visitField(access, name, desc, signature, parentClass);
}
return super.visitField(access, name, desc, signature, value);
}
}
public static abstract class TransformerWrapper implements IClassTransformer
{
private final IClassTransformer parent;
public TransformerWrapper()
{
try
{
this.parent = (IClassTransformer)this.getClass().getClassLoader().loadClass(getParentClass()).newInstance();
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
try
{
return parent.transform(name, transformedName, basicClass);
}
catch(Throwable e)
{
throw new TransformerException("Exception in class transformer " + parent + " from coremod " + getCoreMod(), e);
}
}
@Override
public String toString()
{
return "TransformerWrapper(" + getParentClass() + ", " + getCoreMod() + ")";
}
protected abstract String getParentClass();
protected abstract String getCoreMod();
}
static class TransformerException extends RuntimeException
{
public TransformerException(String message, Throwable cause)
{
super(message, cause);
}
}
}
@@ -0,0 +1,185 @@
/*
* 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.common.asm;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.logging.log4j.Level;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.CertificateHelper;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.patcher.ClassPatchManager;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import net.minecraftforge.fml.relauncher.IFMLCallHook;
import net.minecraftforge.fml.relauncher.Side;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
public class FMLSanityChecker implements IFMLCallHook
{
private static final String FMLFINGERPRINT = "51:0A:FB:4C:AF:A4:A0:F2:F5:CF:C5:0E:B4:CC:3C:30:24:4A:E3:8E".toLowerCase().replace(":", "");
private static final String FORGEFINGERPRINT = "E3:C3:D5:0C:7C:98:6D:F7:4C:64:5C:0A:C5:46:39:74:1C:90:A5:57".toLowerCase().replace(":", "");
private static final String MCFINGERPRINT = "CD:99:95:96:56:F7:53:DC:28:D8:63:B4:67:69:F7:F8:FB:AE:FC:FC".toLowerCase().replace(":", "");
private LaunchClassLoader cl;
private boolean liveEnv;
public static File fmlLocation;
@Override
public Void call() throws Exception
{
CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
boolean goodFML = false;
boolean fmlIsJar = false;
if (codeSource.getLocation().getProtocol().equals("jar"))
{
fmlIsJar = true;
Certificate[] certificates = codeSource.getCertificates();
if (certificates!=null)
{
for (Certificate cert : certificates)
{
String fingerprint = CertificateHelper.getFingerprint(cert);
if (fingerprint.equals(FMLFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint);
goodFML = true;
}
else if (fingerprint.equals(FORGEFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint);
goodFML = true;
}
else
{
FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
}
}
}
}
else
{
goodFML = true;
}
// Server is not signed, so assume it's good - a deobf env is dev time so it's good too
boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
int certCount = 0;
try
{
Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever",false, cl);
codeSource = cbr.getProtectionDomain().getCodeSource();
}
catch (Exception e)
{
// Probably a development environment, or the server (the server is not signed)
goodMC = true;
}
JarFile mcJarFile = null;
if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar"))
{
try
{
String mcPath = codeSource.getLocation().getPath().substring(5);
mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
mcJarFile = new JarFile(mcPath,true);
mcJarFile.getManifest();
JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
ByteStreams.toByteArray(mcJarFile.getInputStream(cbrEntry));
Certificate[] certificates = cbrEntry.getCertificates();
certCount = certificates != null ? certificates.length : 0;
if (certificates!=null)
{
for (Certificate cert : certificates)
{
String fingerprint = CertificateHelper.getFingerprint(cert);
if (fingerprint.equals(MCFINGERPRINT))
{
FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint);
goodMC = true;
}
}
}
}
catch (Throwable e)
{
FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file");
}
finally
{
if (mcJarFile != null)
{
try
{
mcJarFile.close();
}
catch (IOException ioe)
{
// Noise
}
}
}
}
else
{
goodMC = true;
}
if (!goodMC)
{
FMLRelaunchLog.severe("The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",codeSource.getLocation().getFile());
if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates","false")))
{
FMLRelaunchLog.severe("For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
FMLRelaunchLog.severe("Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " +
"and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " +
"run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " +
"want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
FMLCommonHandler.instance().exitJava(1, false);
}
else
{
FMLRelaunchLog.severe("FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
FMLRelaunchLog.severe("Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount);
}
}
if (!goodFML)
{
FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
}
return null;
}
@Override
public void injectData(Map<String, Object> data)
{
liveEnv = (Boolean)data.get("runtimeDeobfuscationEnabled");
cl = (LaunchClassLoader) data.get("classLoader");
File mcDir = (File)data.get("mcLocation");
fmlLocation = (File)data.get("coremodLocation");
ClassPatchManager.INSTANCE.setup(FMLLaunchHandler.side());
FMLDeobfuscatingRemapper.INSTANCE.setup(mcDir, cl, (String) data.get("deobfuscationFileName"));
}
}
@@ -0,0 +1,29 @@
/*
* 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.common.asm;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to force certain classes to reobfuscate
* @author cpw
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ReobfuscationMarker {
}
@@ -0,0 +1,496 @@
/*
* 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.common.asm.transformers;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
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.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.io.CharSource;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
public class AccessTransformer implements IClassTransformer
{
private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("fml.debugAccessTransformer", "false"));
class Modifier
{
public String name = "";
public String desc = "";
public int oldAccess = 0;
public int newAccess = 0;
public int targetAccess = 0;
public boolean changeFinal = false;
public boolean markFinal = false;
protected boolean modifyClassVisibility;
private void setTargetAccess(String name)
{
if (name.startsWith("public")) targetAccess = ACC_PUBLIC;
else if (name.startsWith("private")) targetAccess = ACC_PRIVATE;
else if (name.startsWith("protected")) targetAccess = ACC_PROTECTED;
if (name.endsWith("-f"))
{
changeFinal = true;
markFinal = false;
}
else if (name.endsWith("+f"))
{
changeFinal = true;
markFinal = true;
}
}
}
private Multimap<String, Modifier> modifiers = ArrayListMultimap.create();
public AccessTransformer() throws IOException
{
this("fml_at.cfg");
}
protected AccessTransformer(String rulesFile) throws IOException
{
readMapFile(rulesFile);
}
AccessTransformer(Class<? extends AccessTransformer> dummyClazz)
{
// This is a noop
}
void readMapFile(String rulesFile) throws IOException
{
File file = new File(rulesFile);
URL rulesResource;
if (file.exists())
{
rulesResource = file.toURI().toURL();
}
else
{
rulesResource = Resources.getResource(rulesFile);
}
processATFile(Resources.asCharSource(rulesResource, Charsets.UTF_8));
FMLRelaunchLog.fine("Loaded %d rules from AccessTransformer config file %s", modifiers.size(), rulesFile);
}
protected void processATFile(CharSource rulesResource) throws IOException
{
rulesResource.readLines(new LineProcessor<Void>()
{
@Override
public Void getResult()
{
return null;
}
@Override
public boolean processLine(String input) throws IOException
{
String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim();
if (line.length()==0)
{
return true;
}
List<String> parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
if (parts.size()>3)
{
throw new RuntimeException("Invalid config file line "+ input);
}
Modifier m = new Modifier();
m.setTargetAccess(parts.get(0));
if (parts.size() == 2)
{
m.modifyClassVisibility = true;
}
else
{
String nameReference = parts.get(2);
int parenIdx = nameReference.indexOf('(');
if (parenIdx>0)
{
m.desc = nameReference.substring(parenIdx);
m.name = nameReference.substring(0,parenIdx);
}
else
{
m.name = nameReference;
}
}
String className = parts.get(1).replace('/', '.');
modifiers.put(className, m);
if (DEBUG) System.out.printf("AT RULE: %s %s %s (type %s)\n", toBinary(m.targetAccess), m.name, m.desc, className);
return true;
}
});
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
if (DEBUG)
{
FMLRelaunchLog.fine("Considering all methods and fields on %s (%s)\n", transformedName, name);
}
if (!modifiers.containsKey(transformedName)) { return bytes; }
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
Collection<Modifier> mods = modifiers.get(transformedName);
for (Modifier m : mods)
{
if (m.modifyClassVisibility)
{
classNode.access = getFixedAccess(classNode.access, m);
if (DEBUG)
{
System.out.println(String.format("Class: %s %s -> %s", name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
continue;
}
if (m.desc.isEmpty())
{
for (FieldNode n : classNode.fields)
{
if (n.name.equals(m.name) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
if (DEBUG)
{
System.out.println(String.format("Field: %s.%s %s -> %s", name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
else
{
List<MethodNode> nowOverridable = Lists.newArrayList();
for (MethodNode n : classNode.methods)
{
if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
// constructors always use INVOKESPECIAL
if (!n.name.equals("<init>"))
{
// if we changed from private to something else we need to replace all INVOKESPECIAL calls to this method with INVOKEVIRTUAL
// so that overridden methods will be called. Only need to scan this class, because obviously the method was private.
boolean wasPrivate = (m.oldAccess & ACC_PRIVATE) == ACC_PRIVATE;
boolean isNowPrivate = (m.newAccess & ACC_PRIVATE) == ACC_PRIVATE;
if (wasPrivate && !isNowPrivate)
{
nowOverridable.add(n);
}
}
if (DEBUG)
{
System.out.println(String.format("Method: %s.%s%s %s -> %s", name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
replaceInvokeSpecial(classNode, nowOverridable);
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private void replaceInvokeSpecial(ClassNode clazz, List<MethodNode> toReplace)
{
for (MethodNode method : clazz.methods)
{
for (Iterator<AbstractInsnNode> it = method.instructions.iterator(); it.hasNext();)
{
AbstractInsnNode insn = it.next();
if (insn.getOpcode() == INVOKESPECIAL)
{
MethodInsnNode mInsn = (MethodInsnNode) insn;
for (MethodNode n : toReplace)
{
if (n.name.equals(mInsn.name) && n.desc.equals(mInsn.desc))
{
mInsn.setOpcode(INVOKEVIRTUAL);
break;
}
}
}
}
}
}
private String toBinary(int num)
{
return String.format("%16s", Integer.toBinaryString(num)).replace(' ', '0');
}
private int getFixedAccess(int access, Modifier target)
{
target.oldAccess = access;
int t = target.targetAccess;
int ret = (access & ~7);
switch (access & 7)
{
case ACC_PRIVATE:
ret |= t;
break;
case 0: // default
ret |= (t != ACC_PRIVATE ? t : 0 /* default */);
break;
case ACC_PROTECTED:
ret |= (t != ACC_PRIVATE && t != 0 /* default */? t : ACC_PROTECTED);
break;
case ACC_PUBLIC:
ret |= (t != ACC_PRIVATE && t != 0 /* default */&& t != ACC_PROTECTED ? t : ACC_PUBLIC);
break;
default:
throw new RuntimeException("The fuck?");
}
// Clear the "final" marker on fields only if specified in control field
if (target.changeFinal)
{
if (target.markFinal)
{
ret |= ACC_FINAL;
}
else
{
ret &= ~ACC_FINAL;
}
}
target.newAccess = ret;
return ret;
}
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: AccessTransformer <JarPath> <MapFile> [MapFile2]... ");
System.exit(1);
}
boolean hasTransformer = false;
AccessTransformer[] trans = new AccessTransformer[args.length - 1];
for (int x = 1; x < args.length; x++)
{
try
{
trans[x - 1] = new AccessTransformer(args[x]);
hasTransformer = true;
}
catch (IOException e)
{
System.out.println("Could not read Transformer Map: " + args[x]);
e.printStackTrace();
}
}
if (!hasTransformer)
{
System.out.println("Culd not find a valid transformer to perform");
System.exit(1);
}
File orig = new File(args[0]);
File temp = new File(args[0] + ".ATBack");
if (!orig.exists() && !temp.exists())
{
System.out.println("Could not find target jar: " + orig);
System.exit(1);
}
if (!orig.renameTo(temp))
{
System.out.println("Could not rename file: " + orig + " -> " + temp);
System.exit(1);
}
try
{
processJar(temp, orig, trans);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
if (!temp.delete())
{
System.out.println("Could not delete temp file: " + temp);
}
}
private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException
{
ZipInputStream inJar = null;
ZipOutputStream outJar = null;
try
{
try
{
inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open input file: " + e.getMessage());
}
try
{
outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open output file: " + e.getMessage());
}
ZipEntry entry;
while ((entry = inJar.getNextEntry()) != null)
{
if (entry.isDirectory())
{
outJar.putNextEntry(entry);
continue;
}
byte[] data = new byte[4096];
ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();
int len;
do
{
len = inJar.read(data);
if (len > 0)
{
entryBuffer.write(data, 0, len);
}
}
while (len != -1);
byte[] entryData = entryBuffer.toByteArray();
String entryName = entry.getName();
if (entryName.endsWith(".class") && !entryName.startsWith("."))
{
ClassNode cls = new ClassNode();
ClassReader rdr = new ClassReader(entryData);
rdr.accept(cls, 0);
String name = cls.name.replace('/', '.').replace('\\', '.');
for (AccessTransformer trans : transformers)
{
entryData = trans.transform(name, name, entryData);
}
}
ZipEntry newEntry = new ZipEntry(entryName);
outJar.putNextEntry(newEntry);
outJar.write(entryData);
}
}
finally
{
if (outJar != null)
{
try
{
outJar.close();
}
catch (IOException e)
{
}
}
if (inJar != null)
{
try
{
inJar.close();
}
catch (IOException e)
{
}
}
}
}
Multimap<String, Modifier> getModifiers()
{
return modifiers;
}
boolean isEmpty()
{
return modifiers.isEmpty();
}
}
@@ -0,0 +1,119 @@
package net.minecraftforge.fml.common.asm.transformers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.FMLLog;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import com.google.common.collect.ImmutableSet;
public class BlamingTransformer implements IClassTransformer
{
private static final Map<String, String> classMap = new HashMap<String, String>();
private static final Set<String> naughtyMods = new HashSet<String>();
private static final Set<String> naughtyClasses = new TreeSet<String>();
private static final Set<String> orphanNaughtyClasses = new HashSet();
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
ClassReader classReader = new ClassReader(bytes);
VersionVisitor visitor = new VersionVisitor();
classReader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
return bytes;
}
public static void blame(String modId, String cls)
{
naughtyClasses.add(cls);
naughtyMods.add(modId);
FMLLog.severe("Unsupported class format in mod %s: class %s", modId, cls);
}
public static class VersionVisitor extends ClassVisitor
{
public VersionVisitor()
{
super(Opcodes.ASM5);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
{
if( (version == Opcodes.V1_8 && !SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) ||
(version == Opcodes.V1_7 && !SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_7)) )
{
if(classMap.containsKey(name)) blame(classMap.get(name), name);
else orphanNaughtyClasses.add(name);
}
}
}
private static void checkPendingNaughty()
{
ImmutableSet.Builder<String> toRemove = ImmutableSet.builder();
for(String cls : orphanNaughtyClasses)
{
if(classMap.containsKey(cls))
{
String modId = classMap.get(cls);
blame(modId, cls);
toRemove.add(cls);
}
}
orphanNaughtyClasses.removeAll(toRemove.build());
}
public static void addClasses(String modId, Set<String> classList)
{
for(String cls : classList)
{
classMap.put(cls, modId);
}
checkPendingNaughty();
}
public static void onCrash(StringBuilder builder)
{
checkPendingNaughty();
if(!naughtyClasses.isEmpty())
{
builder.append("\n*** ATTENTION: detected classes with unsupported format ***\n");
builder.append("*** DO NOT SUBMIT THIS CRASH REPORT TO FORGE ***\n\n");
if(!naughtyMods.isEmpty())
{
builder.append("Contact authors of the following mods: \n");
for(String modId : naughtyMods)
{
builder.append(" ").append(modId).append("\n");
}
}
if(!orphanNaughtyClasses.isEmpty())
{
builder.append("Unidentified unsupported classes: \n");
for(String cls : orphanNaughtyClasses)
{
builder.append(" ").append(cls).append("\n");
}
}
builder.append('\n');
}
}
}
@@ -0,0 +1,52 @@
/*
* 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.common.asm.transformers;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLRemappingAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.commons.RemappingClassAdapter;
public class DeobfuscationTransformer implements IClassTransformer, IClassNameTransformer {
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null)
{
return null;
}
ClassReader classReader = new ClassReader(bytes);
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
RemappingClassAdapter remapAdapter = new FMLRemappingAdapter(classWriter);
classReader.accept(remapAdapter, ClassReader.EXPAND_FRAMES);
return classWriter.toByteArray();
}
@Override
public String remapClassName(String name)
{
return FMLDeobfuscatingRemapper.INSTANCE.map(name.replace('.','/')).replace('/', '.');
}
@Override
public String unmapClassName(String name)
{
return FMLDeobfuscatingRemapper.INSTANCE.unmap(name.replace('.', '/')).replace('/','.');
}
}
@@ -0,0 +1,74 @@
package net.minecraftforge.fml.common.asm.transformers;
import java.lang.reflect.Modifier;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public class EventSubscriberTransformer implements IClassTransformer
{
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
if (basicClass == null) return null;
ClassNode classNode = new ClassNode();
new ClassReader(basicClass).accept(classNode, 0);
boolean isSubscriber = false;
for (MethodNode methodNode : classNode.methods)
{
List<AnnotationNode> anns = methodNode.visibleAnnotations;
if (anns != null && Iterables.any(anns, SubscribeEventPredicate.INSTANCE))
{
if (Modifier.isPrivate(methodNode.access))
{
String msg = "Cannot apply @SubsribeEvent to private method %s/%s%s";
throw new RuntimeException(String.format(msg, classNode.name, methodNode.name, methodNode.desc));
}
methodNode.access = toPublic(methodNode.access);
isSubscriber = true;
}
}
if (isSubscriber)
{
classNode.access = toPublic(classNode.access);
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
return basicClass;
}
private static int toPublic(int access)
{
return access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC;
}
private static class SubscribeEventPredicate implements Predicate<AnnotationNode>
{
static final SubscribeEventPredicate INSTANCE = new SubscribeEventPredicate();
@Override
public boolean apply(AnnotationNode input)
{
return input.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/SubscribeEvent;");
}
}
}
@@ -0,0 +1,226 @@
package net.minecraftforge.fml.common.asm.transformers;
import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES;
import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS;
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.ASM5;
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.IFNULL;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
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.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Type.VOID_TYPE;
import static org.objectweb.asm.Type.BOOLEAN_TYPE;
import static org.objectweb.asm.Type.getMethodDescriptor;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.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 EventSubscriptionTransformer implements IClassTransformer
{
public EventSubscriptionTransformer()
{
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null || name.equals("net.minecraftforge.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("net.minecraftforge.fml.common.eventhandler.ListenerList", false, getClass().getClassLoader());
Type tList = Type.getType("Lnet/minecraftforge/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 : (List<MethodNode>)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("<init>") && method.desc.equals(voidDesc)) hasDefaultCtr = true;
}
if (classNode.visibleAnnotations != null)
{
for (AnnotationNode node : classNode.visibleAnnotations)
{
if (!hasResult && node.desc.equals("Lnet/minecraftforge/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("Lnet/minecraftforge/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.getType(classNode.superName);
//Add private static ListenerList LISTENER_LIST
classNode.fields.add(new FieldNode(ACC_PRIVATE | ACC_STATIC, "LISTENER_LIST", listDesc, null, null));
/*Add:
* public <init>()
* {
* super();
* }
*/
if (!hasDefaultCtr)
{
MethodNode method = new MethodNode(ACC_PUBLIC, "<init>", voidDesc, null, null);
method.instructions.add(new VarInsnNode(ALOAD, 0));
method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "<init>", 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(), "<init>", 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;
}
}
@@ -0,0 +1,85 @@
package net.minecraftforge.fml.common.asm.transformers;
import java.util.ListIterator;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
public class ItemStackTransformer implements IClassTransformer {
private static final String ITEM_TYPE = "Lnet/minecraft/item/Item;";
private static final String GETITEM_DESC = "()"+ ITEM_TYPE;
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
if (!"net.minecraft.item.ItemStack".equals(name))
return basicClass;
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(basicClass);
classReader.accept(classNode, 0);
FieldNode itemField = null;
for (FieldNode f : classNode.fields)
{
if (ITEM_TYPE.equals(f.desc) && itemField == null)
{
itemField = f;
}
else if (ITEM_TYPE.equals(f.desc))
{
throw new RuntimeException("Error processing ItemStack - found a duplicate Item field");
}
}
if (itemField == null)
{
throw new RuntimeException("Error processing ItemStack - no Item field declared (is the code somehow obfuscated?)");
}
MethodNode getItemMethod = null;
for (MethodNode m: classNode.methods)
{
if (GETITEM_DESC.equals(m.desc) && getItemMethod == null)
{
getItemMethod = m;
}
else if (GETITEM_DESC.equals(m.desc))
{
throw new RuntimeException("Error processing ItemStack - duplicate getItem method found");
}
}
if (getItemMethod == null)
{
throw new RuntimeException("Error processing ItemStack - no getItem method found (is the code somehow obfuscated?)");
}
for (MethodNode m: classNode.methods)
{
for (ListIterator<AbstractInsnNode> it = m.instructions.iterator(); it.hasNext(); )
{
AbstractInsnNode insnNode = it.next();
if (insnNode.getType() == AbstractInsnNode.FIELD_INSN)
{
FieldInsnNode fi = (FieldInsnNode)insnNode;
if (itemField.name.equals(fi.name) && fi.getOpcode() == Opcodes.GETFIELD)
{
it.remove();
MethodInsnNode replace = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "net/minecraft/item/ItemStack",getItemMethod.name, getItemMethod.desc, false);
it.add(replace);
}
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
}
@@ -0,0 +1,288 @@
/*
* 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.common.asm.transformers;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
public class MarkerTransformer implements IClassTransformer
{
private ListMultimap<String, String> markers = ArrayListMultimap.create();
public MarkerTransformer() throws IOException
{
this("fml_marker.cfg");
}
protected MarkerTransformer(String rulesFile) throws IOException
{
readMapFile(rulesFile);
}
private void readMapFile(String rulesFile) throws IOException
{
File file = new File(rulesFile);
URL rulesResource;
if (file.exists())
{
rulesResource = file.toURI().toURL();
}
else
{
rulesResource = Resources.getResource(rulesFile);
}
Resources.readLines(rulesResource, Charsets.UTF_8, new LineProcessor<Void>()
{
@Override
public Void getResult()
{
return null;
}
@Override
public boolean processLine(String input) throws IOException
{
String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim();
if (line.length()==0)
{
return true;
}
List<String> parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
if (parts.size()!=2)
{
throw new RuntimeException("Invalid config file line "+ input);
}
List<String> markerInterfaces = Lists.newArrayList(Splitter.on(",").trimResults().split(parts.get(1)));
for (String marker : markerInterfaces)
{
markers.put(parts.get(0), marker);
}
return true;
}
});
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
if (!markers.containsKey(name)) { return bytes; }
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
for (String marker : markers.get(name))
{
classNode.interfaces.add(marker);
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: MarkerTransformer <JarPath> <MapFile> [MapFile2]... ");
return;
}
boolean hasTransformer = false;
MarkerTransformer[] trans = new MarkerTransformer[args.length - 1];
for (int x = 1; x < args.length; x++)
{
try
{
trans[x - 1] = new MarkerTransformer(args[x]);
hasTransformer = true;
}
catch (IOException e)
{
System.out.println("Could not read Transformer Map: " + args[x]);
e.printStackTrace();
}
}
if (!hasTransformer)
{
System.out.println("Culd not find a valid transformer to perform");
return;
}
File orig = new File(args[0]);
File temp = new File(args[0] + ".ATBack");
if (!orig.exists() && !temp.exists())
{
System.out.println("Could not find target jar: " + orig);
return;
}
/*
if (temp.exists())
{
if (orig.exists() && !orig.renameTo(new File(args[0] + (new SimpleDateFormat(".yyyy.MM.dd.HHmmss")).format(new Date()))))
{
System.out.println("Could not backup existing file: " + orig);
return;
}
if (!temp.renameTo(orig))
{
System.out.println("Could not restore backup from previous run: " + temp);
return;
}
}
*/
if (!orig.renameTo(temp))
{
System.out.println("Could not rename file: " + orig + " -> " + temp);
return;
}
try
{
processJar(temp, orig, trans);
}
catch (IOException e)
{
e.printStackTrace();
}
if (!temp.delete())
{
System.out.println("Could not delete temp file: " + temp);
}
}
private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException
{
ZipInputStream inJar = null;
ZipOutputStream outJar = null;
try
{
try
{
inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open input file: " + e.getMessage());
}
try
{
outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open output file: " + e.getMessage());
}
ZipEntry entry;
while ((entry = inJar.getNextEntry()) != null)
{
if (entry.isDirectory())
{
outJar.putNextEntry(entry);
continue;
}
byte[] data = new byte[4096];
ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();
int len;
do
{
len = inJar.read(data);
if (len > 0)
{
entryBuffer.write(data, 0, len);
}
}
while (len != -1);
byte[] entryData = entryBuffer.toByteArray();
String entryName = entry.getName();
if (entryName.endsWith(".class") && !entryName.startsWith("."))
{
ClassNode cls = new ClassNode();
ClassReader rdr = new ClassReader(entryData);
rdr.accept(cls, 0);
String name = cls.name.replace('/', '.').replace('\\', '.');
for (MarkerTransformer trans : transformers)
{
entryData = trans.transform(name, name, entryData);
}
}
ZipEntry newEntry = new ZipEntry(entryName);
outJar.putNextEntry(newEntry);
outJar.write(entryData);
}
}
finally
{
if (outJar != null)
{
try
{
outJar.close();
}
catch (IOException e)
{
}
}
if (inJar != null)
{
try
{
inJar.close();
}
catch (IOException e)
{
}
}
}
}
}
@@ -0,0 +1,160 @@
package net.minecraftforge.fml.common.asm.transformers;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModAPIManager;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Sets;
public class ModAPITransformer implements IClassTransformer {
private static final boolean logDebugInfo = Boolean.valueOf(System.getProperty("fml.debugAPITransformer", "false"));
private ListMultimap<String, ASMData> optionals;
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
String lookupName = name;
if(name.endsWith("$class"))
{
lookupName = name.substring(0, name.length() - 6);
}
if (optionals == null || !optionals.containsKey(lookupName))
{
return basicClass;
}
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(basicClass);
classReader.accept(classNode, 0);
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - found optionals for class %s - processing", name);
for (ASMData optional : optionals.get(lookupName))
{
String modId = (String) optional.getAnnotationInfo().get("modid");
if (Loader.isModLoaded(modId) || ModAPIManager.INSTANCE.hasAPI(modId))
{
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal skipped - mod present %s", modId);
continue;
}
if (logDebugInfo) FMLRelaunchLog.finer("Optional on %s triggered - mod missing %s", name, modId);
if (optional.getAnnotationInfo().containsKey("iface"))
{
Boolean stripRefs = (Boolean)optional.getAnnotationInfo().get("striprefs");
if (stripRefs == null) stripRefs = Boolean.FALSE;
stripInterface(classNode,(String)optional.getAnnotationInfo().get("iface"), stripRefs);
}
else
{
stripMethod(classNode, (String)optional.getObjectName());
}
}
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - class %s processed", name);
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private void stripMethod(ClassNode classNode, String methodDescriptor)
{
if(classNode.name.endsWith("$class"))
{
String subName = classNode.name.substring(0, classNode.name.length() - 6);
int pos = methodDescriptor.indexOf('(') + 1;
methodDescriptor = methodDescriptor.substring(0, pos) + 'L' + subName + ';' + methodDescriptor.substring(pos);
}
for (ListIterator<MethodNode> iterator = classNode.methods.listIterator(); iterator.hasNext();)
{
MethodNode method = iterator.next();
if (methodDescriptor.equals(method.name+method.desc))
{
iterator.remove();
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - method %s removed", methodDescriptor);
return;
}
}
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - method %s NOT removed - not found", methodDescriptor);
}
private void stripInterface(ClassNode classNode, String interfaceName, boolean stripRefs)
{
String ifaceName = interfaceName.replace('.', '/');
boolean found = classNode.interfaces.remove(ifaceName);
if (found && logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s removed", interfaceName);
if (!found && logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s NOT removed - not found", interfaceName);
if (found && stripRefs)
{
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s - stripping method signature references", interfaceName);
for (Iterator<MethodNode> iterator = classNode.methods.iterator(); iterator.hasNext();)
{
MethodNode node = iterator.next();
if (node.desc.contains(ifaceName))
{
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s - stripping method containing reference %s", interfaceName, node.name);
iterator.remove();
}
}
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s - all method signature references stripped", interfaceName);
}
else if (found)
{
if (logDebugInfo) FMLRelaunchLog.finer("Optional removal - interface %s - NOT stripping method signature references", interfaceName);
}
}
public void initTable(ASMDataTable dataTable)
{
optionals = ArrayListMultimap.create();
Set<ASMData> interfaceLists = dataTable.getAll("net.minecraftforge.fml.common.Optional$InterfaceList");
addData(unpackInterfaces(interfaceLists));
Set<ASMData> interfaces = dataTable.getAll("net.minecraftforge.fml.common.Optional$Interface");
addData(interfaces);
Set<ASMData> methods = dataTable.getAll("net.minecraftforge.fml.common.Optional$Method");
addData(methods);
}
private Set<ASMData> unpackInterfaces(Set<ASMData> packedInterfaces)
{
Set<ASMData> result = Sets.newHashSet();
for (ASMData data : packedInterfaces)
{
@SuppressWarnings("unchecked")
List<Map<String,Object>> packedList = (List<Map<String,Object>>) data.getAnnotationInfo().get("value");
for (Map<String,Object> packed : packedList)
{
ASMData newData = data.copy(packed);
result.add(newData);
}
}
return result;
}
private void addData(Set<ASMData> interfaces)
{
for (ASMData data : interfaces)
{
optionals.put(data.getClassName(),data);
}
}
}
@@ -0,0 +1,74 @@
package net.minecraftforge.fml.common.asm.transformers;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
public class ModAccessTransformer extends AccessTransformer {
private static Map<String, String> embedded = Maps.newHashMap(); //Needs to be primitive so that both classloaders get the same class.
@SuppressWarnings("unchecked")
public ModAccessTransformer() throws Exception
{
super(ModAccessTransformer.class);
//We are in the new ClassLoader here, so we need to get the static field from the other ClassLoader.
ClassLoader classLoader = this.getClass().getClassLoader().getClass().getClassLoader(); //Bit odd but it gets the class loader that loaded our current class loader yay java!
Class<?> otherClazz = Class.forName(this.getClass().getName(), true, classLoader);
Field otherField = otherClazz.getDeclaredField("embedded");
otherField.setAccessible(true);
embedded = (Map<String, String>)otherField.get(null);
for (Map.Entry<String, String> e : embedded.entrySet())
{
int old_count = getModifiers().size();
processATFile(CharSource.wrap(e.getValue()));
int added = getModifiers().size() - old_count;
if (added > 0)
{
FMLRelaunchLog.fine("Loaded %d rules from AccessTransformer mod jar file %s\n", added, e.getKey());
}
}
}
public static void addJar(JarFile jar) throws IOException
{
Manifest manifest = jar.getManifest();
String atList = manifest.getMainAttributes().getValue("FMLAT");
if (atList == null) return;
for (String at : atList.split(" "))
{
JarEntry jarEntry = jar.getJarEntry("META-INF/"+at);
if (jarEntry != null)
{
embedded.put(String.format("%s!META-INF/%s", jar.getName(), at),
new JarByteSource(jar,jarEntry).asCharSource(Charsets.UTF_8).read());
}
}
}
private static class JarByteSource extends ByteSource
{
private JarFile jar;
private JarEntry entry;
public JarByteSource(JarFile jar, JarEntry entry)
{
this.jar = jar;
this.entry = entry;
}
@Override
public InputStream openStream() throws IOException
{
return jar.getInputStream(entry);
}
}
}
@@ -0,0 +1,13 @@
package net.minecraftforge.fml.common.asm.transformers;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.patcher.ClassPatchManager;
public class PatchingTransformer implements IClassTransformer {
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
return ClassPatchManager.INSTANCE.applyPatch(name, transformedName, bytes);
}
}
@@ -0,0 +1,116 @@
/*
* 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.common.asm.transformers;
import java.util.Iterator;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.SideOnly;
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.FieldNode;
import org.objectweb.asm.tree.MethodNode;
public class SideTransformer implements IClassTransformer
{
private static String SIDE = FMLLaunchHandler.side().name();
private static final boolean DEBUG = false;
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
if (remove((List<AnnotationNode>)classNode.visibleAnnotations, SIDE))
{
if (DEBUG)
{
System.out.println(String.format("Attempted to load class %s for invalid side %s", classNode.name, SIDE));
}
throw new RuntimeException(String.format("Attempted to load class %s for invalid side %s", classNode.name, SIDE));
}
Iterator<FieldNode> fields = classNode.fields.iterator();
while(fields.hasNext())
{
FieldNode field = fields.next();
if (remove((List<AnnotationNode>)field.visibleAnnotations, SIDE))
{
if (DEBUG)
{
System.out.println(String.format("Removing Field: %s.%s", classNode.name, field.name));
}
fields.remove();
}
}
Iterator<MethodNode> methods = classNode.methods.iterator();
while(methods.hasNext())
{
MethodNode method = methods.next();
if (remove((List<AnnotationNode>)method.visibleAnnotations, SIDE))
{
if (DEBUG)
{
System.out.println(String.format("Removing Method: %s.%s%s", classNode.name, method.name, method.desc));
}
methods.remove();
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private boolean remove(List<AnnotationNode> anns, String side)
{
if (anns == null)
{
return false;
}
for (AnnotationNode ann : anns)
{
if (ann.desc.equals(Type.getDescriptor(SideOnly.class)))
{
if (ann.values != null)
{
for (int x = 0; x < ann.values.size() - 1; x += 2)
{
Object key = ann.values.get(x);
Object value = ann.values.get(x+1);
if (key instanceof String && key.equals("value"))
{
if (value instanceof String[] )
{
if (!((String[])value)[1].equals(side))
{
return true;
}
}
}
}
}
}
}
return false;
}
}
@@ -0,0 +1,146 @@
package net.minecraftforge.fml.common.asm.transformers;
import org.objectweb.asm.*;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import net.minecraftforge.fml.relauncher.FMLSecurityManager.ExitTrappedException;
public class TerminalTransformer implements IClassTransformer
{
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass)
{
if (basicClass == null) return null;
ClassReader reader = new ClassReader(basicClass);
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor visitor = writer;
visitor = new ExitVisitor(visitor);
reader.accept(visitor, 0);
return writer.toByteArray();
}
public static class ExitVisitor extends ClassVisitor
{
private String clsName = null;
private static final String callbackOwner = org.objectweb.asm.Type.getInternalName(ExitVisitor.class);
private ExitVisitor(ClassVisitor cv)
{
super(Opcodes.ASM5, cv);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
{
super.visit(version, access, name, signature, superName, interfaces);
this.clsName = name;
}
@Override
public MethodVisitor visitMethod(int mAccess, final String mName, final String mDesc, String mSignature, String[] mExceptions)
{
final boolean warn = !(clsName.equals("net/minecraft/client/Minecraft") ||
clsName.equals("net/minecraft/server/dedicated/DedicatedServer") ||
clsName.equals("net/minecraft/server/dedicated/ServerHangWatchdog") ||
clsName.equals("net/minecraft/server/dedicated/ServerHangWatchdog$1") ||
clsName.equals("net/minecraftforge/fml/common/FMLCommonHandler") ||
clsName.startsWith("com/jcraft/jogg/") ||
clsName.startsWith("scala/sys/") ||
clsName.startsWith("net/minecraft/server/gui/MinecraftServerGui")
);
return new MethodVisitor(Opcodes.ASM5, super.visitMethod(mAccess, mName, mDesc, mSignature, mExceptions))
{
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean isIntf)
{
if (opcode == Opcodes.INVOKESTATIC && owner.equals("java/lang/System") && name.equals("exit") && desc.equals("(I)V"))
{
if (warn)
{
FMLRelaunchLog.warning("=============================================================");
FMLRelaunchLog.warning("MOD HAS DIRECT REFERENCE System.exit() THIS IS NOT ALLOWED REROUTING TO FML!");
FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc);
FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead");
FMLRelaunchLog.warning("=============================================================");
}
owner = ExitVisitor.callbackOwner;
name = "systemExitCalled";
}
else if (opcode == Opcodes.INVOKEVIRTUAL && owner.equals("java/lang/Runtime") && name.equals("exit") && desc.equals("(I)V"))
{
if (warn)
{
FMLRelaunchLog.warning("=============================================================");
FMLRelaunchLog.warning("MOD HAS DIRECT REFERENCE Runtime.exit() THIS IS NOT ALLOWED REROUTING TO FML!");
FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc);
FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead");
FMLRelaunchLog.warning("=============================================================");
}
opcode = Opcodes.INVOKESTATIC;
owner = ExitVisitor.callbackOwner;
name = "runtimeExitCalled";
desc = "(Ljava/lang/Runtime;I)V";
}
else if (opcode == Opcodes.INVOKEVIRTUAL && owner.equals("java/lang/Runtime") && name.equals("halt") && desc.equals("(I)V"))
{
if (warn)
{
FMLRelaunchLog.warning("=============================================================");
FMLRelaunchLog.warning("MOD HAS DIRECT REFERENCE Runtime.halt() THIS IS NOT ALLOWED REROUTING TO FML!");
FMLRelaunchLog.warning("Offendor: %s.%s%s", ExitVisitor.this.clsName, mName, mDesc);
FMLRelaunchLog.warning("Use FMLCommonHandler.exitJava instead");
FMLRelaunchLog.warning("=============================================================");
}
opcode = Opcodes.INVOKESTATIC;
owner = ExitVisitor.callbackOwner;
name = "runtimeHaltCalled";
desc = "(Ljava/lang/Runtime;I)V";
}
super.visitMethodInsn(opcode, owner, name, desc, isIntf);
}
};
}
// Intercept System.exit, and check if the caller is allowed to use it, if not wrap it in a ExitTrappedException
public static void systemExitCalled(int status)
{
ExitVisitor.checkAccess();
System.exit(status);
}
// Intercept Runtime.getRuntime().exit, and check if the caller is allowed to use it, if not wrap it in a ExitTrappedException
public static void runtimeExitCalled(Runtime runtime, int status)
{
ExitVisitor.checkAccess();
runtime.exit(status);
}
// Intercept Runtime.getRuntime().halt, and check if the caller is allowed to use it, if not wrap it in a ExitTrappedException
public static void runtimeHaltCalled(Runtime runtime, int status)
{
ExitVisitor.checkAccess();
runtime.halt(status);
}
private static void checkAccess()
{
StackTraceElement[] cause = Thread.currentThread().getStackTrace();
String callingClass = cause.length > 2 ? cause[3].getClassName() : "none";
String callingParent = cause.length > 3 ? cause[4].getClassName() : "none";
// FML is allowed to call system exit and the Minecraft applet (from the quit button), and the dedicated server (from itself)
if (!(callingClass.startsWith("net.minecraftforge.fml.") ||
("net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) ||
("net.minecraft.server.gui.MinecraftServerGui$1".equals(callingClass) && "java.awt.AWTEventMulticaster".equals(callingParent)) ||
("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent)))
)
{
throw new ExitTrappedException();
}
}
}
}
@@ -0,0 +1,437 @@
/*
* 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.common.asm.transformers.deobf;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.patcher.ClassPatchManager;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import org.apache.logging.log4j.Level;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableBiMap.Builder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
public class FMLDeobfuscatingRemapper extends Remapper {
public static final FMLDeobfuscatingRemapper INSTANCE = new FMLDeobfuscatingRemapper();
private BiMap<String, String> classNameBiMap;
private Map<String,Map<String,String>> rawFieldMaps;
private Map<String,Map<String,String>> rawMethodMaps;
private Map<String,Map<String,String>> fieldNameMaps;
private Map<String,Map<String,String>> methodNameMaps;
private LaunchClassLoader classLoader;
private static final boolean DEBUG_REMAPPING = Boolean.parseBoolean(System.getProperty("fml.remappingDebug", "false"));
private static final boolean DUMP_FIELD_MAPS = Boolean.parseBoolean(System.getProperty("fml.remappingDebug.dumpFieldMaps", "false")) && DEBUG_REMAPPING;
private static final boolean DUMP_METHOD_MAPS = Boolean.parseBoolean(System.getProperty("fml.remappingDebug.dumpMethodMaps", "false")) && DEBUG_REMAPPING;
private FMLDeobfuscatingRemapper()
{
classNameBiMap=ImmutableBiMap.of();
}
public void setupLoadOnly(String deobfFileName, boolean loadAll)
{
try
{
File mapData = new File(deobfFileName);
LZMAInputSupplier zis = new LZMAInputSupplier(new FileInputStream(mapData));
CharSource srgSource = zis.asCharSource(Charsets.UTF_8);
List<String> srgList = srgSource.readLines();
rawMethodMaps = Maps.newHashMap();
rawFieldMaps = Maps.newHashMap();
Builder<String, String> builder = ImmutableBiMap.<String,String>builder();
Splitter splitter = Splitter.on(CharMatcher.anyOf(": ")).omitEmptyStrings().trimResults();
for (String line : srgList)
{
String[] parts = Iterables.toArray(splitter.split(line),String.class);
String typ = parts[0];
if ("CL".equals(typ))
{
parseClass(builder, parts);
}
else if ("MD".equals(typ) && loadAll)
{
parseMethod(parts);
}
else if ("FD".equals(typ) && loadAll)
{
parseField(parts);
}
}
classNameBiMap = builder.build();
}
catch (IOException ioe)
{
FMLRelaunchLog.log(Level.ERROR, "An error occurred loading the deobfuscation map data", ioe);
}
methodNameMaps = Maps.newHashMapWithExpectedSize(rawMethodMaps.size());
fieldNameMaps = Maps.newHashMapWithExpectedSize(rawFieldMaps.size());
}
public void setup(File mcDir, LaunchClassLoader classLoader, String deobfFileName)
{
this.classLoader = classLoader;
try
{
List<String> srgList;
final String gradleStartProp = System.getProperty("net.minecraftforge.gradle.GradleStart.srg.srg-mcp");
if (Strings.isNullOrEmpty(gradleStartProp))
{
// get as a resource
InputStream classData = getClass().getResourceAsStream(deobfFileName);
LZMAInputSupplier zis = new LZMAInputSupplier(classData);
CharSource srgSource = zis.asCharSource(Charsets.UTF_8);
srgList = srgSource.readLines();
}
else
{
srgList = Files.readLines(new File(gradleStartProp), Charsets.UTF_8);
}
rawMethodMaps = Maps.newHashMap();
rawFieldMaps = Maps.newHashMap();
Builder<String, String> builder = ImmutableBiMap.<String,String>builder();
Splitter splitter = Splitter.on(CharMatcher.anyOf(": ")).omitEmptyStrings().trimResults();
for (String line : srgList)
{
String[] parts = Iterables.toArray(splitter.split(line),String.class);
String typ = parts[0];
if ("CL".equals(typ))
{
parseClass(builder, parts);
}
else if ("MD".equals(typ))
{
parseMethod(parts);
}
else if ("FD".equals(typ))
{
parseField(parts);
}
}
classNameBiMap = builder.build();
}
catch (IOException ioe)
{
FMLRelaunchLog.log(Level.ERROR, ioe, "An error occurred loading the deobfuscation map data");
}
methodNameMaps = Maps.newHashMapWithExpectedSize(rawMethodMaps.size());
fieldNameMaps = Maps.newHashMapWithExpectedSize(rawFieldMaps.size());
}
public boolean isRemappedClass(String className)
{
return !map(className).equals(className);
}
private void parseField(String[] parts)
{
String oldSrg = parts[1];
int lastOld = oldSrg.lastIndexOf('/');
String cl = oldSrg.substring(0,lastOld);
String oldName = oldSrg.substring(lastOld+1);
String newSrg = parts[2];
int lastNew = newSrg.lastIndexOf('/');
String newName = newSrg.substring(lastNew+1);
if (!rawFieldMaps.containsKey(cl))
{
rawFieldMaps.put(cl, Maps.<String,String>newHashMap());
}
rawFieldMaps.get(cl).put(oldName + ":" + getFieldType(cl, oldName), newName);
rawFieldMaps.get(cl).put(oldName + ":null", newName);
}
/*
* Cache the field descriptions for classes so we don't repeatedly reload the same data again and again
*/
private Map<String,Map<String,String>> fieldDescriptions = Maps.newHashMap();
// Cache null values so we don't waste time trying to recompute classes with no field or method maps
private Set<String> negativeCacheMethods = Sets.newHashSet();
private Set<String> negativeCacheFields = Sets.newHashSet();
private String getFieldType(String owner, String name)
{
if (fieldDescriptions.containsKey(owner))
{
return fieldDescriptions.get(owner).get(name);
}
synchronized (fieldDescriptions)
{
try
{
byte[] classBytes = ClassPatchManager.INSTANCE.getPatchedResource(owner, map(owner).replace('/', '.'), classLoader);
if (classBytes == null)
{
return null;
}
ClassReader cr = new ClassReader(classBytes);
ClassNode classNode = new ClassNode();
cr.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
Map<String,String> resMap = Maps.newHashMap();
for (FieldNode fieldNode : (List<FieldNode>) classNode.fields) {
resMap.put(fieldNode.name, fieldNode.desc);
}
fieldDescriptions.put(owner, resMap);
return resMap.get(name);
}
catch (IOException e)
{
FMLRelaunchLog.log(Level.ERROR,e, "A critical exception occured reading a class file %s", owner);
}
return null;
}
}
private void parseClass(Builder<String, String> builder, String[] parts)
{
builder.put(parts[1],parts[2]);
}
private void parseMethod(String[] parts)
{
String oldSrg = parts[1];
int lastOld = oldSrg.lastIndexOf('/');
String cl = oldSrg.substring(0,lastOld);
String oldName = oldSrg.substring(lastOld+1);
String sig = parts[2];
String newSrg = parts[3];
int lastNew = newSrg.lastIndexOf('/');
String newName = newSrg.substring(lastNew+1);
if (!rawMethodMaps.containsKey(cl))
{
rawMethodMaps.put(cl, Maps.<String,String>newHashMap());
}
rawMethodMaps.get(cl).put(oldName+sig, newName);
}
@Override
public String mapFieldName(String owner, String name, String desc)
{
if (classNameBiMap == null || classNameBiMap.isEmpty())
{
return name;
}
Map<String, String> fieldMap = getFieldMap(owner);
return fieldMap!=null && fieldMap.containsKey(name+":"+desc) ? fieldMap.get(name+":"+desc) : name;
}
@Override
public String map(String typeName)
{
if (classNameBiMap == null || classNameBiMap.isEmpty())
{
return typeName;
}
if (classNameBiMap.containsKey(typeName))
{
return classNameBiMap.get(typeName);
}
int dollarIdx = typeName.lastIndexOf('$');
if (dollarIdx > -1)
{
return map(typeName.substring(0, dollarIdx)) + "$" + typeName.substring(dollarIdx + 1);
}
return typeName;
}
public String unmap(String typeName)
{
if (classNameBiMap == null || classNameBiMap.isEmpty())
{
return typeName;
}
if (classNameBiMap.containsValue(typeName))
{
return classNameBiMap.inverse().get(typeName);
}
int dollarIdx = typeName.lastIndexOf('$');
if (dollarIdx > -1)
{
return unmap(typeName.substring(0, dollarIdx)) + "$" + typeName.substring(dollarIdx + 1);
}
return typeName;
}
@Override
public String mapMethodName(String owner, String name, String desc)
{
if (classNameBiMap==null || classNameBiMap.isEmpty())
{
return name;
}
Map<String, String> methodMap = getMethodMap(owner);
String methodDescriptor = name+desc;
return methodMap!=null && methodMap.containsKey(methodDescriptor) ? methodMap.get(methodDescriptor) : name;
}
private Map<String,String> getFieldMap(String className)
{
if (!fieldNameMaps.containsKey(className) && !negativeCacheFields.contains(className))
{
findAndMergeSuperMaps(className);
if (!fieldNameMaps.containsKey(className))
{
negativeCacheFields.add(className);
}
if (DUMP_FIELD_MAPS)
{
FMLRelaunchLog.finer("Field map for %s : %s", className, fieldNameMaps.get(className));
}
}
return fieldNameMaps.get(className);
}
private Map<String,String> getMethodMap(String className)
{
if (!methodNameMaps.containsKey(className) && !negativeCacheMethods.contains(className))
{
findAndMergeSuperMaps(className);
if (!methodNameMaps.containsKey(className))
{
negativeCacheMethods.add(className);
}
if (DUMP_METHOD_MAPS)
{
FMLRelaunchLog.finer("Method map for %s : %s", className, methodNameMaps.get(className));
}
}
return methodNameMaps.get(className);
}
private void findAndMergeSuperMaps(String name)
{
try
{
String superName = null;
String[] interfaces = new String[0];
byte[] classBytes = ClassPatchManager.INSTANCE.getPatchedResource(name, map(name), classLoader);
if (classBytes != null)
{
ClassReader cr = new ClassReader(classBytes);
superName = cr.getSuperName();
interfaces = cr.getInterfaces();
}
mergeSuperMaps(name, superName, interfaces);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void mergeSuperMaps(String name, String superName, String[] interfaces)
{
// System.out.printf("Computing super maps for %s: %s %s\n", name, superName, Arrays.asList(interfaces));
if (classNameBiMap == null || classNameBiMap.isEmpty())
{
return;
}
// Skip Object
if (Strings.isNullOrEmpty(superName))
{
return;
}
List<String> allParents = ImmutableList.<String>builder().add(superName).addAll(Arrays.asList(interfaces)).build();
// generate maps for all parent objects
for (String parentThing : allParents)
{
if (!methodNameMaps.containsKey(parentThing))
{
findAndMergeSuperMaps(parentThing);
}
}
Map<String, String> methodMap = Maps.<String,String>newHashMap();
Map<String, String> fieldMap = Maps.<String,String>newHashMap();
for (String parentThing : allParents)
{
if (methodNameMaps.containsKey(parentThing))
{
methodMap.putAll(methodNameMaps.get(parentThing));
}
if (fieldNameMaps.containsKey(parentThing))
{
fieldMap.putAll(fieldNameMaps.get(parentThing));
}
}
if (rawMethodMaps.containsKey(name))
{
methodMap.putAll(rawMethodMaps.get(name));
}
if (rawFieldMaps.containsKey(name))
{
fieldMap.putAll(rawFieldMaps.get(name));
}
methodNameMaps.put(name, ImmutableMap.copyOf(methodMap));
fieldNameMaps.put(name, ImmutableMap.copyOf(fieldMap));
// System.out.printf("Maps: %s %s\n", name, methodMap);
}
public Set<String> getObfedClasses()
{
return ImmutableSet.copyOf(classNameBiMap.keySet());
}
public String getStaticFieldType(String oldType, String oldName, String newType, String newName)
{
String fType = getFieldType(oldType, oldName);
if (oldType.equals(newType))
{
return fType;
}
Map<String,String> newClassMap = fieldDescriptions.get(newType);
if (newClassMap == null)
{
newClassMap = Maps.newHashMap();
fieldDescriptions.put(newType, newClassMap);
}
newClassMap.put(newName, fType);
return fType;
}
}
@@ -0,0 +1,75 @@
/*
* 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.common.asm.transformers.deobf;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.Remapper;
import org.objectweb.asm.commons.RemappingClassAdapter;
import org.objectweb.asm.commons.RemappingMethodAdapter;
public class FMLRemappingAdapter extends RemappingClassAdapter {
public FMLRemappingAdapter(ClassVisitor cv)
{
super(cv, FMLDeobfuscatingRemapper.INSTANCE);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
{
if (interfaces == null)
{
interfaces = new String[0];
}
FMLDeobfuscatingRemapper.INSTANCE.mergeSuperMaps(name, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
protected MethodVisitor createRemappingMethodAdapter(int access, String newDesc, MethodVisitor mv)
{
return new StaticFixingMethodVisitor(access, newDesc, mv, remapper);
}
private static class StaticFixingMethodVisitor extends RemappingMethodAdapter
{
public StaticFixingMethodVisitor(int access, String desc, MethodVisitor mv, Remapper remapper)
{
super(access, desc, mv, remapper);
}
@Override
public void visitFieldInsn(int opcode, String originalType, String originalName, String desc)
{
// This method solves the problem of a static field reference changing type. In all probability it is a
// compatible change, however we need to fix up the desc to point at the new type
String type = remapper.mapType(originalType);
String fieldName = remapper.mapFieldName(originalType, originalName, desc);
String newDesc = remapper.mapDesc(desc);
if (opcode == Opcodes.GETSTATIC && type.startsWith("net/minecraft/") && newDesc.startsWith("Lnet/minecraft/"))
{
String replDesc = FMLDeobfuscatingRemapper.INSTANCE.getStaticFieldType(originalType, originalName, type, fieldName);
if (replDesc != null)
{
newDesc = remapper.mapDesc(replDesc);
}
}
// super.super
if (mv != null) {
mv.visitFieldInsn(opcode, type, fieldName, newDesc);
}
}
}
}
@@ -0,0 +1,36 @@
/*
* 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.common.asm.transformers.deobf;
import java.io.IOException;
import java.io.InputStream;
import LZMA.LzmaInputStream;
import com.google.common.io.ByteSource;
public class LZMAInputSupplier extends ByteSource {
private InputStream compressedData;
public LZMAInputSupplier(InputStream compressedData)
{
this.compressedData = compressedData;
}
@Override
public InputStream openStream() throws IOException
{
return new LzmaInputStream(this.compressedData);
}
}
@@ -0,0 +1,141 @@
/*
* 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.common.discovery;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.ModContainer;
import com.google.common.base.Predicate;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
public class ASMDataTable
{
public final static class ASMData implements Cloneable
{
private ModCandidate candidate;
private String annotationName;
private String className;
private String objectName;
private Map<String,Object> annotationInfo;
public ASMData(ModCandidate candidate, String annotationName, String className, String objectName, Map<String,Object> info)
{
this.candidate = candidate;
this.annotationName = annotationName;
this.className = className;
this.objectName = objectName;
this.annotationInfo = info;
}
public ModCandidate getCandidate()
{
return candidate;
}
public String getAnnotationName()
{
return annotationName;
}
public String getClassName()
{
return className;
}
public String getObjectName()
{
return objectName;
}
public Map<String, Object> getAnnotationInfo()
{
return annotationInfo;
}
public ASMData copy(Map<String,Object> newAnnotationInfo)
{
try
{
ASMData clone = (ASMData) this.clone();
clone.annotationInfo = newAnnotationInfo;
return clone;
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException("Unpossible", e);
}
}
}
private static class ModContainerPredicate implements Predicate<ASMData>
{
private ModContainer container;
public ModContainerPredicate(ModContainer container)
{
this.container = container;
}
@Override
public boolean apply(ASMData data)
{
return container.getSource().equals(data.candidate.getModContainer());
}
}
private SetMultimap<String, ASMData> globalAnnotationData = HashMultimap.create();
private Map<ModContainer, SetMultimap<String,ASMData>> containerAnnotationData;
private List<ModContainer> containers = Lists.newArrayList();
private SetMultimap<String,ModCandidate> packageMap = HashMultimap.create();
public SetMultimap<String,ASMData> getAnnotationsFor(ModContainer container)
{
if (containerAnnotationData == null)
{
ImmutableMap.Builder<ModContainer, SetMultimap<String, ASMData>> mapBuilder = ImmutableMap.<ModContainer, SetMultimap<String,ASMData>>builder();
for (ModContainer cont : containers)
{
Multimap<String, ASMData> values = Multimaps.filterValues(globalAnnotationData, new ModContainerPredicate(cont));
mapBuilder.put(cont, ImmutableSetMultimap.copyOf(values));
}
containerAnnotationData = mapBuilder.build();
}
return containerAnnotationData.get(container);
}
public Set<ASMData> getAll(String annotation)
{
return globalAnnotationData.get(annotation);
}
public void addASMData(ModCandidate candidate, String annotation, String className, String objectName, Map<String,Object> annotationInfo)
{
globalAnnotationData.put(annotation, new ASMData(candidate, annotation, className, objectName, annotationInfo));
}
public void addContainer(ModContainer container)
{
this.containers.add(container);
}
public void registerPackage(ModCandidate modCandidate, String pkg)
{
this.packageMap.put(pkg,modCandidate);
}
public Set<ModCandidate> getCandidatesFor(String pkg)
{
return this.packageMap.get(pkg);
}
}
@@ -0,0 +1,44 @@
/*
* 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.common.discovery;
import java.util.List;
import net.minecraftforge.fml.common.ModContainer;
import com.google.common.base.Throwables;
public enum ContainerType
{
JAR(JarDiscoverer.class),
DIR(DirectoryDiscoverer.class);
private ITypeDiscoverer discoverer;
private ContainerType(Class<? extends ITypeDiscoverer> discovererClass)
{
try
{
this.discoverer = discovererClass.newInstance();
}
catch (Exception e)
{
throw Throwables.propagate(e);
}
}
public List<ModContainer> findMods(ModCandidate candidate, ASMDataTable table)
{
return discoverer.discover(candidate, table);
}
}
@@ -0,0 +1,128 @@
/*
* 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.common.discovery;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.common.MetadataCollection;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ModContainerFactory;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import org.apache.logging.log4j.Level;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
public class DirectoryDiscoverer implements ITypeDiscoverer
{
private class ClassFilter implements FileFilter
{
@Override
public boolean accept(File file)
{
return (file.isFile() && classFile.matcher(file.getName()).matches()) || file.isDirectory();
}
}
private ASMDataTable table;
@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table)
{
this.table = table;
List<ModContainer> found = Lists.newArrayList();
FMLLog.fine("Examining directory %s for potential mods", candidate.getModContainer().getName());
exploreFileSystem("", candidate.getModContainer(), found, candidate, null);
for (ModContainer mc : found)
{
table.addContainer(mc);
}
return found;
}
public void exploreFileSystem(String path, File modDir, List<ModContainer> harvestedMods, ModCandidate candidate, MetadataCollection mc)
{
if (path.length() == 0)
{
File metadata = new File(modDir, "mcmod.info");
try
{
FileInputStream fis = new FileInputStream(metadata);
mc = MetadataCollection.from(fis,modDir.getName());
fis.close();
FMLLog.fine("Found an mcmod.info file in directory %s", modDir.getName());
}
catch (Exception e)
{
mc = MetadataCollection.from(null,"");
FMLLog.fine("No mcmod.info file found in directory %s", modDir.getName());
}
}
File[] content = modDir.listFiles(new ClassFilter());
// Always sort our content
Arrays.sort(content);
for (File file : content)
{
if (file.isDirectory())
{
FMLLog.finer("Recursing into package %s", path + file.getName());
exploreFileSystem(path + file.getName() + ".", file, harvestedMods, candidate, mc);
continue;
}
Matcher match = classFile.matcher(file.getName());
if (match.matches())
{
ASMModParser modParser = null;
try
{
FileInputStream fis = new FileInputStream(file);
modParser = new ASMModParser(fis);
fis.close();
candidate.addClassEntry(path+file.getName());
}
catch (LoaderException e)
{
FMLLog.log(Level.ERROR, e, "There was a problem reading the file %s - probably this is a corrupt file", file.getPath());
throw e;
}
catch (Exception e)
{
Throwables.propagate(e);
}
modParser.validate();
modParser.sendToTable(table, candidate);
ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate);
if (container!=null)
{
harvestedMods.add(container);
container.bindMetadata(mc);
}
}
}
}
}
@@ -0,0 +1,26 @@
/*
* 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.common.discovery;
import java.util.List;
import java.util.regex.Pattern;
import net.minecraftforge.fml.common.ModContainer;
public interface ITypeDiscoverer
{
// main class part, followed by an optional $ and an "inner class" part. $ cannot be last, otherwise scala breaks
public static Pattern classFile = Pattern.compile("[^\\s\\$]+(\\$[^\\s]+)?\\.class$");
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table);
}
@@ -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.common.discovery;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarFile;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.common.MetadataCollection;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ModContainerFactory;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import org.apache.logging.log4j.Level;
import java.util.regex.Matcher;
import java.util.zip.ZipEntry;
import com.google.common.collect.Lists;
public class JarDiscoverer implements ITypeDiscoverer
{
@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table)
{
List<ModContainer> foundMods = Lists.newArrayList();
FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName());
JarFile jar = null;
try
{
jar = new JarFile(candidate.getModContainer());
if (jar.getManifest()!=null && (jar.getManifest().getMainAttributes().get("FMLCorePlugin") != null || jar.getManifest().getMainAttributes().get("TweakClass") != null))
{
FMLLog.finer("Ignoring coremod or tweak system %s", candidate.getModContainer());
return foundMods;
}
ZipEntry modInfo = jar.getEntry("mcmod.info");
MetadataCollection mc = null;
if (modInfo != null)
{
FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName());
mc = MetadataCollection.from(jar.getInputStream(modInfo), candidate.getModContainer().getName());
}
else
{
FMLLog.fine("The mod container %s appears to be missing an mcmod.info file", candidate.getModContainer().getName());
mc = MetadataCollection.from(null, "");
}
for (ZipEntry ze : Collections.list(jar.entries()))
{
if (ze.getName()!=null && ze.getName().startsWith("__MACOSX"))
{
continue;
}
Matcher match = classFile.matcher(ze.getName());
if (match.matches())
{
ASMModParser modParser;
try
{
modParser = new ASMModParser(jar.getInputStream(ze));
candidate.addClassEntry(ze.getName());
}
catch (LoaderException e)
{
FMLLog.log(Level.ERROR, e, "There was a problem reading the entry %s in the jar %s - probably a corrupt zip", ze.getName(), candidate.getModContainer().getPath());
jar.close();
throw e;
}
modParser.validate();
modParser.sendToTable(table, candidate);
ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate);
if (container!=null)
{
table.addContainer(container);
foundMods.add(container);
container.bindMetadata(mc);
}
}
}
}
catch (Exception e)
{
FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored", candidate.getModContainer().getName());
}
finally
{
if (jar != null)
{
try
{
jar.close();
}
catch (Exception e)
{
}
}
}
return foundMods;
}
}
@@ -0,0 +1,126 @@
/*
* 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.common.discovery;
import java.io.File;
import java.util.List;
import java.util.Set;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class ModCandidate
{
private File classPathRoot;
private File modContainer;
private ContainerType sourceType;
private boolean classpath;
private List<String> baseModTypes = Lists.newArrayList();
private boolean isMinecraft;
private List<ASMModParser> baseModCandidateTypes = Lists.newArrayListWithCapacity(1);
private Set<String> foundClasses = Sets.newHashSet();
private List<ModContainer> mods;
private List<String> packages = Lists.newArrayList();
private ASMDataTable table;
public ModCandidate(File classPathRoot, File modContainer, ContainerType sourceType)
{
this(classPathRoot, modContainer, sourceType, false, false);
}
public ModCandidate(File classPathRoot, File modContainer, ContainerType sourceType, boolean isMinecraft, boolean classpath)
{
this.classPathRoot = classPathRoot;
this.modContainer = modContainer;
this.sourceType = sourceType;
this.isMinecraft = isMinecraft;
this.classpath = classpath;
}
public File getClassPathRoot()
{
return classPathRoot;
}
public File getModContainer()
{
return modContainer;
}
public ContainerType getSourceType()
{
return sourceType;
}
public List<ModContainer> explore(ASMDataTable table)
{
this.table = table;
this.mods = sourceType.findMods(this, table);
if (!baseModCandidateTypes.isEmpty())
{
FMLLog.info("Attempting to reparse the mod container %s", getModContainer().getName());
this.mods = sourceType.findMods(this, table);
}
return this.mods;
}
public void addClassEntry(String name)
{
String className = name.substring(0, name.lastIndexOf('.')); // strip the .class
foundClasses.add(className);
className = className.replace('/','.');
int pkgIdx = className.lastIndexOf('.');
if (pkgIdx > -1)
{
String pkg = className.substring(0,pkgIdx);
packages.add(pkg);
this.table.registerPackage(this,pkg);
}
}
public boolean isClasspath()
{
return classpath;
}
public void rememberBaseModType(String className)
{
baseModTypes.add(className);
}
public List<String> getRememberedBaseMods()
{
return baseModTypes;
}
public boolean isMinecraftJar()
{
return isMinecraft;
}
public void rememberModCandidateType(ASMModParser modParser)
{
baseModCandidateTypes.add(modParser);
}
public Set<String> getClassList()
{
return foundClasses;
}
public List<ModContainer> getContainedMods()
{
return mods;
}
public List<String> getContainedPackages()
{
return packages;
}
}
@@ -0,0 +1,180 @@
/*
* 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.common.discovery;
import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.common.ModClassLoader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.FileListHelper;
import net.minecraftforge.fml.relauncher.ModListHelper;
import org.apache.logging.log4j.Level;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
public class ModDiscoverer
{
private static Pattern zipJar = Pattern.compile("(.+).(zip|jar)$");
private List<ModCandidate> candidates = Lists.newArrayList();
private ASMDataTable dataTable = new ASMDataTable();
private List<File> nonModLibs = Lists.newArrayList();
public void findClasspathMods(ModClassLoader modClassLoader)
{
List<String> knownLibraries = ImmutableList.<String>builder()
// skip default libs
.addAll(modClassLoader.getDefaultLibraries())
// skip loaded coremods
.addAll(CoreModManager.getLoadedCoremods())
// skip reparse coremods here
.addAll(CoreModManager.getReparseableCoremods())
.build();
File[] minecraftSources = modClassLoader.getParentSources();
if (minecraftSources.length == 1 && minecraftSources[0].isFile())
{
FMLLog.fine("Minecraft is a file at %s, loading", minecraftSources[0].getAbsolutePath());
addCandidate(new ModCandidate(minecraftSources[0], minecraftSources[0], ContainerType.JAR, true, true));
}
else
{
int i = 0;
for (File source : minecraftSources)
{
if (source.isFile())
{
if (knownLibraries.contains(source.getName()) || modClassLoader.isDefaultLibrary(source))
{
FMLLog.finer("Skipping known library file %s", source.getAbsolutePath());
}
else
{
FMLLog.fine("Found a minecraft related file at %s, examining for mod candidates", source.getAbsolutePath());
addCandidate(new ModCandidate(source, source, ContainerType.JAR, i==0, true));
}
}
else if (minecraftSources[i].isDirectory())
{
FMLLog.fine("Found a minecraft related directory at %s, examining for mod candidates", source.getAbsolutePath());
addCandidate(new ModCandidate(source, source, ContainerType.DIR, i==0, true));
}
i++;
}
}
}
public void findModDirMods(File modsDir)
{
findModDirMods(modsDir, new File[0]);
}
public void findModDirMods(File modsDir, File[] supplementalModFileCandidates)
{
File[] modList = FileListHelper.sortFileList(modsDir, null);
modList = FileListHelper.sortFileList(ObjectArrays.concat(modList, supplementalModFileCandidates, File.class));
for (File modFile : modList)
{
// skip loaded coremods
if (CoreModManager.getLoadedCoremods().contains(modFile.getName()))
{
FMLLog.finer("Skipping already parsed coremod or tweaker %s", modFile.getName());
}
else if (modFile.isDirectory())
{
FMLLog.fine("Found a candidate mod directory %s", modFile.getName());
addCandidate(new ModCandidate(modFile, modFile, ContainerType.DIR));
}
else
{
Matcher matcher = zipJar.matcher(modFile.getName());
if (matcher.matches())
{
FMLLog.fine("Found a candidate zip or jar file %s", matcher.group(0));
addCandidate(new ModCandidate(modFile, modFile, ContainerType.JAR));
}
else
{
FMLLog.fine("Ignoring unknown file %s in mods directory", modFile.getName());
}
}
}
}
public List<ModContainer> identifyMods()
{
List<ModContainer> modList = Lists.newArrayList();
for (ModCandidate candidate : candidates)
{
try
{
List<ModContainer> mods = candidate.explore(dataTable);
if (mods.isEmpty() && !candidate.isClasspath())
{
nonModLibs.add(candidate.getModContainer());
}
else
{
modList.addAll(mods);
}
}
catch (LoaderException le)
{
FMLLog.log(Level.WARN, le, "Identified a problem with the mod candidate %s, ignoring this source", candidate.getModContainer());
}
catch (Throwable t)
{
Throwables.propagate(t);
}
}
return modList;
}
public ASMDataTable getASMTable()
{
return dataTable;
}
public List<File> getNonModLibs()
{
return nonModLibs;
}
private void addCandidate(ModCandidate candidate)
{
for (ModCandidate c : candidates)
{
if (c.getModContainer().equals(candidate.getModContainer()))
{
FMLLog.finer(" Skipping already in list %s", candidate.getModContainer());
return;
}
}
candidates.add(candidate);
}
}
@@ -0,0 +1,186 @@
/*
* 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.common.discovery.asm;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import org.apache.logging.log4j.Level;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
public class ASMModParser
{
private Type asmType;
private int classVersion;
private Type asmSuperType;
private LinkedList<ModAnnotation> annotations = Lists.newLinkedList();
private String baseModProperties;
static enum AnnotationType
{
CLASS, FIELD, METHOD, SUBTYPE;
}
public ASMModParser(InputStream stream) throws IOException
{
try
{
ClassReader reader = new ClassReader(stream);
reader.accept(new ModClassVisitor(this), 0);
}
catch (Exception ex)
{
FMLLog.log(Level.ERROR, ex, "Unable to read a class file correctly");
throw new LoaderException(ex);
}
}
public void beginNewTypeName(String typeQName, int classVersion, String superClassQName)
{
this.asmType = Type.getObjectType(typeQName);
this.classVersion = classVersion;
this.asmSuperType = !Strings.isNullOrEmpty(superClassQName) ? Type.getObjectType(superClassQName) : null;
}
public void startClassAnnotation(String annotationName)
{
ModAnnotation ann = new ModAnnotation(AnnotationType.CLASS, Type.getType(annotationName), this.asmType.getClassName());
annotations.addFirst(ann);
}
public void addAnnotationProperty(String key, Object value)
{
annotations.getFirst().addProperty(key, value);
}
public void startFieldAnnotation(String fieldName, String annotationName)
{
ModAnnotation ann = new ModAnnotation(AnnotationType.FIELD, Type.getType(annotationName), fieldName);
annotations.addFirst(ann);
}
@Override
public String toString()
{
return Objects.toStringHelper("ASMAnnotationDiscoverer")
.add("className", asmType.getClassName())
.add("classVersion", classVersion)
.add("superName", asmSuperType.getClassName())
.add("annotations", annotations)
.add("isBaseMod", isBaseMod(Collections.<String>emptyList()))
.add("baseModProperties", baseModProperties)
.toString();
}
public Type getASMType()
{
return asmType;
}
public int getClassVersion()
{
return classVersion;
}
public Type getASMSuperType()
{
return asmSuperType;
}
public LinkedList<ModAnnotation> getAnnotations()
{
return annotations;
}
public void validate()
{
// if (classVersion > 50.0)
// {
//
// throw new LoaderException(new RuntimeException("Mod compiled for Java 7 detected"));
// }
}
public boolean isBaseMod(List<String> rememberedTypes)
{
return getASMSuperType().equals(Type.getType("LBaseMod;")) || getASMSuperType().equals(Type.getType("Lnet/minecraft/src/BaseMod;"))|| rememberedTypes.contains(getASMSuperType().getClassName());
}
public void setBaseModProperties(String foundProperties)
{
this.baseModProperties = foundProperties;
}
public String getBaseModProperties()
{
return this.baseModProperties;
}
public void sendToTable(ASMDataTable table, ModCandidate candidate)
{
for (ModAnnotation ma : annotations)
{
table.addASMData(candidate, ma.asmType.getClassName(), this.asmType.getClassName(), ma.member, ma.values);
}
}
public void addAnnotationArray(String name)
{
annotations.getFirst().addArray(name);
}
public void addAnnotationEnumProperty(String name, String desc, String value)
{
annotations.getFirst().addEnumProperty(name, desc, value);
}
public void endArray()
{
annotations.getFirst().endArray();
}
public void addSubAnnotation(String name, String desc)
{
ModAnnotation ma = annotations.getFirst();
annotations.addFirst(ma.addChildAnnotation(name, desc));
}
public void endSubAnnotation()
{
// take the child and stick it at the end
ModAnnotation child = annotations.removeFirst();
annotations.addLast(child);
}
public void startMethodAnnotation(String methodName, String methodDescriptor, String annotationName)
{
ModAnnotation ann = new ModAnnotation(AnnotationType.METHOD, Type.getType(annotationName), methodName+methodDescriptor);
annotations.addFirst(ann);
}
}
@@ -0,0 +1,120 @@
/*
* 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.common.discovery.asm;
import java.util.ArrayList;
import java.util.Map;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser.AnnotationType;
import org.objectweb.asm.Type;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class ModAnnotation
{
public class EnumHolder
{
private String desc;
private String value;
public EnumHolder(String desc, String value)
{
this.desc = desc;
this.value = value;
}
}
AnnotationType type;
Type asmType;
String member;
Map<String,Object> values = Maps.newHashMap();
private ArrayList<Object> arrayList;
private String arrayName;
public ModAnnotation(AnnotationType type, Type asmType, String member)
{
this.type = type;
this.asmType = asmType;
this.member = member;
}
public ModAnnotation(AnnotationType type, Type asmType, ModAnnotation parent)
{
this.type = type;
this.asmType = asmType;
}
@Override
public String toString()
{
return Objects.toStringHelper("Annotation")
.add("type",type)
.add("name",asmType.getClassName())
.add("member",member)
.add("values", values)
.toString();
}
public AnnotationType getType()
{
return type;
}
public Type getASMType()
{
return asmType;
}
public String getMember()
{
return member;
}
public Map<String, Object> getValues()
{
return values;
}
public void addArray(String name)
{
this.arrayList = Lists.newArrayList();
this.arrayName = name;
}
public void addProperty(String key, Object value)
{
if (this.arrayList != null)
{
arrayList.add(value);
}
else
{
values.put(key, value);
}
}
public void addEnumProperty(String key, String enumName, String value)
{
values.put(key, new EnumHolder(enumName, value));
}
public void endArray()
{
values.put(arrayName, arrayList);
arrayList = null;
}
public ModAnnotation addChildAnnotation(String name, String desc)
{
ModAnnotation child = new ModAnnotation(AnnotationType.SUBTYPE, Type.getType(desc), this);
if (arrayList != null)
{
arrayList.add(child.getValues());
}
return child;
}
}
@@ -0,0 +1,81 @@
/*
* 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.common.discovery.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Opcodes;
public class ModAnnotationVisitor extends AnnotationVisitor
{
private ASMModParser discoverer;
private boolean array;
private String name;
private boolean isSubAnnotation;
public ModAnnotationVisitor(ASMModParser discoverer)
{
super(Opcodes.ASM5);
this.discoverer = discoverer;
}
public ModAnnotationVisitor(ASMModParser discoverer, String name)
{
this(discoverer);
this.array = true;
this.name = name;
discoverer.addAnnotationArray(name);
}
public ModAnnotationVisitor(ASMModParser discoverer, boolean isSubAnnotation)
{
this(discoverer);
this.isSubAnnotation = true;
}
@Override
public void visit(String key, Object value)
{
discoverer.addAnnotationProperty(key, value);
}
@Override
public void visitEnum(String name, String desc, String value)
{
discoverer.addAnnotationEnumProperty(name, desc, value);
}
@Override
public AnnotationVisitor visitArray(String name)
{
return new ModAnnotationVisitor(discoverer, name);
}
@Override
public AnnotationVisitor visitAnnotation(String name, String desc)
{
discoverer.addSubAnnotation(name, desc);
return new ModAnnotationVisitor(discoverer, true);
}
@Override
public void visitEnd()
{
if (array)
{
discoverer.endArray();
}
if (isSubAnnotation)
{
discoverer.endSubAnnotation();
}
}
}
@@ -0,0 +1,57 @@
/*
* 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.common.discovery.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class ModClassVisitor extends ClassVisitor
{
private ASMModParser discoverer;
public ModClassVisitor(ASMModParser discoverer)
{
super(Opcodes.ASM5);
this.discoverer = discoverer;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces)
{
discoverer.beginNewTypeName(name, version, superName);
}
@Override
public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible)
{
discoverer.startClassAnnotation(annotationName);
return new ModAnnotationVisitor(discoverer);
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value)
{
return new ModFieldVisitor(name, discoverer);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions)
{
return new ModMethodVisitor(name, desc, discoverer);
}
}
@@ -0,0 +1,38 @@
/*
* 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.common.discovery.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
public class ModFieldVisitor extends FieldVisitor
{
private String fieldName;
private ASMModParser discoverer;
public ModFieldVisitor(String name, ASMModParser discoverer)
{
super(Opcodes.ASM5);
this.fieldName = name;
this.discoverer = discoverer;
}
@Override
public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible)
{
discoverer.startFieldAnnotation(fieldName, annotationName);
return new ModAnnotationVisitor(discoverer);
}
}
@@ -0,0 +1,28 @@
package net.minecraftforge.fml.common.discovery.asm;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
public class ModMethodVisitor extends MethodVisitor {
private String methodName;
private String methodDescriptor;
private ASMModParser discoverer;
public ModMethodVisitor(String name, String desc, ASMModParser discoverer)
{
super(Opcodes.ASM5);
this.methodName = name;
this.methodDescriptor = desc;
this.discoverer = discoverer;
}
@Override
public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible)
{
discoverer.startMethodAnnotation(methodName, methodDescriptor, annotationName);
return new ModAnnotationVisitor(discoverer);
}
}
@@ -0,0 +1,55 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.ModClassLoader;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import com.google.common.collect.ListMultimap;
public class FMLConstructionEvent extends FMLStateEvent
{
private ModClassLoader modClassLoader;
private ASMDataTable asmData;
private ListMultimap<String,String> reverseDependencies;
@SuppressWarnings("unchecked")
public FMLConstructionEvent(Object... eventData)
{
this.modClassLoader = (ModClassLoader)eventData[0];
this.asmData = (ASMDataTable) eventData[1];
this.reverseDependencies = (ListMultimap<String, String>) eventData[2];
}
public ModClassLoader getModClassLoader()
{
return modClassLoader;
}
@Override
public ModState getModState()
{
return ModState.CONSTRUCTED;
}
public ASMDataTable getASMHarvestedData()
{
return asmData;
}
public ListMultimap<String, String> getReverseDependencies()
{
return reverseDependencies;
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.ModContainer;
public class FMLEvent
{
public final String getEventType()
{
return getClass().getSimpleName();
}
public final String description()
{
String cn = getClass().getName();
return cn.substring(cn.lastIndexOf('.')+4,cn.length()-5);
}
public void applyModContainer(ModContainer activeContainer) {
// NO OP
}
}
@@ -0,0 +1,36 @@
/*
* 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.common.event;
import java.io.File;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
public class FMLFingerprintViolationEvent extends FMLEvent {
public final boolean isDirectory;
public final Set<String> fingerprints;
public final File source;
public final String expectedFingerprint;
public FMLFingerprintViolationEvent(boolean isDirectory, File source, ImmutableSet<String> fingerprints, String expectedFingerprint)
{
super();
this.isDirectory = isDirectory;
this.source = source;
this.fingerprints = fingerprints;
this.expectedFingerprint = expectedFingerprint;
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLInitializationEvent extends FMLStateEvent
{
public FMLInitializationEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.INITIALIZED;
}
}
@@ -0,0 +1,218 @@
/*
* 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.common.event;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.Mod.Instance;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
/**
* Simple intermod communications to receive simple messages directed at you
* from other mods
*
* @author cpw
*
*/
public class FMLInterModComms {
private static final ImmutableList<IMCMessage> emptyIMCList = ImmutableList.<IMCMessage>of();
private static ArrayListMultimap<String, IMCMessage> modMessages = ArrayListMultimap.create();
/**
* Subscribe to this event to receive your messages (they are sent between
* {@link Init} and {@link PostInit})
*
* @author cpw
*
*/
public static class IMCEvent extends FMLEvent {
private ModContainer activeContainer;
@Override
public void applyModContainer(ModContainer activeContainer)
{
this.activeContainer = activeContainer;
this.currentList = null;
FMLLog.finer("Attempting to deliver %d IMC messages to mod %s", modMessages.get(activeContainer.getModId()).size(), activeContainer.getModId());
}
private ImmutableList<IMCMessage> currentList;
public ImmutableList<IMCMessage> getMessages()
{
if (currentList == null)
{
currentList = ImmutableList.copyOf(modMessages.removeAll(activeContainer.getModId()));
}
return currentList;
}
}
/**
* You will receive an instance of this for each message sent
*
* @author cpw
*
*/
public static final class IMCMessage {
/**
* This is the modid of the mod that sent you the message
*/
private String sender;
/**
* This field, and {@link #value} are both at the mod's discretion
*/
public final String key;
/**
* This field, and {@link #key} are both at the mod's discretion
*/
private Object value;
private IMCMessage(String key, Object value)
{
this.key = key;
this.value = value;
}
@Override
public String toString()
{
return sender;
}
public String getSender()
{
return this.sender;
}
void setSender(ModContainer activeModContainer)
{
this.sender = activeModContainer.getModId();
}
public String getStringValue()
{
return (String) value;
}
public NBTTagCompound getNBTValue()
{
return (NBTTagCompound) value;
}
public ItemStack getItemStackValue()
{
return (ItemStack) value;
}
public Class<?> getMessageType()
{
return value.getClass();
}
public boolean isStringMessage()
{
return String.class.isAssignableFrom(getMessageType());
}
public boolean isItemStackMessage()
{
return ItemStack.class.isAssignableFrom(getMessageType());
}
public boolean isNBTMessage()
{
return NBTTagCompound.class.isAssignableFrom(getMessageType());
}
}
public static boolean sendMessage(String modId, String key, NBTTagCompound value)
{
return enqueueStartupMessage(modId, new IMCMessage(key, value));
}
public static boolean sendMessage(String modId, String key, ItemStack value)
{
return enqueueStartupMessage(modId, new IMCMessage(key, value));
}
public static boolean sendMessage(String modId, String key, String value)
{
return enqueueStartupMessage(modId, new IMCMessage(key, value));
}
public static void sendRuntimeMessage(Object sourceMod, String modId, String key, NBTTagCompound value)
{
enqueueMessage(sourceMod, modId, new IMCMessage(key, value));
}
public static void sendRuntimeMessage(Object sourceMod, String modId, String key, ItemStack value)
{
enqueueMessage(sourceMod, modId, new IMCMessage(key, value));
}
public static void sendRuntimeMessage(Object sourceMod, String modId, String key, String value)
{
enqueueMessage(sourceMod, modId, new IMCMessage(key, value));
}
private static boolean enqueueStartupMessage(String modTarget, IMCMessage message)
{
if (Loader.instance().activeModContainer() == null)
{
return false;
}
enqueueMessage(Loader.instance().activeModContainer(), modTarget, message);
return Loader.isModLoaded(modTarget) && !Loader.instance().hasReachedState(LoaderState.POSTINITIALIZATION);
}
private static void enqueueMessage(Object sourceMod, String modTarget, IMCMessage message)
{
ModContainer mc;
if (sourceMod instanceof ModContainer) {
mc = (ModContainer) sourceMod;
}
else
{
mc = FMLCommonHandler.instance().findContainerFor(sourceMod);
}
if (mc != null && Loader.isModLoaded(modTarget))
{
message.setSender(mc);
modMessages.put(modTarget, message);
}
}
/**
* Retrieve any pending runtime messages for the mod
* @param forMod The {@link Instance} of the Mod to fetch messages for
* @return any messages - the collection will never be null
*/
public static ImmutableList<IMCMessage> fetchRuntimeMessages(Object forMod)
{
ModContainer mc = FMLCommonHandler.instance().findContainerFor(forMod);
if (mc != null)
{
return ImmutableList.copyOf(modMessages.removeAll(mc.getModId()));
}
else
{
return emptyIMCList;
}
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLLoadCompleteEvent extends FMLStateEvent
{
public FMLLoadCompleteEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -0,0 +1,18 @@
/*
* 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.common.event;
public class FMLLoadEvent
{
}
@@ -0,0 +1,204 @@
package net.minecraftforge.fml.common.event;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.registry.GameData;
import net.minecraftforge.fml.common.registry.GameRegistry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ListMultimap;
/**
* This event is fired if a world is loaded that has block and item mappings referring the mod that are not
* in existence.
* These can be remapped to other existing objects, or simply discarded.
* Use get() and getAll() to process this event.
*
* @author cpw, Player
*
*/
public class FMLMissingMappingsEvent extends FMLEvent {
/**
* Actions you can take with this missing mapping.
* <ul>
* <li>{@link #IGNORE} means this missing mapping will be ignored.
* <li>{@link #WARN} means this missing mapping will generate a warning.
* <li>{@link #FAIL} means this missing mapping will prevent the world from loading.
* </ul>
* @author cpw
*
*/
public static enum Action {
/**
* Take the default action
*/
DEFAULT,
/**
* Ignore this missing mapping. This means the mapping will be abandoned
*/
IGNORE,
/**
* Generate a warning but allow loading to continue
*/
WARN,
/**
* Fail to load
*/
FAIL,
/**
* Remap this name to a new name (add a migration mapping)
*/
REMAP,
/**
* Allow a block to exist without itemblock anymore
*/
BLOCKONLY
}
public static class MissingMapping {
public final GameRegistry.Type type;
public final String name;
public final int id;
private Action action = Action.DEFAULT;
private Object target;
public MissingMapping(GameRegistry.Type type, String name, int id)
{
this.type = type;
this.name = name;
this.id = id;
}
/**
* @deprecated use ignore(), warn(), fail() or remap() instead
*/
@Deprecated
public void setAction(Action target)
{
if (target == Action.DEFAULT || target == Action.REMAP || target == Action.BLOCKONLY) throw new IllegalArgumentException();
this.action = target;
}
/**
* Ignore the missing item.
*/
public void ignore()
{
action = Action.IGNORE;
}
/**
* Warn the user about the missing item.
*/
public void warn()
{
action = Action.WARN;
}
/**
* Prevent the world from loading due to the missing item.
*/
public void fail()
{
action = Action.FAIL;
}
/**
* Remap the missing item to the specified Block.
*
* Use this if you have renamed a Block, don't forget to handle the ItemBlock.
* Existing references using the old name will point to the new one.
*
* @param target Block to remap to.
*/
public void remap(Block target)
{
if (type != GameRegistry.Type.BLOCK) throw new IllegalArgumentException("Can't remap an item to a block.");
if (target == null) throw new NullPointerException("remap target is null");
if (GameData.getBlockRegistry().getId(target) < 0) throw new IllegalArgumentException(String.format("The specified block %s hasn't been registered at startup.", target));
action = Action.REMAP;
this.target = target;
}
/**
* Remap the missing item to the specified Item.
*
* Use this if you have renamed an Item.
* Existing references using the old name will point to the new one.
*
* @param target Item to remap to.
*/
public void remap(Item target)
{
if (type != GameRegistry.Type.ITEM) throw new IllegalArgumentException("Can't remap a block to an item.");
if (target == null) throw new NullPointerException("remap target is null");
if (GameData.getItemRegistry().getId(target) < 0) throw new IllegalArgumentException(String.format("The specified item %s hasn't been registered at startup.", target));
action = Action.REMAP;
this.target = target;
}
public void skipItemBlock()
{
if (type != GameRegistry.Type.ITEM) throw new IllegalArgumentException("Cannot skip an item that is a block");
if (GameData.getBlockRegistry().getRaw(id) == null) throw new IllegalArgumentException("Cannot skip an ItemBlock that doesn't have a Block");
action = Action.BLOCKONLY;
}
// internal
public Action getAction()
{
return this.action;
}
public Object getTarget()
{
return target;
}
}
private ListMultimap<String,MissingMapping> missing;
private ModContainer activeContainer;
public FMLMissingMappingsEvent(ListMultimap<String,MissingMapping> missingMappings)
{
this.missing = missingMappings;
}
@Override
public void applyModContainer(ModContainer activeContainer)
{
super.applyModContainer(activeContainer);
this.activeContainer = activeContainer;
}
/**
* Get the list of missing mappings for the active mod.
*
* Process the list entries by calling ignore(), warn(), fail() or remap() on each entry.
*
* @return list of missing mappings
*/
public List<MissingMapping> get()
{
return ImmutableList.copyOf(missing.get(activeContainer.getModId()));
}
/**
* Get the list of missing mappings for all mods.
*
* Only use this if you need to handle mod id changes, e.g. if you renamed your mod or
* split/merge into/from multiple mods.
*
* Process the list entries by calling ignore(), warn(), fail() or remap() on each entry you
* want to handle.
*
* @return list of missing mappings
*/
public List<MissingMapping> getAll()
{
return ImmutableList.copyOf(missing.values());
}
}
@@ -0,0 +1,4 @@
package net.minecraftforge.fml.common.event;
public class FMLModDisabledEvent extends FMLEvent {
}
@@ -0,0 +1,52 @@
package net.minecraftforge.fml.common.event;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class FMLModIdMappingEvent extends FMLEvent {
public static enum RemapTarget { BLOCK, ITEM }
public class ModRemapping
{
public final int oldId;
public final int newId;
public final String tag;
public final RemapTarget remapTarget;
public ModRemapping(int oldId, int newId, String tag, RemapTarget type)
{
this.oldId = oldId;
this.newId = newId;
this.tag = tag;
this.remapTarget = type;
}
}
public final ImmutableList<ModRemapping> remappedIds;
public FMLModIdMappingEvent(Map<String, Integer[]> blocks, Map<String, Integer[]> items)
{
List<ModRemapping> remappings = Lists.newArrayList();
for (Entry<String, Integer[]> mapping : blocks.entrySet())
{
remappings.add(new ModRemapping(mapping.getValue()[0], mapping.getValue()[1], mapping.getKey(), RemapTarget.BLOCK));
}
for (Entry<String, Integer[]> mapping : items.entrySet())
{
remappings.add(new ModRemapping(mapping.getValue()[0], mapping.getValue()[1], mapping.getKey(), RemapTarget.ITEM));
}
Collections.sort(remappings, new Comparator<ModRemapping>() {
@Override
public int compare(ModRemapping o1, ModRemapping o2)
{
return (o1.newId < o2.newId) ? -1 : ((o1.newId == o2.newId) ? 0 : 1);
}
});
remappedIds = ImmutableList.copyOf(remappings);
}
}
@@ -0,0 +1,50 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState.ModState;
import com.google.common.base.Throwables;
public class FMLPostInitializationEvent extends FMLStateEvent
{
public FMLPostInitializationEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.POSTINITIALIZED;
}
public Object buildSoftDependProxy(String modId, String className)
{
if (Loader.isModLoaded(modId))
{
try
{
Class<?> clz = Class.forName(className,true,Loader.instance().getModClassLoader());
return clz.newInstance();
}
catch (Exception e)
{
Throwables.propagateIfPossible(e);
return null;
}
}
return null;
}
}
@@ -0,0 +1,132 @@
/*
* 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.common.event;
import java.io.File;
import java.security.CodeSource;
import java.security.cert.Certificate;
import java.util.Properties;
import net.minecraftforge.fml.common.FMLModContainer;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ModMetadata;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class FMLPreInitializationEvent extends FMLStateEvent
{
private ModMetadata modMetadata;
private File sourceFile;
private File configurationDir;
private File suggestedConfigFile;
private ASMDataTable asmData;
private ModContainer modContainer;
public FMLPreInitializationEvent(Object... data)
{
super(data);
this.asmData = (ASMDataTable)data[0];
this.configurationDir = (File)data[1];
}
@Override
public ModState getModState()
{
return ModState.PREINITIALIZED;
}
@Override
public void applyModContainer(ModContainer activeContainer)
{
this.modContainer = activeContainer;
this.modMetadata = activeContainer.getMetadata();
this.sourceFile = activeContainer.getSource();
this.suggestedConfigFile = new File(configurationDir, activeContainer.getModId()+".cfg");
}
public File getSourceFile()
{
return sourceFile;
}
public ModMetadata getModMetadata()
{
return modMetadata;
}
public File getModConfigurationDirectory()
{
return configurationDir;
}
public File getSuggestedConfigurationFile()
{
return suggestedConfigFile;
}
public ASMDataTable getAsmData()
{
return asmData;
}
public Properties getVersionProperties()
{
if (this.modContainer instanceof FMLModContainer)
{
return ((FMLModContainer)this.modContainer).searchForVersionProperties();
}
return null;
}
/**
* Get a logger instance configured to write to the FML Log as a parent, identified by modid. Handy for mod logging!
* Configurations can be applied through the <code>config/logging.properties</code> file, specifying logging levels
* for your ModID. Use this!
*
* @return A logger
*/
public Logger getModLog()
{
Logger log = LogManager.getLogger(modContainer.getModId());
return log;
}
/**
* Retrieve the FML signing certificates, if any. Validate these against the
* published FML certificates in your mod, if you wish.
*
* Deprecated because mods should <b>NOT</b> trust this code. Rather
* they should copy this, or something like this, into their own mods.
*
* @return Certificates used to sign FML and Forge
*/
@Deprecated
public Certificate[] getFMLSigningCertificates()
{
CodeSource codeSource = getClass().getClassLoader().getParent().getClass().getProtectionDomain().getCodeSource();
Certificate[] certs = codeSource.getCertificates();
if (certs == null)
{
return new Certificate[0];
}
else
{
return certs;
}
}
}
@@ -0,0 +1,37 @@
/*
* 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.common.event;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerAboutToStartEvent extends FMLStateEvent {
private MinecraftServer server;
public FMLServerAboutToStartEvent(Object... data)
{
super(data);
this.server = (MinecraftServer) data[0];
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
public MinecraftServer getServer()
{
return server;
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStartedEvent extends FMLStateEvent
{
public FMLServerStartedEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -0,0 +1,46 @@
/*
* 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.common.event;
import net.minecraft.command.CommandHandler;
import net.minecraft.command.ICommand;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStartingEvent extends FMLStateEvent
{
private MinecraftServer server;
public FMLServerStartingEvent(Object... data)
{
super(data);
this.server = (MinecraftServer) data[0];
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
public MinecraftServer getServer()
{
return server;
}
public void registerServerCommand(ICommand command)
{
CommandHandler ch = (CommandHandler) getServer().getCommandManager();
ch.registerCommand(command);
}
}
@@ -0,0 +1,29 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStoppedEvent extends FMLStateEvent {
public FMLServerStoppedEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -0,0 +1,31 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStoppingEvent extends FMLStateEvent
{
public FMLServerStoppingEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -0,0 +1,32 @@
/*
* 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.common.event;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.relauncher.Side;
public abstract class FMLStateEvent extends FMLEvent
{
public FMLStateEvent(Object... data)
{
}
public abstract ModState getModState();
public Side getSide()
{
return FMLCommonHandler.instance().getSide();
}
}
@@ -0,0 +1,152 @@
package net.minecraftforge.fml.common.eventhandler;
import static org.objectweb.asm.Opcodes.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import net.minecraftforge.fml.common.ModContainer;
import org.apache.logging.log4j.ThreadContext;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import com.google.common.collect.Maps;
public class ASMEventHandler implements IEventListener
{
private static int IDs = 0;
private static final String HANDLER_DESC = Type.getInternalName(IEventListener.class);
private static final String HANDLER_FUNC_DESC = Type.getMethodDescriptor(IEventListener.class.getDeclaredMethods()[0]);
private static final ASMClassLoader LOADER = new ASMClassLoader();
private static final HashMap<Method, Class<?>> cache = Maps.newHashMap();
private static final boolean GETCONTEXT = Boolean.parseBoolean(System.getProperty("fml.LogContext", "false"));
private final IEventListener handler;
private final SubscribeEvent subInfo;
private ModContainer owner;
private String readable;
public ASMEventHandler(Object target, Method method, ModContainer owner) throws Exception
{
this.owner = owner;
handler = (IEventListener)createWrapper(method).getConstructor(Object.class).newInstance(target);
subInfo = method.getAnnotation(SubscribeEvent.class);
readable = "ASM: " + target + " " + method.getName() + Type.getMethodDescriptor(method);
}
@Override
public void invoke(Event event)
{
if (owner != null && GETCONTEXT)
{
ThreadContext.put("mod", owner.getName());
}
else if (GETCONTEXT)
{
ThreadContext.put("mod", "");
}
if (handler != null)
{
if (!event.isCancelable() || !event.isCanceled() || subInfo.receiveCanceled())
{
handler.invoke(event);
}
}
if (GETCONTEXT)
ThreadContext.remove("mod");
}
public EventPriority getPriority()
{
return subInfo.priority();
}
public Class<?> createWrapper(Method callback)
{
if (cache.containsKey(callback))
{
return cache.get(callback);
}
ClassWriter cw = new ClassWriter(0);
MethodVisitor mv;
String name = getUniqueName(callback);
String desc = name.replace('.', '/');
String instType = Type.getInternalName(callback.getDeclaringClass());
String eventType = Type.getInternalName(callback.getParameterTypes()[0]);
/*
System.out.println("Name: " + name);
System.out.println("Desc: " + desc);
System.out.println("InstType: " + instType);
System.out.println("Callback: " + callback.getName() + Type.getMethodDescriptor(callback));
System.out.println("Event: " + eventType);
*/
cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER, desc, null, "java/lang/Object", new String[]{ HANDLER_DESC });
cw.visitSource(".dynamic", null);
{
cw.visitField(ACC_PUBLIC, "instance", "Ljava/lang/Object;", null, null).visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitFieldInsn(PUTFIELD, desc, "instance", "Ljava/lang/Object;");
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "invoke", HANDLER_FUNC_DESC, null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, desc, "instance", "Ljava/lang/Object;");
mv.visitTypeInsn(CHECKCAST, instType);
mv.visitVarInsn(ALOAD, 1);
mv.visitTypeInsn(CHECKCAST, eventType);
mv.visitMethodInsn(INVOKEVIRTUAL, instType, callback.getName(), Type.getMethodDescriptor(callback), false);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
}
cw.visitEnd();
Class<?> ret = LOADER.define(name, cw.toByteArray());
cache.put(callback, ret);
return ret;
}
private String getUniqueName(Method callback)
{
return String.format("%s_%d_%s_%s_%s", getClass().getName(), IDs++,
callback.getDeclaringClass().getSimpleName(),
callback.getName(),
callback.getParameterTypes()[0].getSimpleName());
}
private static class ASMClassLoader extends ClassLoader
{
private ASMClassLoader()
{
super(ASMClassLoader.class.getClassLoader());
}
public Class<?> define(String name, byte[] data)
{
return defineClass(name, data, 0, data.length);
}
}
public String toString()
{
return readable;
}
}
@@ -0,0 +1,11 @@
package net.minecraftforge.fml.common.eventhandler;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface Cancelable{}
@@ -0,0 +1,142 @@
package net.minecraftforge.fml.common.eventhandler;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
/**
* Base Event class that all other events are derived from
*/
public class Event
{
@Retention(value = RUNTIME)
@Target(value = TYPE)
public @interface HasResult{}
public enum Result
{
DENY,
DEFAULT,
ALLOW
}
private boolean isCanceled = false;
private Result result = Result.DEFAULT;
private static ListenerList listeners = new ListenerList();
private EventPriority phase = null;
public Event()
{
setup();
}
/**
* Determine if this function is cancelable at all.
* @return If access to setCanceled should be allowed
*
* Note:
* Events with the Cancelable annotation will have this method automatically added to return true.
*/
public boolean isCancelable()
{
return false;
}
/**
* Determine if this event is canceled and should stop executing.
* @return The current canceled state
*/
public boolean isCanceled()
{
return isCanceled;
}
/**
* Sets the state of this event, not all events are cancelable, and any attempt to
* cancel a event that can't be will result in a IllegalArgumentException.
*
* The functionality of setting the canceled state is defined on a per-event bases.
*
* @param cancel The new canceled value
*/
public void setCanceled(boolean cancel)
{
if (!isCancelable())
{
throw new IllegalArgumentException("Attempted to cancel a uncancelable event");
}
isCanceled = cancel;
}
/**
* Determines if this event expects a significant result value.
*
* Note:
* Events with the HasResult annotation will have this method automatically added to return true.
*/
public boolean hasResult()
{
return false;
}
/**
* Returns the value set as the result of this event
*/
public Result getResult()
{
return result;
}
/**
* Sets the result value for this event, not all events can have a result set, and any attempt to
* set a result for a event that isn't expecting it will result in a IllegalArgumentException.
*
* The functionality of setting the result is defined on a per-event bases.
*
* @param value The new result
*/
public void setResult(Result value)
{
result = value;
}
/**
* Called by the base constructor, this is used by ASM generated
* event classes to setup various functionality such as the listenerlist.
*/
protected void setup()
{
}
/**
* Returns a ListenerList object that contains all listeners
* that are registered to this event.
*
* @return Listener List
*/
public ListenerList getListenerList()
{
return listeners;
}
@Nullable
public EventPriority getPhase()
{
return this.phase;
}
public void setPhase(@Nonnull EventPriority value)
{
Preconditions.checkArgument(value != null, "setPhase argument must not be null");
int prev = phase == null ? -1 : phase.ordinal();
Preconditions.checkArgument(prev < value.ordinal(), "Attempted to set event phase to %s when already %s", value, phase);
phase = value;
}
}
@@ -0,0 +1,159 @@
package net.minecraftforge.fml.common.eventhandler;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.apache.logging.log4j.Level;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.MapMaker;
import com.google.common.reflect.TypeToken;
public class EventBus implements IEventExceptionHandler
{
private static int maxID = 0;
private ConcurrentHashMap<Object, ArrayList<IEventListener>> listeners = new ConcurrentHashMap<Object, ArrayList<IEventListener>>();
private Map<Object,ModContainer> listenerOwners = new MapMaker().weakKeys().weakValues().makeMap();
private final int busID = maxID++;
private IEventExceptionHandler exceptionHandler;
public EventBus()
{
ListenerList.resize(busID + 1);
exceptionHandler = this;
}
public EventBus(@Nonnull IEventExceptionHandler handler)
{
this();
Preconditions.checkArgument(handler != null, "EventBus exception handler can not be null");
exceptionHandler = handler;
}
public void register(Object target)
{
if (listeners.containsKey(target))
{
return;
}
ModContainer activeModContainer = Loader.instance().activeModContainer();
if (activeModContainer == null)
{
FMLLog.log(Level.ERROR, new Throwable(), "Unable to determine registrant mod for %s. This is a critical error and should be impossible", target);
activeModContainer = Loader.instance().getMinecraftModContainer();
}
listenerOwners.put(target, activeModContainer);
Set<? extends Class<?>> supers = TypeToken.of(target.getClass()).getTypes().rawTypes();
for (Method method : target.getClass().getMethods())
{
for (Class<?> cls : supers)
{
try
{
Method real = cls.getDeclaredMethod(method.getName(), method.getParameterTypes());
if (real.isAnnotationPresent(SubscribeEvent.class))
{
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1)
{
throw new IllegalArgumentException(
"Method " + method + " has @SubscribeEvent annotation, but requires " + parameterTypes.length +
" arguments. Event handler methods must require a single argument."
);
}
Class<?> eventType = parameterTypes[0];
if (!Event.class.isAssignableFrom(eventType))
{
throw new IllegalArgumentException("Method " + method + " has @SubscribeEvent annotation, but takes a argument that is not an Event " + eventType);
}
register(eventType, target, real, activeModContainer);
break;
}
}
catch (NoSuchMethodException e)
{
;
}
}
}
}
private void register(Class<?> eventType, Object target, Method method, ModContainer owner)
{
try
{
Constructor<?> ctr = eventType.getConstructor();
ctr.setAccessible(true);
Event event = (Event)ctr.newInstance();
ASMEventHandler listener = new ASMEventHandler(target, method, owner);
event.getListenerList().register(busID, listener.getPriority(), listener);
ArrayList<IEventListener> others = listeners.get(target);
if (others == null)
{
others = new ArrayList<IEventListener>();
listeners.put(target, others);
}
others.add(listener);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void unregister(Object object)
{
ArrayList<IEventListener> list = listeners.remove(object);
for (IEventListener listener : list)
{
ListenerList.unregisterAll(busID, listener);
}
}
public boolean post(Event event)
{
IEventListener[] listeners = event.getListenerList().getListeners(busID);
int index = 0;
try
{
for (; index < listeners.length; index++)
{
listeners[index].invoke(event);
}
}
catch (Throwable throwable)
{
exceptionHandler.handleException(this, event, listeners, index, throwable);
Throwables.propagate(throwable);
}
return (event.isCancelable() ? event.isCanceled() : false);
}
@Override
public void handleException(EventBus bus, Event event, IEventListener[] listeners, int index, Throwable throwable)
{
FMLLog.log(Level.ERROR, throwable, "Exception caught during firing event %s:", event);
FMLLog.log(Level.ERROR, "Index: %d Listeners:", index);
for (int x = 0; x < listeners.length; x++)
{
FMLLog.log(Level.ERROR, "%d: %s", x, listeners[x]);
}
}
}
@@ -0,0 +1,23 @@
package net.minecraftforge.fml.common.eventhandler;
public enum EventPriority implements IEventListener
{
/*Priority of event listeners, listeners will be sorted with respect to this priority level.
*
* Note:
* Due to using a ArrayList in the ListenerList,
* these need to stay in a contiguous index starting at 0. {Default ordinal}
*/
HIGHEST, //First to execute
HIGH,
NORMAL,
LOW,
LOWEST //Last to execute
;
@Override
public void invoke(Event event)
{
event.setPhase(this);
}
}
Loaded 100 of 356 files, more files were not shown because too many files have changed in this diff. Show more