Well, it works, for a game, now.

This commit is contained in:
cpw authored and LexManos committed 2018-09-05 12:30:02 -07:00
1 parent 06b16aaa19
commit d0ab0e166c
208 files changed
+2328 -5883

No files matched your search

@@ -19,10 +19,9 @@
package net.minecraftforge.fml;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.language.ModFileScanData;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation;
@@ -47,6 +46,7 @@ public class AutomaticEventSubscriber
private static final Logger LOGGER = LogManager.getLogger("FML");
public static void inject(final ModContainer mod, final ModFileScanData scanData, final ClassLoader loader)
{
if (scanData == null) return;
LOGGER.debug(LOADING,"Attempting to inject @EventBusSubscriber classes into the eventbus for {}", mod.getModId());
List<ModFileScanData.AnnotationData> ebsTargets = scanData.getAnnotations().stream().
filter(annotationData -> Objects.equals(annotationData.getAnnotationType(), Type.getType(Mod.EventBusSubscriber.class))).
@@ -55,11 +55,11 @@ public class AutomaticEventSubscriber
ebsTargets.forEach(ad -> {
@SuppressWarnings("unchecked")
final List<ModAnnotation.EnumHolder> sidesValue = (List<ModAnnotation.EnumHolder>)ad.getAnnotationData().
getOrDefault("value", Arrays.asList(new ModAnnotation.EnumHolder(null, "CLIENT"), new ModAnnotation.EnumHolder(null, "SERVER")));
final EnumSet<Side> sides = sidesValue.stream().map(eh -> Side.valueOf(eh.getValue())).
collect(Collectors.toCollection(() -> EnumSet.noneOf(Side.class)));
getOrDefault("value", Arrays.asList(new ModAnnotation.EnumHolder(null, "CLIENT"), new ModAnnotation.EnumHolder(null, "DEDICATED_SERVER")));
final EnumSet<Dist> sides = sidesValue.stream().map(eh -> Dist.valueOf(eh.getValue())).
collect(Collectors.toCollection(() -> EnumSet.noneOf(Dist.class)));
final String modId = (String)ad.getAnnotationData().getOrDefault("modId", mod.getModId());
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.side)) {
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) {
try
{
MinecraftForge.EVENT_BUS.register(Class.forName(ad.getClassType().getClassName(), true, loader));
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.client;
package net.minecraftforge.fml;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
@@ -25,6 +25,7 @@ import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.fml.ModList;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@@ -70,4 +71,9 @@ public class BrandingControl
public static String getClientBranding() {
return defaultClientBranding.stream().collect(Collectors.joining(","));
}
public static final List<String> defaultServerBranding = Arrays.asList("fml", "forge");
public static String getServerBranding() {
return defaultServerBranding.stream().collect(Collectors.joining(","));
}
}
@@ -19,13 +19,9 @@
package net.minecraftforge.fml;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraftforge.fml.common.ICrashCallable;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.relauncher.CoreModManager;
import java.util.ArrayList;
import java.util.List;
@@ -0,0 +1,143 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import com.google.common.collect.Multimap;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.RegistryManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
/**
* @author cpw
*
*/
public final class FMLWorldPersistenceHook implements WorldPersistenceHooks.WorldPersistenceHook
{
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP");
@Override
public String getModId()
{
return "fml";
}
@Override
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
{
NBTTagCompound fmlData = new NBTTagCompound();
NBTTagList modList = new NBTTagList();
ModList.get().getMods().forEach(mi->
{
final NBTTagCompound mod = new NBTTagCompound();
mod.setString("ModId", mi.getModId());
mod.setString("ModVersion", mi.getVersion().getVersionString());
modList.appendTag(mod);
});
fmlData.setTag("LoadingModList", modList);
NBTTagCompound registries = new NBTTagCompound();
fmlData.setTag("Registries", registries);
LOGGER.debug(WORLDPERSISTENCE,"Gathering id map for writing to world save {}", info.getWorldName());
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
{
registries.setTag(e.getKey().toString(), e.getValue().write());
}
return fmlData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag)
{
if (tag.hasKey("LoadingModList"))
{
NBTTagList modList = tag.getTagList("LoadingModList", (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");
Optional<? extends ModContainer> container = ModList.get().getModContainerById(modId);
if (!container.isPresent())
{
LOGGER.error(WORLDPERSISTENCE,"This world was saved with mod {} which appears to be missing, things may not work well", modId);
continue;
}
if (!modVersion.equals(container.get().getModInfo().getVersion().getVersionString()))
{
LOGGER.info(WORLDPERSISTENCE,"This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, container.get().getModInfo().getVersion().getVersionString());
}
}
}
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
if (tag.hasKey("ModItemData") || tag.hasKey("ItemData")) // Pre 1.7
{
StartupQuery.notify("This save predates 1.7.10, it can no longer be loaded here. Please load in 1.7.10 or 1.8 first");
StartupQuery.abort();
}
else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list
{
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
NBTTagCompound regs = tag.getCompoundTag("Registries");
for (String key : regs.getKeySet())
{
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompoundTag(key)));
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
if (failedElements != null && !failedElements.isEmpty())
{
StringBuilder buf = new StringBuilder();
buf.append("Forge Mod Loader could not load this save.\n\n")
.append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n")
.append("You will not be able to load until they are present again.\n\n");
failedElements.asMap().forEach((name, entries) ->
{
buf.append("Missing ").append(name).append(":\n");
entries.forEach(rl -> buf.append(" ").append(rl).append("\n"));
});
StartupQuery.notify(buf.toString());
StartupQuery.abort();
}
}
}
@@ -1,6 +1,6 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -17,16 +17,9 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
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);
}
package net.minecraftforge.fml;
public enum LogicalSide
{
CLIENT, SERVER
}
@@ -20,6 +20,7 @@
package net.minecraftforge.fml;
import net.minecraftforge.fml.language.IModInfo;
import net.minecraftforge.fml.network.Networking;
import java.util.ArrayList;
import java.util.HashMap;
@@ -51,7 +52,6 @@ public abstract class ModContainer
protected final Map<ModLoadingStage, Consumer<LifecycleEventProvider.LifecycleEvent>> triggerMap;
protected final Map<ExtensionPoint, Supplier<?>> extensionPoints = new IdentityHashMap<>();
protected final List<Throwable> modLoadingError;
public ModContainer(IModInfo info)
{
this.modId = info.getModId();
@@ -39,6 +39,7 @@ import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.FutureTask;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -157,4 +158,9 @@ public class ModList
return modFileScanData;
}
public void forEachModFile(Consumer<ModFile> fileConsumer)
{
modFiles.stream().map(ModFileInfo::getFile).forEach(fileConsumer);
}
}
@@ -19,7 +19,8 @@
package net.minecraftforge.fml;
import net.minecraftforge.api.Side;
import com.google.common.collect.Streams;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.CapabilityManager;
@@ -32,6 +33,7 @@ import net.minecraftforge.registries.GameData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -39,6 +41,9 @@ import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.minecraftforge.fml.Logging.CORE;
public class ModLoader
{
@@ -69,16 +74,30 @@ public class ModLoader
public void loadMods() {
final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).collect(Collectors.toList()), loadingModList.getMods());
modList.setLoadedMods(loadingModList.getModFiles().stream().
final ModContainer forgeModContainer;
try
{
forgeModContainer = (ModContainer)Class.forName("net.minecraftforge.common.ForgeModContainer", true, modClassLoader).
getConstructor(ModLoadingClassLoader.class).newInstance(modClassLoader);
}
catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException e)
{
LOGGER.error(CORE,"Unable to load the Forge Mod Container", e);
throw new RuntimeException(e);
}
final Stream<ModContainer> modContainerStream = loadingModList.getModFiles().stream().
map(ModFileInfo::getFile).
map(mf -> buildMods(mf, modClassLoader)).
flatMap(Collection::stream).collect(Collectors.toList()));
flatMap(Collection::stream);
modList.setLoadedMods(Streams.concat(Stream.of(forgeModContainer), modContainerStream).collect(Collectors.toList()));
LifecycleEventProvider.CONSTRUCT.dispatch();
WorldPersistenceHooks.addHook(new FMLWorldPersistenceHook());
WorldPersistenceHooks.addHook((WorldPersistenceHooks.WorldPersistenceHook)forgeModContainer.getMod());
GameData.fireCreateRegistryEvents();
CapabilityManager.INSTANCE.injectCapabilities(modList.getAllScanData());
LifecycleEventProvider.PREINIT.dispatch();
GameData.fireRegistryEvents(rl -> !Objects.equals(rl, GameData.RECIPES));
SidedExecutor.runOn(Side.CLIENT, ModLoader::fireClientEvents);
SidedExecutor.runOn(Dist.CLIENT, ModLoader::fireClientEvents);
LifecycleEventProvider.SIDEDINIT.dispatch();
}
@@ -97,5 +116,7 @@ public class ModLoader
LifecycleEventProvider.INIT.dispatch();
LifecycleEventProvider.POSTINIT.dispatch();
LifecycleEventProvider.COMPLETE.dispatch();
GameData.freezeData();
}
}
@@ -27,9 +27,13 @@ public class ModThreadContext
return context.get();
}
private ModContainer currentContainer;
private ModContainer activeContainer;
public ModContainer getCurrentContainer() {
return currentContainer == null ? DefaultModContainers.MINECRAFT : currentContainer;
public void setActiveContainer(final ModContainer container) {
this.activeContainer = container;
}
public ModContainer getActiveContainer() {
return activeContainer == null ? DefaultModContainers.MINECRAFT : activeContainer;
}
}
@@ -20,7 +20,6 @@
package net.minecraftforge.fml;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
import net.minecraftforge.registries.RegistryManager;
@@ -0,0 +1,156 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* 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 version 2.1
* of the License.
*
* 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;
import net.minecraft.network.EnumConnectionState;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.handshake.client.C00Handshake;
import net.minecraft.network.login.server.SPacketDisconnect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.FMLLog;
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.network.NetworkRegistry;
import net.minecraftforge.fml.network.NetworkHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
public class ServerLifecycleHooks
{
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker SERVERHOOKS = MarkerManager.getMarker("SERVERHOOKS");
private static volatile CountDownLatch exitLatch = null;
private static MinecraftServer currentServer;
public static boolean handleServerAboutToStart(final MinecraftServer server)
{
currentServer = server;
return !MinecraftForge.EVENT_BUS.post(new FMLServerAboutToStartEvent(server));
}
public static boolean handleServerStarting(final MinecraftServer server)
{
return !MinecraftForge.EVENT_BUS.post(new FMLServerStartingEvent(server));
}
public static void handleServerStarted()
{
MinecraftForge.EVENT_BUS.post(new FMLServerStartedEvent());
allowLogins.set(true);
}
public static void handleServerStopping()
{
allowLogins.set(false);
MinecraftForge.EVENT_BUS.post(new FMLServerStoppingEvent());
}
public static void expectServerStopped()
{
exitLatch = new CountDownLatch(1);
}
public static void handleServerStopped(final MinecraftServer server)
{
MinecraftForge.EVENT_BUS.post(new FMLServerStoppedEvent());
currentServer = null;
CountDownLatch latch = exitLatch;
if (latch != null)
{
latch.countDown();
exitLatch = null;
}
}
public static MinecraftServer getCurrentServer()
{
return currentServer;
}
private static AtomicBoolean allowLogins = new AtomicBoolean(false);
public static boolean handleServerLogin(final C00Handshake packet, final NetworkManager manager) {
if (!allowLogins.get())
{
TextComponentString text = new TextComponentString("Server is still starting! Please wait before reconnecting.");
LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getUnformattedText());
manager.sendPacket(new SPacketDisconnect(text));
manager.closeChannel(text);
return false;
}
if (packet.getRequestedState() == EnumConnectionState.LOGIN && !NetworkHooks.accepts(packet))
{
manager.setConnectionState(EnumConnectionState.LOGIN);
TextComponentString text = new TextComponentString("This server has mods that require Forge to be installed on the client. Contact your server admin for more details.");
List<String> modNames = net.minecraftforge.fml.network.NetworkRegistry.getNonVanillaNetworkMods();
LOGGER.info(SERVERHOOKS,"Disconnecting vanilla connection attempt. Required mods {}", modNames);
manager.sendPacket(new SPacketDisconnect(text));
manager.closeChannel(text);
return false;
}
manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.getFMLVersion());
return true;
}
public void handleExit(int retVal)
{
/*
CountDownLatch latch = exitLatch;
if (latch != null)
{
try
{
FMLLog.log.info("Waiting for the server to terminate/save.");
if (!latch.await(10, TimeUnit.SECONDS))
{
FMLLog.log.warn("The server didn't stop within 10 seconds, exiting anyway.");
}
else
{
FMLLog.log.info("Server terminated.");
}
}
catch (InterruptedException e)
{
FMLLog.log.warn("Interrupted wait, exiting.");
}
}
*/
System.exit(retVal);
}
}
@@ -19,7 +19,7 @@
package net.minecraftforge.fml;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.FMLEnvironment;
import java.util.concurrent.Callable;
@@ -32,13 +32,13 @@ public final class SidedExecutor
/**
* Run the callable in the supplier only on the specified {@link Side}
*
* @param side The side to run on
* @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate side)
* @param dist The dist to run on
* @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate dist)
* @param <T> The return type from the callable
* @return The callable's result
*/
public static <T> T runOn(Side side, Supplier<Callable<T>> toRun) {
if (side == FMLEnvironment.side) {
public static <T> T runOn(Dist dist, Supplier<Callable<T>> toRun) {
if (dist == FMLEnvironment.dist) {
try
{
return toRun.get().call();
@@ -52,11 +52,11 @@ public final class SidedExecutor
}
public static <T> T runSided(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
switch (FMLEnvironment.side)
switch (FMLEnvironment.dist)
{
case CLIENT:
return clientTarget.get().get();
case SERVER:
case DEDICATED_SERVER:
return serverTarget.get().get();
default:
throw new IllegalArgumentException("UNSIDED?");
@@ -21,13 +21,12 @@ package net.minecraftforge.fml;
import net.minecraft.client.Minecraft;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.client.SplashProgress;
import net.minecraftforge.fml.common.event.FMLClientInitEvent;
import net.minecraftforge.fml.common.event.FMLServerInitEvent;
import net.minecraftforge.fml.loading.FMLEnvironment;
import sun.plugin.security.StripClassFile;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -38,7 +37,8 @@ public enum SidedProvider
SIDEDINIT((Function<Supplier<Minecraft>, Function<ModContainer, Event>>)c-> mc->new FMLClientInitEvent(c.get(), mc),
(Function<Supplier<DedicatedServer>, Function<ModContainer, Event>>)s-> mc->new FMLServerInitEvent(s.get(), mc)),
STRIPCHARS((Function<Supplier<Minecraft>, Function<String, String>>)c-> SplashProgress::stripSpecialChars,
(Function<Supplier<DedicatedServer>, Function<String, String>>)s-> str->str);
(Function<Supplier<DedicatedServer>, Function<String, String>>)s-> str->str),
STARTUPQUERY(StartupQuery::clientQuery, StartupQuery::dedicatedServerQuery);
private static Supplier<Minecraft> client;
private static Supplier<DedicatedServer> server;
@@ -64,10 +64,10 @@ public enum SidedProvider
@SuppressWarnings("unchecked")
public <T> T get() {
if (FMLEnvironment.side == Side.CLIENT) {
if (FMLEnvironment.dist == Dist.CLIENT) {
return (T)this.clientSide.apply(client);
}
else if (FMLEnvironment.side == Side.SERVER) {
else if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) {
return (T)this.serverSide.apply(server);
}
else {
@@ -0,0 +1,322 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* 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 version 2.1
* of the License.
*
* 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;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraft.client.Minecraft;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.dedicated.PendingCommand;
import net.minecraftforge.fml.client.gui.GuiConfirmation;
import net.minecraftforge.fml.client.gui.GuiNotification;
import net.minecraftforge.fml.common.thread.EffectiveSide;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nullable;
public class StartupQuery {
// internal class/functionality, do not use
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker SQ = MarkerManager.getMarker("STARTUPQUERY");
public static boolean confirm(String text)
{
StartupQuery query = new StartupQuery(text, new AtomicBoolean());
query.execute();
return query.getResult();
}
private InterruptedException exception;
public static void notify(String text)
{
StartupQuery query = new StartupQuery(text, null);
query.execute();
}
public static void abort()
{
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
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
{
try
{
SidedProvider.STARTUPQUERY.<Consumer<StartupQuery>>get().accept(pending);
}
catch (RuntimeException e)
{
}
pending.throwException();
}
catch (InterruptedException e)
{
LOGGER.warn(SQ, "query interrupted");
abort();
}
pending = null;
}
return !aborted;
}
private void throwException() throws InterruptedException
{
if (exception != null) throw exception;
}
private static volatile StartupQuery pending;
private static volatile boolean aborted = false;
private StartupQuery(String text, @Nullable AtomicBoolean result)
{
this.text = text;
this.result = result;
}
@Nullable
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)
{
LOGGER.info(SQ, "Using fml.queryResult {} to answer the following query:\n{}", prop, text);
if (prop.equalsIgnoreCase("confirm"))
{
setResult(true);
return;
}
else if (prop.equalsIgnoreCase("cancel"))
{
setResult(false);
return;
}
LOGGER.warn(SQ, "Invalid value for fml.queryResult: {}, 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 (FMLEnvironment.dist.isDedicatedServer() || EffectiveSide.get() == LogicalSide.CLIENT)
{
synchronous = true;
check();
}
try
{
signal.await();
reset();
}
catch (InterruptedException e)
{
LOGGER.warn(SQ, "query interrupted");
abort();
}
}
private String text;
@Nullable
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();
}
}
public static Consumer<StartupQuery> clientQuery(Supplier<Minecraft> clientSupplier)
{
return (query) -> {
Minecraft client = clientSupplier.get();
if (query.getResult() == null)
{
client.displayGuiScreen(new GuiNotification(query));
}
else
{
client.displayGuiScreen(new GuiConfirmation(query));
}
if (query.isSynchronous())
{
while (client.currentScreen instanceof GuiNotification)
{
if (Thread.interrupted()) {
query.exception = new InterruptedException();
throw new RuntimeException();
}
client.loadingScreen.displayLoadingString("");
try
{
Thread.sleep(50);
} catch (InterruptedException ie) {
query.exception = ie;
}
}
client.loadingScreen.displayLoadingString(""); // make sure the blank screen is being drawn at the end
}
};
}
public static Consumer<StartupQuery> dedicatedServerQuery(Supplier<DedicatedServer> serverSupplier)
{
return (query) -> {
DedicatedServer server = serverSupplier.get();
if (query.getResult() == null)
{
LOGGER.warn(SQ, query.getText());
query.finish();
}
else
{
String text = query.getText() +
"\n\nRun the command /fml confirm or or /fml cancel to proceed." +
"\nAlternatively start the server with -Dfml.queryResult=confirm or -Dfml.queryResult=cancel to preselect the answer.";
LOGGER.warn(SQ, text);
if (!query.isSynchronous()) return; // no-op until mc does commands in another thread (if ever)
boolean done = false;
while (!done && server.isServerRunning())
{
if (Thread.interrupted())
{
query.exception = new InterruptedException();
throw new RuntimeException();
}
DedicatedServer dedServer = (DedicatedServer)server;
// rudimentary command processing, check for fml confirm/cancel and stop commands
synchronized (dedServer.pendingCommandList)
{
for (Iterator<PendingCommand> it = dedServer.pendingCommandList.iterator(); it.hasNext(); )
{
String cmd = it.next().command.trim().toLowerCase();
if (cmd.equals("/fml confirm"))
{
LOGGER.info(SQ, "confirmed");
query.setResult(true);
done = true;
it.remove();
}
else if (cmd.equals("/fml cancel"))
{
LOGGER.info(SQ, "cancelled");
query.setResult(false);
done = true;
it.remove();
}
else if (cmd.equals("/stop"))
{
StartupQuery.abort();
}
}
}
try
{
Thread.sleep(10L);
} catch (InterruptedException ie) {
query.exception = ie;
}
}
query.finish();
}
};
}
}
@@ -0,0 +1,81 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* 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 version 2.1
* of the License.
*
* 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;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.fml.common.thread.EffectiveSide;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WorldPersistenceHooks
{
private static List<WorldPersistenceHook> worldPersistenceHooks = new ArrayList<>();
public static void addHook(WorldPersistenceHook hook) {
worldPersistenceHooks.add(hook);
}
public static void handleWorldDataSave(final SaveHandler handler, final WorldInfo worldInfo, final NBTTagCompound tagCompound)
{
worldPersistenceHooks.forEach(wac->tagCompound.setTag(wac.getModId(), wac.getDataForWriting(handler, worldInfo)));
}
public static void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
{
if (EffectiveSide.get() == LogicalSide.SERVER)
{
Map<String, NBTBase> additionalProperties = new HashMap<>();
worldInfo.setAdditionalProperties(additionalProperties);
worldPersistenceHooks.forEach(wac->wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(wac.getModId())));
}
}
public static 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 interface WorldPersistenceHook
{
String getModId();
NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info);
void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag);
}
}
@@ -0,0 +1,197 @@
/*
* Minecraft Forge
* Copyright (c) 2018.
*
* 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 version 2.1
* of the License.
*
* 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.client;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiWorldSelection;
import net.minecraft.client.gui.ServerListEntryNormal;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.ServerStatusResponse;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.WorldSummary;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.registries.GameData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class ClientHooks
{
private static final Logger LOGGER = LogManager.getLogger("FML");
private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS");
private static Map<ServerStatusResponse,JsonObject> extraServerListData;
private static Map<ServerData, ExtendedServerListData> serverDataTag;
public static void setupServerList()
{
extraServerListData = Collections.synchronizedMap(new HashMap<>());
serverDataTag = Collections.synchronizedMap(new HashMap<>());
}
public static void captureAdditionalData(ServerStatusResponse serverstatusresponse, JsonObject jsonobject)
{
if (jsonobject.has("modinfo"))
{
JsonObject fmlData = jsonobject.get("modinfo").getAsJsonObject();
extraServerListData.put(serverstatusresponse, fmlData);
}
}
public static void bindServerListData(ServerData data, ServerStatusResponse originalResponse)
{
if (extraServerListData.containsKey(originalResponse))
{
JsonObject jsonData = extraServerListData.get(originalResponse);
String type = jsonData.get("type").getAsString();
JsonArray modDataArray = jsonData.get("modList").getAsJsonArray();
boolean moddedClientAllowed = !jsonData.has("clientModsAllowed") || jsonData.get("clientModsAllowed").getAsBoolean();
ImmutableMap.Builder<String, String> modListBldr = ImmutableMap.builder();
for (JsonElement obj : modDataArray)
{
JsonObject modObj = obj.getAsJsonObject();
modListBldr.put(modObj.get("modid").getAsString(), modObj.get("version").getAsString());
}
Map<String,String> modListMap = modListBldr.build();
String modRejections = FMLNetworkHandler.checkModList(modListMap, LogicalSide.SERVER);
serverDataTag.put(data, new ExtendedServerListData(type, modRejections == null, modListMap, !moddedClientAllowed));
}
else
{
String serverDescription = data.serverMOTD;
boolean moddedClientAllowed = true;
if (!Strings.isNullOrEmpty(serverDescription))
{
moddedClientAllowed = !serverDescription.endsWith(":NOFML§r");
}
serverDataTag.put(data, new ExtendedServerListData("VANILLA", false, ImmutableMap.of(), !moddedClientAllowed));
}
startupConnectionData.countDown();
}
private static final ResourceLocation iconSheet = new ResourceLocation("fml:textures/gui/icons.png");
private static final CountDownLatch startupConnectionData = new CountDownLatch(1);
@Nullable
public static String enhanceServerListEntry(ServerListEntryNormal serverListEntry, ServerData serverEntry, int x, int width, int y, int relativeMouseX, int relativeMouseY)
{
String tooltip;
int idx;
boolean blocked = false;
if (serverDataTag.containsKey(serverEntry))
{
ExtendedServerListData extendedData = serverDataTag.get(serverEntry);
if ("FML".equals(extendedData.type) && extendedData.isCompatible)
{
idx = 0;
tooltip = String.format("Compatible FML modded server\n%d mods present", extendedData.modData.size());
}
else if ("FML".equals(extendedData.type) && !extendedData.isCompatible)
{
idx = 16;
tooltip = String.format("Incompatible FML modded server\n%d mods present", extendedData.modData.size());
}
else if ("BUKKIT".equals(extendedData.type))
{
idx = 32;
tooltip = String.format("Bukkit modded server");
}
else if ("VANILLA".equals(extendedData.type))
{
idx = 48;
tooltip = String.format("Vanilla server");
}
else
{
idx = 64;
tooltip = String.format("Unknown server data");
}
blocked = extendedData.isBlocked;
}
else
{
return null;
}
Minecraft.getMinecraft().getTextureManager().bindTexture(iconSheet);
Gui.drawModalRectWithCustomSizedTexture(x + width - 18, y + 10, 0, (float)idx, 16, 16, 256.0f, 256.0f);
if (blocked)
{
Gui.drawModalRectWithCustomSizedTexture(x + width - 18, y + 10, 0, 80, 16, 16, 256.0f, 256.0f);
}
return relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26 ? tooltip : null;
}
public static String fixDescription(String description)
{
return description.endsWith(":NOFML§r") ? description.substring(0, description.length() - 8)+"§r" : description;
}
static File getSavesDir()
{
return new File(Minecraft.getMinecraft().mcDataDir, "saves");
}
public static void tryLoadExistingWorld(GuiWorldSelection selectWorldGUI, WorldSummary comparator)
{
try
{
Minecraft.getMinecraft().launchIntegratedServer(comparator.getFileName(), comparator.getDisplayName(), null);
}
catch (StartupQuery.AbortedException e)
{
// ignore
}
}
private static NetworkManager getClientToServerNetworkManager()
{
return Minecraft.getMinecraft().getConnection()!=null ? Minecraft.getMinecraft().getConnection().getNetworkManager() : null;
}
public static void handleClientWorldClosing(WorldClient world)
{
NetworkManager client = getClientToServerNetworkManager();
// ONLY revert a non-local connection
if (client != null && !client.isLocalChannel())
{
GameData.revertToFrozen();
}
}
}
@@ -25,8 +25,8 @@ import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.data.MetadataSerializer;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.SideOnly;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.SidedProvider;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.ModLoader;
@@ -37,7 +37,7 @@ import org.lwjgl.input.Mouse;
import java.io.IOException;
import java.util.List;
@SideOnly(Side.CLIENT)
@OnlyIn(Dist.CLIENT)
public class ClientModLoader
{
private static boolean loading;
@@ -113,14 +113,12 @@ import net.minecraftforge.fml.common.MetadataCollection;
import net.minecraftforge.fml.common.MissingModsException;
import net.minecraftforge.fml.common.MultipleModsErrored;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.ModMetadata;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.common.WrongMinecraftVersionException;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.common.toposort.ModSortingException;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.registries.GameData;
import org.lwjgl.input.Mouse;
@@ -21,11 +21,10 @@ package net.minecraftforge.fml.client.gui;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiErrorScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.common.IFMLHandledException;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.api.distmarker.Dist;
/**
* If a mod throws this exception during loading, it will be called back to render
@@ -37,7 +36,7 @@ import net.minecraftforge.fml.relauncher.SideOnly;
* @author cpw
*
*/
@SideOnly(Side.CLIENT)
@OnlyIn(Dist.CLIENT)
public abstract class CustomModLoadingErrorDisplayException extends EnhancedRuntimeException implements IFMLHandledException, IDisplayableError
{
public CustomModLoadingErrorDisplayException() {
@@ -23,7 +23,7 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.StartupQuery;
public class GuiConfirmation extends GuiNotification
{
@@ -23,7 +23,7 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.StartupQuery;
public class GuiNotification extends GuiScreen
{
@@ -28,7 +28,7 @@ import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.StartupQuery;
import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.common.ZipperUtil;
public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback {
@@ -52,7 +52,10 @@ import net.minecraftforge.client.model.animation.Animation;
import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.fml.client.BrandingControl;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.StartupQuery;
import net.minecraftforge.fml.WorldPersistenceHooks;
import net.minecraftforge.fml.BrandingControl;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.gameevent.InputEvent;
@@ -63,7 +66,6 @@ import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.thread.SidedThreadGroup;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.server.FMLServerHandler;
import org.apache.logging.log4j.Logger;
@@ -320,7 +322,7 @@ public class FMLCommonHandler
{
if (mc instanceof InjectedModContainer)
{
WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
WorldPersistenceHooks.WorldPersistenceHook wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
if (wac != null)
{
NBTTagCompound dataForWriting = wac.getDataForWriting(handler, worldInfo);
@@ -332,7 +334,7 @@ public class FMLCommonHandler
public void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound)
{
if (getEffectiveSide()!=Side.SERVER)
if (getEffectiveSide()!=LogicalSide.SERVER)
{
return;
}
@@ -348,7 +350,7 @@ public class FMLCommonHandler
{
if (mc instanceof InjectedModContainer)
{
WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
WorldPersistenceHooks.WorldPersistenceHook wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer();
if (wac != null)
{
wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(mc.getModId()));
@@ -564,7 +566,7 @@ public class FMLCommonHandler
if (!shouldAllowPlayerLogins())
{
TextComponentString text = new TextComponentString("Server is still starting! Please wait before reconnecting.");
FMLLog.log.info("Disconnecting Player: {}", text.getUnformattedText());
LOGGER.info("Disconnecting Player: {}", text.getUnformattedText());
manager.sendPacket(new SPacketDisconnect(text));
manager.closeChannel(text);
return false;
@@ -1,227 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.security.cert.Certificate;
import java.util.Arrays;
import java.util.Map;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ResourceLocation;
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.ForgeRegistries;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.RegistryManager;
import org.apache.logging.log4j.LogManager;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
/**
* @author cpw
*
*/
public final class FMLContainer extends DummyModContainer implements WorldAccessContainer
{
private static final Logger modTrackerLogger = LogManager.getLogger("FML.ModTracker");
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.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 all Forge/Vanilla registries {invoke the static init)
if (ForgeRegistries.ITEMS == null)
throw new RuntimeException("Something horrible went wrong in init, ForgeRegistres didn't create...");
}
@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("LoadingModList", modList);
NBTTagCompound registries = new NBTTagCompound();
fmlData.setTag("Registries", registries);
FMLLog.log.debug("Gathering id map for writing to world save {}", info.getWorldName());
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
{
registries.setTag(e.getKey().toString(), e.getValue().write());
}
return fmlData;
}
@Override
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag)
{
if (tag.hasKey("LoadingModList"))
{
NBTTagList modList = tag.getTagList("LoadingModList", (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)
{
modTrackerLogger.error("This world was saved with mod {} which appears to be missing, things may not work well", modId);
continue;
}
if (!modVersion.equals(container.getVersion()))
{
modTrackerLogger.info("This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, container.getVersion());
}
}
}
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
if (tag.hasKey("ModItemData") || tag.hasKey("ItemData")) // Pre 1.7
{
StartupQuery.notify("This save predates 1.7.10, it can no longer be loaded here. Please load in 1.7.10 or 1.8 first");
StartupQuery.abort();
}
else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list
{
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = Maps.newHashMap();
NBTTagCompound regs = tag.getCompoundTag("Registries");
for (String key : regs.getKeySet())
{
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompoundTag(key)));
}
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
if (failedElements != null && !failedElements.isEmpty())
{
StringBuilder buf = new StringBuilder();
buf.append("Forge Mod Loader could not load this save.\n\n")
.append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n")
.append("You will not be able to load until they are present again.\n\n");
failedElements.asMap().forEach((name, entries) ->
{
buf.append("Missing ").append(name).append(":\n");
entries.forEach(rl -> buf.append(" ").append(rl).append("\n"));
});
StartupQuery.notify(buf.toString());
StartupQuery.abort();
}
}
@Override
@Nullable
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;
}
}
@@ -19,12 +19,15 @@
package net.minecraftforge.fml.common;
import java.util.Locale;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.FMLRelaunchLog;
import net.minecraftforge.api.distmarker.Dist;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
/**
* FMLs logging class. <b>Internal use only, NOT FOR MOD LOGGING!</b> Mods use your own log, see {@link FMLPreInitializationEvent#getModLog()}.
@@ -30,7 +30,7 @@ import net.minecraft.util.IThreadListener;
import net.minecraftforge.common.util.CompoundDataFixer;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.StartupQuery;
public interface IFMLSidedHandler
{
@@ -1,216 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
public interface ILanguageAdapter {
Object getNewInstance(FMLModContainer container, Class<?> objectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception;
boolean supportsStatics();
void setProxy(Field target, Class<?> proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException;
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.info("An error occurred trying to load a proxy into {}.{}. Did you declare your mod as 'class' instead of 'object'?", proxyTarget.getSimpleName(), target.getName(), e);
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.error("An error occurred trying to load a proxy into {}.{}", target.getName(), e);
throw new LoaderException(e);
}
// If we come here we could not find a setter for this proxy.
FMLLog.log.fatal("Failed loading proxy into {}.{}, 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.log.fatal("Attempted to load a proxy type {} into {}.{}, 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.error("An error occurred trying to load a proxy into {}.{}", target.getName(), e);
throw new LoaderException(e);
}
}
}
}
else
{
FMLLog.log.trace("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.
}
}
}
@@ -29,7 +29,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.minecraftforge.common.util.TextTable;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.common.ProgressManager.ProgressBar;
import net.minecraftforge.fml.common.event.ModLifecycleEvent;
import net.minecraftforge.fml.common.event.FMLLoadEvent;
@@ -41,14 +41,9 @@ import net.minecraftforge.common.ForgeVersion;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModContainer.Disableable;
import net.minecraftforge.fml.common.ProgressManager.ProgressBar;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ContainerType;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.ModDiscoverer;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLLoadEvent;
import net.minecraftforge.fml.common.event.FMLModIdMappingEvent;
@@ -60,11 +55,8 @@ import net.minecraftforge.fml.common.toposort.ModSortingException.SortingExcepti
import net.minecraftforge.fml.common.versioning.ArtifactVersion;
import net.minecraftforge.fml.common.versioning.DependencyParser;
import net.minecraftforge.fml.common.versioning.VersionParser;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.libraries.Artifact;
import net.minecraftforge.fml.relauncher.libraries.LibraryManager;
import net.minecraftforge.fml.relauncher.libraries.Repository;
import net.minecraftforge.fml.relauncher.ModListHelper;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.ObjectHolderRegistry;
@@ -1,138 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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 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;
/**
* 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 (ReflectiveOperationException e)
{
throw new RuntimeException(e);
}
}
public LoaderState requiredState()
{
if (this == NOINIT) return NOINIT;
return LoaderState.values()[this.ordinal()-1];
}
public String getPrettyName()
{
return name;
}
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;
}
}
}
@@ -24,7 +24,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.common.event.ModLifecycleEvent;
import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
@@ -108,7 +108,7 @@ public @interface Mod
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface EventBusSubscriber {
Side[] value() default { Side.CLIENT, Side.SERVER };
Dist[] value() default { Dist.CLIENT, Dist.DEDICATED_SERVER };
/**
* Optional value, only nessasary if tis annotation is not on the same class that has a @Mod annotation.
@@ -32,10 +32,6 @@ 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;
import com.google.common.collect.Lists;
@@ -1,90 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.lang.reflect.Constructor;
import java.util.Map;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import net.minecraftforge.fml.javafmlmod.FMLModContainer;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation;
import org.objectweb.asm.Type;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
public class ModContainerFactory
{
public static Map<Type, Constructor<? extends ModContainer>> modTypes = Maps.newHashMap();
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)
{
throw new RuntimeException("Critical error : cannot register mod container type " + container.getName() + ", it has an invalid constructor", e);
}
}
@Nullable
public ModContainer build(ASMModParser modParser, File modSource, ModCandidate container)
{
String className = modParser.getASMType().getClassName();
for (ModAnnotation ann : modParser.getAnnotations())
{
if (modTypes.containsKey(ann.getASMType()))
{
FMLLog.log.debug("Identified a mod of type {} ({}) - loading", ann.getASMType(), className);
try {
ModContainer ret = modTypes.get(ann.getASMType()).newInstance(className, container, ann.getValues());
if (!ret.shouldLoadInEnvironment())
{
FMLLog.log.debug("Skipping mod {}, container opted to not load.", className);
return null;
}
return ret;
} catch (Exception e) {
FMLLog.log.error("Unable to construct {} container", ann.getASMType().getClassName(), e);
return null;
}
}
}
return null;
}
}
@@ -1,94 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.List;
import java.util.Set;
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;
import net.minecraftforge.fml.ModContainer;
/**
* @author cpw
*
*/
public class ModMetadata
{
@SerializedName("modid")
public String modId;
public String name;
public String description = "";
public String url = "";
@Deprecated //Never really used for anything and format is undefined. See updateJSON for replacement.
public String updateUrl = "";
/**
* URL to update json file. Format is defined here: https://gist.github.com/LexManos/7aacb9aa991330523884
*/
public String updateJSON = "";
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(childMods.stream().map(ModContainer::getName).iterator());
}
public String printableSortingRules()
{
return "";
}
}
@@ -21,13 +21,11 @@ package net.minecraftforge.fml.common;
import java.util.Arrays;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.asm.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.
*
@@ -26,7 +26,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.SidedExecutor;
import net.minecraftforge.fml.SidedProvider;
import net.minecraftforge.fml.client.SplashProgress;
@@ -62,7 +62,7 @@ public class ProgressManager
{
bar.timeEachStep();
}
SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages);
SidedExecutor.runOn(Dist.CLIENT, ()->SplashProgress::processMessages);
return bar;
}
@@ -87,7 +87,7 @@ public class ProgressManager
else
fmlLog.debug(SPLASH, () -> new MessageFormatMessage("Bar Finished: {0} took {1,number,0.000}ms", bar.getTitle(), (newTime - bar.lastTime) / 1.0e6));
}
SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages);
SidedExecutor.runOn(Dist.CLIENT, ()->SplashProgress::processMessages);
}
/*
@@ -1,108 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.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.ModContainer;
import net.minecraftforge.fml.relauncher.Side;
import com.google.common.base.Strings;
import com.google.common.collect.SetMultimap;
/**
* @author cpw
*
*/
public class ProxyInjector
{
public static void inject(ModContainer mod, ASMDataTable data, Side side, ILanguageAdapter languageAdapter)
{
FMLLog.log.debug("Attempting to inject @SidedProxy classes into {}", mod.getModId());
SetMultimap<String, ASMData> modData = data.getAnnotationsFor(mod);
Set<ASMData> mods = modData.get(Mod.class.getName());
Set<ASMData> targets = modData.get(SidedProxy.class.getName());
ClassLoader mcl = Loader.instance().getModClassLoader();
for (ASMData targ : targets)
{
try
{
String amodid = (String)targ.getAnnotationInfo().get("modId");
if (Strings.isNullOrEmpty(amodid))
{
amodid = ASMDataTable.getOwnerModID(mods, targ);
if (Strings.isNullOrEmpty(amodid))
{
FMLLog.bigWarning("Could not determine owning mod for @SidedProxy on {} for mod {}", targ.getClassName(), mod.getModId());
continue;
}
}
if (!mod.getModId().equals(amodid))
{
FMLLog.log.debug("Skipping proxy injection for {}.{} since it is not for mod {}", targ.getClassName(), targ.getObjectName(), mod.getModId());
continue;
}
Class<?> proxyTarget = Class.forName(targ.getClassName(), true, mcl);
Field target = proxyTarget.getDeclaredField(targ.getObjectName());
if (target == null)
{
// Impossible?
FMLLog.log.fatal("Attempted to load a proxy type into {}.{} 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);
String targetType = side.isClient() ? annotation.clientSide() : annotation.serverSide();
if(targetType.equals(""))
{
targetType = targ.getClassName() + (side.isClient() ? "$ClientProxy" : "$ServerProxy");
}
Object proxy=Class.forName(targetType, true, mcl).newInstance();
if (languageAdapter.supportsStatics() && (target.getModifiers() & Modifier.STATIC) == 0 )
{
FMLLog.log.fatal("Attempted to load a proxy type {} into {}.{}, 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.log.fatal("Attempted to load a proxy type {} into {}.{}, 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.error("An error occurred trying to load a proxy into {}.{}", targ.getObjectName(), e);
throw new LoaderException(e);
}
}
// Allow language specific proxy injection.
languageAdapter.setInternalProxies(mod, side, mcl);
}
}
@@ -1,76 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.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 full name of the client side class to load and populate.
* Defaults to the nested class named "ClientProxy" in the current class.
*/
String clientSide() default "";
/**
* The full name of the server side class to load and populate.
* Defaults to the nested class named "ServerProxy" in the current class.
*/
String serverSide() default "";
/**
* The name of a mod to load this proxy for. This is required if this annotation is not in the class with @Mod annotation.
* Or there is no other way to determine the mod this annotation belongs to. When in doubt, add this value.
*/
String modId() default "";
}
@@ -1,183 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import net.minecraft.server.MinecraftServer;
import javax.annotation.Nullable;
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.log.warn("query interrupted");
abort();
}
pending = null;
}
return !aborted;
}
private static volatile StartupQuery pending;
private static volatile boolean aborted = false;
private StartupQuery(String text, @Nullable AtomicBoolean result)
{
this.text = text;
this.result = result;
}
@Nullable
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.log.info("Using fml.queryResult {} to answer the following query:\n{}", prop, text);
if (prop.equalsIgnoreCase("confirm"))
{
setResult(true);
return;
}
else if (prop.equalsIgnoreCase("cancel"))
{
setResult(false);
return;
}
FMLLog.log.warn("Invalid value for fml.queryResult: {}, 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.log.warn("query interrupted");
abort();
}
}
private String text;
@Nullable
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();
}
}
}
@@ -17,12 +17,12 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
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 net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.asm.deobf.FMLRemappingAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
@@ -34,7 +34,7 @@ public class DeobfuscationTransformer implements IClassTransformer, IClassNameTr
private static final int WRITER_FLAGS = ClassWriter.COMPUTE_MAXS | (RECALC_FRAMES ? ClassWriter.COMPUTE_FRAMES : 0);
private static final int READER_FLAGS = RECALC_FRAMES ? ClassReader.SKIP_FRAMES : ClassReader.EXPAND_FRAMES;
// COMPUTE_FRAMES causes classes to be loaded, which could cause issues if the classes do not exist.
// However in testing this has not happened. {As we run post SideTransformer}
// However in testing this has not happened. {As we run post RuntimeDistCleaner}
// If reported we need to add a custom implementation of ClassWriter.getCommonSuperClass
// that does not cause class loading.
@@ -35,11 +35,9 @@ import org.apache.commons.io.IOUtils;
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.asm.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.patcher.ClassPatchManager;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.IFMLCallHook;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import com.google.common.io.ByteStreams;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
import java.util.ListIterator;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
public class ItemBlockSpecialTransformer extends FieldRedirectTransformer
{
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
public class ItemBlockTransformer extends FieldRedirectTransformer
{
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
public class ItemStackTransformer extends FieldRedirectTransformer
{
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers;
package net.minecraftforge.fml.common.asm;
import org.objectweb.asm.*;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers.deobf;
package net.minecraftforge.fml.common.asm.deobf;
import java.io.File;
import java.io.FileInputStream;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers.deobf;
package net.minecraftforge.fml.common.asm.deobf;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
@@ -17,7 +17,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common.asm.transformers.deobf;
package net.minecraftforge.fml.common.asm.deobf;
import java.io.IOException;
import java.io.InputStream;
@@ -1,485 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.asm.transformers;
import net.minecraftforge.fml.common.FMLLog;
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.nio.charset.StandardCharsets;
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 org.apache.commons.io.IOUtils;
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.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("forge_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, StandardCharsets.UTF_8));
FMLLog.log.debug("Loaded {} rules from AccessTransformer config file {}", 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) FMLLog.log.debug("AT RULE: {} {} {} (type {})", 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 (!modifiers.containsKey(transformedName)) { return bytes; }
if (DEBUG)
{
FMLLog.log.debug("Considering all methods and fields on {} ({})", transformedName, name);
}
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)
{
FMLLog.log.debug("Class: {} {} -> {}", 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)
{
FMLLog.log.debug("Field: {}.{} {} -> {}", name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
else
{
List<MethodNode> nowOverrideable = 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)
{
nowOverrideable.add(n);
}
}
if (DEBUG)
{
FMLLog.log.debug("Method: {}.{}{} {} -> {}", name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess));
}
if (!m.name.equals("*"))
{
break;
}
}
}
replaceInvokeSpecial(classNode, nowOverrideable);
}
}
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("Could 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
{
IOUtils.closeQuietly(outJar);
IOUtils.closeQuietly(inJar);
}
}
Multimap<String, Modifier> getModifiers()
{
return modifiers;
}
boolean isEmpty()
{
return modifiers.isEmpty();
}
}
@@ -1,93 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.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 @SubscribeEvent 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;");
}
}
}
@@ -1,242 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.asm.transformers;
import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PROTECTED;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.F_SAME;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.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 net.minecraft.launchwrapper.IClassTransformer;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.eventbus.api.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)
{
FMLLog.log.error("Error building events.", e);
}
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 (!net.minecraftforge.eventbus.api.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 : 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 initListener = new LabelNode();
method.instructions.add(new JumpInsnNode(IFNULL, initListener));
method.instructions.add(new InsnNode(RETURN));
method.instructions.add(initListener);
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;
}
}
@@ -1,210 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.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.FMLLog;
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 org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureWriter;
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) FMLLog.log.trace("Optional removal - found optionals for class {} - 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) FMLLog.log.trace("Optional removal skipped - mod present {}", modId);
continue;
}
if (logDebugInfo) FMLLog.log.trace("Optional on {} triggered - mod missing {}", 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, optional.getObjectName());
}
}
if (logDebugInfo) FMLLog.log.trace("Optional removal - class {} 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) FMLLog.log.debug("Optional removal - method {} removed", methodDescriptor);
return;
}
}
if (logDebugInfo) FMLLog.log.debug("Optional removal - method {} NOT removed - not found", methodDescriptor);
}
private void stripInterface(ClassNode classNode, String interfaceName, boolean stripRefs)
{
final String ifaceName = interfaceName.replace('.', '/');
boolean found = classNode.interfaces.remove(ifaceName);
if (found && classNode.signature != null)
{
SignatureReader sr = new SignatureReader(classNode.signature);
final RemovingSignatureWriter signatureWriter = new RemovingSignatureWriter(ifaceName);
sr.accept(signatureWriter);
classNode.signature = signatureWriter.toString();
if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} removed from type signature", interfaceName);
}
if (found && logDebugInfo) FMLLog.log.debug("Optional removal - interface {} removed", interfaceName);
if (!found && logDebugInfo) FMLLog.log.debug("Optional removal - interface {} NOT removed - not found", interfaceName);
if (found && stripRefs)
{
if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - 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) FMLLog.log.debug("Optional removal - interface {} - stripping method containing reference {}", interfaceName, node.name);
iterator.remove();
}
}
if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - all method signature references stripped", interfaceName);
}
else if (found)
{
if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - 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);
}
}
private static class RemovingSignatureWriter extends SignatureWriter
{
private final String ifaceName;
RemovingSignatureWriter(String ifaceName)
{
this.ifaceName = ifaceName;
}
@Override
public void visitClassType(String name)
{
if (name.equals(ifaceName)) {
super.visitClassType("java/lang/Object");
}
else
{
super.visitClassType(name);
}
}
}
}
@@ -1,91 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.asm.transformers;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.minecraftforge.fml.common.FMLLog;
import com.google.common.collect.Maps;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
public class ModAccessTransformer extends AccessTransformer
{
public static final Attributes.Name FMLAT = new Attributes.Name("FMLAT");
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)
{
FMLLog.log.debug("Loaded {} rules from AccessTransformer mod jar file {}\n", added, e.getKey());
}
}
}
public static void addJar(JarFile jar, String atList) throws IOException
{
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(StandardCharsets.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);
}
}
}
@@ -1,166 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
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;
import net.minecraftforge.fml.ModContainer;
public class ASMDataTable
{
public final static class ASMData implements Cloneable
{
private ModCandidate candidate;
private String annotationName;
private String className;
private String objectName;
private int classVersion;
private Map<String,Object> annotationInfo;
public ASMData(ModCandidate candidate, String annotationName, String className, @Nullable String objectName, @Nullable 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.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, @Nullable String objectName, @Nullable 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);
}
@Nullable
public static String getOwnerModID(Set<ASMData> mods, ASMData targ)
{
if (mods.size() == 1) {
return (String)mods.iterator().next().getAnnotationInfo().get("modid");
} else {
for (ASMData m : mods) {
if (targ.getClassName().startsWith(m.getClassName())) {
return (String)m.getAnnotationInfo().get("modid");
}
}
}
return null;
}
}
@@ -1,49 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.util.List;
import net.minecraftforge.fml.ModContainer;
public enum ContainerType
{
JAR(JarDiscoverer.class),
DIR(DirectoryDiscoverer.class);
private ITypeDiscoverer discoverer;
private ContainerType(Class<? extends ITypeDiscoverer> discovererClass)
{
try
{
this.discoverer = discovererClass.newInstance();
}
catch (ReflectiveOperationException e)
{
throw new RuntimeException(e);
}
}
public List<ModContainer> findMods(ModCandidate candidate, ASMDataTable table)
{
return discoverer.discover(candidate, table);
}
}
@@ -1,147 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
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.ModContainer;
import net.minecraftforge.fml.common.ModContainerFactory;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import org.apache.commons.io.IOUtils;
import com.google.common.collect.Lists;
import javax.annotation.Nullable;
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.log.debug("Examining directory {} 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, @Nullable MetadataCollection mc)
{
if (path.length() == 0)
{
File metadata = new File(modDir, "mcmod.info");
try
{
FileInputStream fis = new FileInputStream(metadata);
try
{
mc = MetadataCollection.from(fis, modDir.getName());
}
finally
{
IOUtils.closeQuietly(fis);
}
FMLLog.log.debug("Found an mcmod.info file in directory {}", modDir.getName());
}
catch (Exception e)
{
mc = MetadataCollection.from(null,"");
FMLLog.log.debug("No mcmod.info file found in directory {}", modDir.getName());
}
}
File[] content = modDir.listFiles(new ClassFilter());
// Always sort our content
Arrays.sort(content);
for (File file : content)
{
if (file.isDirectory())
{
FMLLog.log.trace("Recursing into package {}", path + file.getName());
exploreFileSystem(path + file.getName() + "/", file, harvestedMods, candidate, mc);
continue;
}
Matcher match = classFile.matcher(file.getName());
if (match.matches())
{
ASMModParser modParser = null;
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
modParser = new ASMModParser(fis);
candidate.addClassEntry(path+file.getName());
}
catch (LoaderException e)
{
FMLLog.log.error("There was a problem reading the file {} - probably this is a corrupt file", file.getPath(), e);
throw e;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
IOUtils.closeQuietly(fis);
}
modParser.validate();
modParser.sendToTable(table, candidate);
ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate);
if (container!=null)
{
harvestedMods.add(container);
container.bindMetadata(mc);
}
}
}
}
}
@@ -1,168 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
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.ModContainer;
import net.minecraftforge.fml.common.ModContainerFactory;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.discovery.asm.ASMModParser;
import net.minecraftforge.fml.common.discovery.json.JsonAnnotationLoader;
import java.util.regex.Matcher;
import java.util.zip.ZipEntry;
import org.objectweb.asm.Type;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
public class JarDiscoverer implements ITypeDiscoverer
{
private static final boolean ENABLE_JSON_TEST = "true".equals(System.getProperty("fml.enableJsonAnnotations", "false"));
@Override
public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table)
{
List<ModContainer> foundMods = Lists.newArrayList();
FMLLog.log.debug("Examining file {} for potential mods", candidate.getModContainer().getName());
try (JarFile jar = new JarFile(candidate.getModContainer()))
{
ZipEntry modInfo = jar.getEntry("mcmod.info");
MetadataCollection mc = null;
if (modInfo != null)
{
FMLLog.log.trace("Located mcmod.info file in file {}", candidate.getModContainer().getName());
try (InputStream inputStream = jar.getInputStream(modInfo))
{
mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName());
}
}
else
{
FMLLog.log.debug("The mod container {} appears to be missing an mcmod.info file", candidate.getModContainer().getName());
mc = MetadataCollection.from(null, "");
}
if (ENABLE_JSON_TEST && jar.getEntry(JsonAnnotationLoader.ANNOTATION_JSON) != null)
findClassesJSON(candidate, table, jar, foundMods, mc);
else
findClassesASM(candidate, table, jar, foundMods, mc);
}
catch (Exception e)
{
FMLLog.log.warn("Zip file {} failed to read properly, it will be ignored", candidate.getModContainer().getName(), e);
}
return foundMods;
}
private void findClassesASM(ModCandidate candidate, ASMDataTable table, JarFile jar, List<ModContainer> foundMods, MetadataCollection mc) throws IOException
{
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
{
try (InputStream inputStream = jar.getInputStream(ze))
{
modParser = new ASMModParser(inputStream);
}
candidate.addClassEntry(ze.getName());
}
catch (LoaderException e)
{
FMLLog.log.error("There was a problem reading the entry {} in the jar {} - probably a corrupt zip", candidate.getModContainer().getPath(), e);
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);
container.setClassVersion(modParser.getClassVersion());
}
}
}
}
private void findClassesJSON(ModCandidate candidate, ASMDataTable table, JarFile jar, List<ModContainer> foundMods, MetadataCollection mc) throws IOException
{
FMLLog.log.info("Loading jar {} annotation data from json", candidate.getModContainer().getPath());
ZipEntry json = jar.getEntry(JsonAnnotationLoader.ANNOTATION_JSON);
Multimap<String, ASMData> annos = JsonAnnotationLoader.loadJson(jar.getInputStream(json), candidate, table);
for (ZipEntry e : Collections.list(jar.entries()))
{
if (!e.getName().startsWith("__MACOSX") && !e.getName().startsWith("META-INF/") && e.getName().endsWith(".class"))
{
candidate.addClassEntry(e.getName());
}
}
for (Entry<Type, Constructor<? extends ModContainer>> entry : ModContainerFactory.modTypes.entrySet())
{
Type type = entry.getKey();
Constructor<? extends ModContainer> ctr = entry.getValue();
for (ASMData data : annos.get(type.getClassName()))
{
FMLLog.log.debug("Identified a mod of type {} ({}) - loading", type.getClassName(), data.getClassName());
try
{
ModContainer ret = ctr.newInstance(data.getClassName(), candidate, data.getAnnotationInfo());
if (!ret.shouldLoadInEnvironment())
FMLLog.log.debug("Skipping mod {}, container opted to not load.", data.getClassName());
else
{
table.addContainer(ret);
foundMods.add(ret);
ret.bindMetadata(mc);
//ret.setClassVersion(classVersion); // Not really needed anymore as we're forcing J8. Maybe think of reinstating for J9 support? After LaunchWraper re-do.
}
}
catch (Exception e)
{
FMLLog.log.error("Unable to construct {} container", data.getClassName(), e);
}
}
}
}
}
@@ -1,112 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.io.File;
import java.util.List;
import java.util.Set;
import net.minecraftforge.fml.ModContainer;
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 boolean isMinecraft;
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);
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 boolean isMinecraftJar()
{
return isMinecraft;
}
public Set<String> getClassList()
{
return foundClasses;
}
public List<ModContainer> getContainedMods()
{
return mods;
}
public List<String> getContainedPackages()
{
return packages;
}
}
@@ -1,134 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery;
import java.io.File;
import java.util.List;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.common.ModClassLoader;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.relauncher.CoreModManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class ModDiscoverer
{
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.getIgnoredMods())
// skip reparse coremods here
.addAll(CoreModManager.getReparseableCoremods())
.build();
File[] minecraftSources = modClassLoader.getParentSources();
if (minecraftSources.length == 1 && minecraftSources[0].isFile())
{
FMLLog.log.debug("Minecraft is a file at {}, 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.log.trace("Skipping known library file {}", source.getAbsolutePath());
}
else
{
FMLLog.log.debug("Found a minecraft related file at {}, examining for mod candidates", source.getAbsolutePath());
addCandidate(new ModCandidate(source, source, ContainerType.JAR, i==0, true));
}
}
else if (minecraftSources[i].isDirectory())
{
FMLLog.log.debug("Found a minecraft related directory at {}, examining for mod candidates", source.getAbsolutePath());
addCandidate(new ModCandidate(source, source, ContainerType.DIR, i==0, true));
}
i++;
}
}
}
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.warn("Identified a problem with the mod candidate {}, ignoring this source", candidate.getModContainer(), le);
}
}
return modList;
}
public ASMDataTable getASMTable()
{
return dataTable;
}
public List<File> getNonModLibs()
{
return nonModLibs;
}
public void addCandidate(ModCandidate candidate)
{
for (ModCandidate c : candidates)
{
if (c.getModContainer().equals(candidate.getModContainer()))
{
FMLLog.log.trace(" Skipping already in list {}", candidate.getModContainer());
return;
}
}
candidates.add(candidate);
}
}
@@ -1,179 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.discovery.asm;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Set;
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 net.minecraftforge.fml.loading.moddiscovery.ModAnnotation;
import net.minecraftforge.fml.loading.moddiscovery.ModClassVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class ASMModParser
{
private Type asmType;
private int classVersion;
private Type asmSuperType;
private LinkedList<ModAnnotation> annotations = Lists.newLinkedList();
private Set<String> interfaces = Sets.newHashSet();
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.error("Unable to read a class file correctly", ex);
throw new LoaderException(ex);
}
}
public void beginNewTypeName(String typeQName, int classVersion, String superClassQName, String[] interfaces)
{
this.asmType = Type.getObjectType(typeQName);
this.classVersion = classVersion;
this.asmSuperType = !Strings.isNullOrEmpty(superClassQName) ? Type.getObjectType(superClassQName) : null;
for (String intf : interfaces)
this.interfaces.add(intf);
}
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 MoreObjects.toStringHelper("ASMAnnotationDiscoverer")
.add("className", asmType.getClassName())
.add("classVersion", classVersion)
.add("superName", asmSuperType.getClassName())
.add("annotations", annotations)
.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()
{
}
public void sendToTable(ASMDataTable table, ModCandidate candidate)
{
for (ModAnnotation ma : annotations)
{
table.addASMData(candidate, ma.asmType.getClassName(), this.asmType.getClassName(), ma.member, ma.values);
}
for (String intf : interfaces)
{
table.addASMData(candidate, intf, this.asmType.getInternalName(), null, null);
}
}
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);
}
}
@@ -33,9 +33,6 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.discovery.ModCandidate;
import net.minecraftforge.fml.common.discovery.json.ASMInfo.Annotation;
import net.minecraftforge.fml.common.discovery.json.ASMInfo.TargetType;
@@ -28,8 +28,6 @@ import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModThreadContext;
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.ModContainer;
import net.minecraftforge.fml.common.Mod.Instance;
@@ -379,11 +377,11 @@ public class FMLInterModComms {
private static boolean enqueueStartupMessage(String modTarget, IMCMessage message)
{
if (ModThreadContext.get().getCurrentContainer() == null)
if (ModThreadContext.get().getActiveContainer() == null)
{
return false;
}
enqueueMessage(ModThreadContext.get().getCurrentContainer(), modTarget, message);
enqueueMessage(ModThreadContext.get().getActiveContainer(), modTarget, message);
return ModList.get().isLoaded(modTarget);
}
@@ -20,7 +20,6 @@
package net.minecraftforge.fml.common.event;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.ModMetadata;
/**
* Called before {@link FMLInitializationEvent} during mod startup.
@@ -20,7 +20,6 @@
package net.minecraftforge.fml.common.event;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.LoaderState.ModState;
/**
* Called before the server begins loading anything. Called after {@link FMLPostInitializationEvent} on the dedicated
@@ -32,17 +31,11 @@ import net.minecraftforge.fml.common.LoaderState.ModState;
*/
public class FMLServerAboutToStartEvent extends FMLStateEvent {
private MinecraftServer server;
private final MinecraftServer server;
public FMLServerAboutToStartEvent(Object... data)
public FMLServerAboutToStartEvent(MinecraftServer server)
{
super(data);
this.server = (MinecraftServer) data[0];
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
this.server = (MinecraftServer) server;
}
public MinecraftServer getServer()
@@ -19,8 +19,6 @@
package net.minecraftforge.fml.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
/**
* Called after {@link FMLServerStartingEvent} when the server is available and ready to play.
*
@@ -30,15 +28,7 @@ import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStartedEvent extends FMLStateEvent
{
public FMLServerStartedEvent(Object... data)
public FMLServerStartedEvent()
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -22,7 +22,6 @@ 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;
/**
* Called after {@link FMLServerAboutToStartEvent} and before {@link FMLServerStartedEvent}.
@@ -35,17 +34,11 @@ import net.minecraftforge.fml.common.LoaderState.ModState;
public class FMLServerStartingEvent extends FMLStateEvent
{
private MinecraftServer server;
private final MinecraftServer server;
public FMLServerStartingEvent(Object... data)
public FMLServerStartingEvent(final MinecraftServer server)
{
super(data);
this.server = (MinecraftServer) data[0];
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
this.server = (MinecraftServer) server;
}
public MinecraftServer getServer()
@@ -19,8 +19,6 @@
package net.minecraftforge.fml.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
/**
* Called after {@link FMLServerStoppingEvent} when the server has completely shut down.
* Called immediately before shutting down, on the dedicated server, and before returning
@@ -30,15 +28,4 @@ import net.minecraftforge.fml.common.LoaderState.ModState;
* @author cpw
*/
public class FMLServerStoppedEvent extends FMLStateEvent {
public FMLServerStoppedEvent(Object... data)
{
super(data);
}
@Override
public ModState getModState()
{
return ModState.AVAILABLE;
}
}
@@ -19,8 +19,6 @@
package net.minecraftforge.fml.common.event;
import net.minecraftforge.fml.common.LoaderState.ModState;
/**
* Called when the server begins an orderly shutdown, before {@link FMLServerStoppedEvent}.
*
@@ -29,16 +27,4 @@ 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;
}
}
@@ -20,7 +20,7 @@
package net.minecraftforge.fml.common.event;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
/**
* The parent of all mod-state changing events
@@ -22,8 +22,8 @@ package net.minecraftforge.fml.common.gameevent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.LogicalSide;
public class TickEvent extends net.minecraftforge.eventbus.api.Event
{
@@ -35,9 +35,9 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event
START, END;
}
public final Type type;
public final Side side;
public final LogicalSide side;
public final Phase phase;
public TickEvent(Type type, Side side, Phase phase)
public TickEvent(Type type, LogicalSide side, Phase phase)
{
this.type = type;
this.side = side;
@@ -47,20 +47,20 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event
public static class ServerTickEvent extends TickEvent {
public ServerTickEvent(Phase phase)
{
super(Type.SERVER, Side.SERVER, phase);
super(Type.SERVER, LogicalSide.SERVER, phase);
}
}
public static class ClientTickEvent extends TickEvent {
public ClientTickEvent(Phase phase)
{
super(Type.CLIENT, Side.CLIENT, phase);
super(Type.CLIENT, LogicalSide.CLIENT, phase);
}
}
public static class WorldTickEvent extends TickEvent {
public final World world;
public WorldTickEvent(Side side, Phase phase, World world)
public WorldTickEvent(LogicalSide side, Phase phase, World world)
{
super(Type.WORLD, side, phase);
this.world = world;
@@ -71,7 +71,7 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event
public PlayerTickEvent(Phase phase, EntityPlayer player)
{
super(Type.PLAYER, player instanceof EntityPlayerMP ? Side.SERVER : Side.CLIENT, phase);
super(Type.PLAYER, player instanceof EntityPlayerMP ? LogicalSide.SERVER : LogicalSide.CLIENT, phase);
this.player = player;
}
}
@@ -80,7 +80,7 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event
public final float renderTickTime;
public RenderTickEvent(Phase phase, float renderTickTime)
{
super(Type.RENDER, Side.CLIENT, phase);
super(Type.RENDER, LogicalSide.CLIENT, phase);
this.renderTickTime = renderTickTime;
}
}
@@ -1,82 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.launcher;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.relauncher.CoreModManager;
import net.minecraftforge.fml.relauncher.FMLInjectionData;
public class FMLDeobfTweaker implements ITweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
// Deobfuscation transformer, always last, and the access transformer tweaker as well
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.DeobfuscationTransformer");
// Add all the access transformers now as well
for (String transformer : CoreModManager.getAccessTransformers())
{
classLoader.registerTransformer(transformer);
}
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ModAccessTransformer");
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemStackTransformer");
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockTransformer");
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockSpecialTransformer");
try
{
FMLLog.log.debug("Validating minecraft");
Class<?> loaderClazz = Class.forName("net.minecraftforge.fml.common.Loader", true, classLoader);
Method m = loaderClazz.getMethod("injectData", Object[].class);
m.invoke(null, (Object)FMLInjectionData.data());
m = loaderClazz.getMethod("instance");
m.invoke(null);
FMLLog.log.debug("Minecraft validated, launching...");
}
catch (Exception e)
{
// Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here
FMLLog.log.fatal("A CRITICAL PROBLEM OCCURRED INITIALIZING MINECRAFT - LIKELY YOU HAVE AN INCORRECT VERSION FOR THIS FML");
throw new RuntimeException(e);
}
}
@Override
public String getLaunchTarget()
{
throw new RuntimeException("Invalid for use as a primary tweaker");
}
@Override
public String[] getLaunchArguments()
{
return new String[0];
}
}
@@ -1,76 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.launcher;
import java.io.File;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.CoreModManager;
/**
* This class is to manage the injection of coremods as tweakers into the tweak framework.
* It has to inject the coremod tweaks during construction, because that is the only time
* the tweak list is writeable.
* @author cpw
*
*/
public class FMLInjectionAndSortingTweaker implements ITweaker {
private boolean run;
public FMLInjectionAndSortingTweaker()
{
CoreModManager.injectCoreModTweaks(this);
run = false;
}
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
if (!run)
{
// We sort the tweak list here so that it obeys the tweakordering
CoreModManager.sortTweakList();
@SuppressWarnings("unchecked")
List<String> newTweaks = (List<String>) Launch.blackboard.get("TweakClasses");
newTweaks.add("net.minecraftforge.fml.common.launcher.TerminalTweaker");
}
run = true;
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
}
@Override
public String getLaunchTarget()
{
return "";
}
@Override
public String[] getLaunchArguments()
{
return new String[0];
}
}
@@ -1,65 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.launcher;
import java.io.File;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
public class FMLServerTweaker extends FMLTweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
super.acceptOptions(args, gameDir, assetsDir, profile);
if (System.getProperty("log4j.configurationFile") == null)
{
System.setProperty("log4j.configurationFile", "log4j2_server.xml");
((LoggerContext) LogManager.getContext(false)).reconfigure();
}
}
@Override
public String getLaunchTarget()
{
return "net.minecraft.server.MinecraftServer";
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
// The log4j2 queue is excluded so it is correctly visible from the obfuscated
// and deobfuscated parts of the code. Without, the UI won't show anything
classLoader.addClassLoaderExclusion("com.mojang.util.QueueLogAppender");
classLoader.addClassLoaderExclusion("org.jline.");
classLoader.addClassLoaderExclusion("com.sun.jna.");
classLoader.addClassLoaderExclusion("net.minecraftforge.server.terminalconsole.");
FMLLaunchHandler.configureForServerLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
}
@@ -1,182 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.launcher;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.FMLSecurityManager;
import org.apache.logging.log4j.LogManager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class FMLTweaker implements ITweaker {
private File gameDir;
private Map<String, String> launchArgs;
private List<String> standaloneArgs;
private static URI jarLocation;
public FMLTweaker()
{
if (System.getProperty("java.net.preferIPv4Stack") == null)
{
System.setProperty("java.net.preferIPv4Stack", "true");
}
try
{
System.setSecurityManager(new FMLSecurityManager());
}
catch (SecurityException se)
{
throw new RuntimeException("FML was unable to install the security manager. The game will not start", se);
}
}
@SuppressWarnings("unchecked")
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
this.gameDir = (gameDir == null ? new File(".") : gameDir);
this.launchArgs = (Map<String, String>)Launch.blackboard.get("launchArgs");
this.standaloneArgs = Lists.newArrayList();
if (this.launchArgs == null)
{
this.launchArgs = Maps.newHashMap();
Launch.blackboard.put("launchArgs", this.launchArgs);
}
String classifier = null;
for (String arg : args)
{
if (arg.startsWith("-"))
{
if (classifier != null)
{
classifier = launchArgs.put(classifier, "");
}
else if (arg.contains("="))
{
classifier = launchArgs.put(arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1));
}
else
{
classifier = arg;
}
}
else
{
if (classifier != null)
{
classifier = launchArgs.put(classifier, arg);
}
else
{
this.standaloneArgs.add(arg);
}
}
}
if (!this.launchArgs.containsKey("--version"))
{
launchArgs.put("--version", profile != null ? profile : "UnknownFMLProfile");
}
if (!this.launchArgs.containsKey("--gameDir") && gameDir != null)
{
launchArgs.put("--gameDir", gameDir.getAbsolutePath());
}
if (!this.launchArgs.containsKey("--assetsDir") && assetsDir != null)
{
launchArgs.put("--assetsDir", assetsDir.getAbsolutePath());
}
Yggdrasil.login(launchArgs);
try
{
jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
}
catch (URISyntaxException e)
{
LogManager.getLogger("FML.TWEAK").error("Missing URI information for FML tweak");
throw new RuntimeException(e);
}
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
FMLLaunchHandler.configureForClientLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
@Override
public String getLaunchTarget()
{
return "net.minecraft.client.main.Main";
}
@Override
public String[] getLaunchArguments()
{
List<String> args = Lists.newArrayList();
args.addAll(standaloneArgs);
for (Entry<String, String> arg : launchArgs.entrySet())
{
if ("--modListFile".equals(arg.getKey()) || "--mods".equals(arg.getKey()))
continue;
args.add(arg.getKey());
args.add(arg.getValue());
}
return args.toArray(new String[args.size()]);
}
public File getGameDir()
{
return gameDir;
}
public static URI getJarLocation()
{
return jarLocation;
}
public void injectCascadingTweak(String tweakClassName)
{
@SuppressWarnings("unchecked")
List<String> tweakClasses = (List<String>) Launch.blackboard.get("TweakClasses");
tweakClasses.add(tweakClassName);
}
}
@@ -1,51 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* 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 version 2.1
* of the License.
*
* 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.launcher;
import java.io.File;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
public final class TerminalTweaker implements ITweaker {
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.TerminalTransformer");
}
@Override
public String getLaunchTarget()
{
return null;
}
@Override
public String[] getLaunchArguments()
{
return new String[0];
}
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
}
}
@@ -25,14 +25,13 @@ import io.netty.channel.embedded.EmbeddedChannel;
import java.util.Map.Entry;
import net.minecraft.network.Packet;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModThreadContext;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.network.FMLOutboundHandler.OutboundTarget;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.javafmlmod.ModLoadingContext;
import javax.annotation.Nullable;
@@ -44,11 +43,11 @@ import javax.annotation.Nullable;
*
*/
public class FMLEmbeddedChannel extends EmbeddedChannel {
public FMLEmbeddedChannel(String channelName, Side source, ChannelHandler... handlers)
public FMLEmbeddedChannel(String channelName, LogicalSide source, ChannelHandler... handlers)
{
this(ModThreadContext.get().getCurrentContainer(), channelName, source, handlers);
this(ModThreadContext.get().getActiveContainer(), channelName, source, handlers);
}
public FMLEmbeddedChannel(ModContainer container, String channelName, Side source, ChannelHandler... handlers)
public FMLEmbeddedChannel(ModContainer container, String channelName, LogicalSide source, ChannelHandler... handlers)
{
super(handlers);
this.attr(NetworkRegistry.FML_CHANNEL).set(channelName);
@@ -32,7 +32,7 @@ import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import javax.annotation.Nullable;
@@ -29,7 +29,7 @@ import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
public class FMLNetworkEvent<T extends INetHandler> extends Event {
private final T handler;
@@ -42,7 +42,7 @@ import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -19,13 +19,13 @@
package net.minecraftforge.fml.common.network;
import net.minecraftforge.api.distmarker.Dist;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.minecraftforge.fml.relauncher.Side;
/**
* A method annotated with this will be called when a remote network connection is offered.
* The method should have two parameters, of types Map<String,String> and {@link Side}. It should return a boolean
@@ -21,7 +21,7 @@ package net.minecraftforge.fml.common.network;
import net.minecraft.network.INetHandler;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
/**
* This message is sent through all channels affected by a currently occurring handshake. It is guaranteed to
@@ -35,12 +35,11 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.network.INetHandler;
import net.minecraft.world.World;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.network.FMLOutboundHandler.OutboundTarget;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.common.network.internal.NetworkModHolder;
@@ -55,10 +54,10 @@ import javax.annotation.Nullable;
* @author cpw
*
*/
public enum NetworkRegistry
public class NetworkRegistry
{
INSTANCE;
private EnumMap<Side,Map<String,FMLEmbeddedChannel>> channels = Maps.newEnumMap(Side.class);
public static final NetworkRegistry INSTANCE = new NetworkRegistry();
private EnumMap<LogicalSide,Map<String,FMLEmbeddedChannel>> channels = Maps.newEnumMap(LogicalSide.class);
private Map<ModContainer, NetworkModHolder> registry = Maps.newHashMap();
private Map<ModContainer, IGuiHandler> serverGuiHandlers = Maps.newHashMap();
private Map<ModContainer, IGuiHandler> clientGuiHandlers = Maps.newHashMap();
@@ -67,10 +66,10 @@ public enum NetworkRegistry
* Set in the {@link ChannelHandlerContext}
*/
public static final AttributeKey<String> FML_CHANNEL = AttributeKey.valueOf("fml:channelName");
public static final AttributeKey<Side> CHANNEL_SOURCE = AttributeKey.valueOf("fml:channelSource");
public static final AttributeKey<LogicalSide> CHANNEL_SOURCE = AttributeKey.valueOf("fml:channelSource");
public static final AttributeKey<ModContainer> MOD_CONTAINER = AttributeKey.valueOf("fml:modContainer");
public static final AttributeKey<INetHandler> NET_HANDLER = AttributeKey.valueOf("fml:netHandler");
public static final AttributeKey<Boolean> FML_MARKER = AttributeKey.valueOf("fml:hasMarker");
public static final AttributeKey<String> FML_MARKER = AttributeKey.valueOf("fml:versionMarker");
// Version 1: ServerHello only contains this value as a byte
// Version 2: ServerHello additionally contains a 4 byte (int) dimension for the logging in client
@@ -78,8 +77,8 @@ public enum NetworkRegistry
private NetworkRegistry()
{
channels.put(Side.CLIENT, Maps.<String,FMLEmbeddedChannel>newConcurrentMap());
channels.put(Side.SERVER, Maps.<String,FMLEmbeddedChannel>newConcurrentMap());
channels.put(LogicalSide.CLIENT, Maps.<String,FMLEmbeddedChannel>newConcurrentMap());
channels.put(LogicalSide.SERVER, Maps.<String,FMLEmbeddedChannel>newConcurrentMap());
}
/**
@@ -123,8 +122,8 @@ public enum NetworkRegistry
* <li> Alternatively, simply use the netty features provided here and implement the full power of the netty stack.
* </ul>
*
* There are two channels created : one for each logical side (considered as the source of an outbound message)
* The returned map will contain a value for each logical side, though both will only be working in the
* There are two channels created : one for each logical Dist (conDistred as the source of an outbound message)
* The returned map will contain a value for each logical Dist, though both will only be working in the
* integrated server case.
*
* The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the
@@ -133,7 +132,7 @@ public enum NetworkRegistry
* The first handler in the pipeline is special and should not be removed or moved from the head - it transforms
* packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value
* {@link FMLOutboundHandler#FML_MESSAGETARGET} and {@link FMLOutboundHandler#FML_MESSAGETARGETARGS} set on the channel.
* For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
* For the client to server channel (source Dist : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets,
* several possible values exist.
*
* Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides
@@ -147,15 +146,15 @@ public enum NetworkRegistry
* @param handlers
* @return
*/
public EnumMap<Side,FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers)
public EnumMap<LogicalSide,FMLEmbeddedChannel> newChannel(String name, ChannelHandler... handlers)
{
if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || name.startsWith("FML"))
if (channels.get(LogicalSide.CLIENT).containsKey(name) || channels.get(LogicalSide.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || name.startsWith("FML"))
{
throw new RuntimeException("That channel is already registered");
}
EnumMap<Side,FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
EnumMap<LogicalSide, FMLEmbeddedChannel> result = Maps.newEnumMap(LogicalSide.class);
for (Side side : Side.values())
for (LogicalSide side : LogicalSide.values())
{
FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers);
channels.get(side).put(name,channel);
@@ -191,26 +190,26 @@ public enum NetworkRegistry
* @param container The container to associate the channel with
* @param name The name for the channel
* @param handlers Some {@link ChannelHandler} for the channel
* @return an {@link EnumMap} of the pair of channels. keys are {@link Side}. There will always be two entries.
* @return an {@link EnumMap} of the pair of channels. keys are {@link Dist}. There will always be two entries.
*/
public EnumMap<Side,FMLEmbeddedChannel> newChannel(ModContainer container, String name, ChannelHandler... handlers)
public EnumMap<LogicalSide,FMLEmbeddedChannel> newChannel(ModContainer container, String name, ChannelHandler... handlers)
{
if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || (name.startsWith("FML") && !("FML".equals(container.getModId()))))
if (channels.get(Dist.CLIENT).containsKey(name) || channels.get(Dist.DEDICATED_SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || (name.startsWith("FML") && !("FML".equals(container.getModId()))))
{
throw new RuntimeException("That channel is already registered");
}
EnumMap<Side,FMLEmbeddedChannel> result = Maps.newEnumMap(Side.class);
EnumMap<LogicalSide,FMLEmbeddedChannel> result = Maps.newEnumMap(LogicalSide.class);
for (Side side : Side.values())
for (LogicalSide Dist : LogicalSide.values())
{
FMLEmbeddedChannel channel = new FMLEmbeddedChannel(container, name, side, handlers);
channels.get(side).put(name,channel);
result.put(side, channel);
FMLEmbeddedChannel channel = new FMLEmbeddedChannel(container, name, Dist, handlers);
channels.get(Dist).put(name,channel);
result.put(Dist, channel);
}
return result;
}
public FMLEmbeddedChannel getChannel(String name, Side source)
public FMLEmbeddedChannel getChannel(String name, Dist source)
{
return channels.get(source).get(name);
}
@@ -241,7 +240,7 @@ public enum NetworkRegistry
* @param x X coord
* @param y Y coord
* @param z Z coord
* @return The server side GUI object (An instance of {@link Container})
* @return The server Dist GUI object (An instance of {@link Container})
*/
@Nullable
public Container getRemoteGuiContainer(ModContainer mc, EntityPlayerMP player, int modGuiId, World world, int x, int y, int z)
@@ -267,7 +266,7 @@ public enum NetworkRegistry
* @param x X coord
* @param y Y coord
* @param z Z coord
* @return The client side GUI object (An instance of {@link net.minecraft.client.gui.Gui})
* @return The client Dist GUI object (An instance of {@link net.minecraft.client.gui.Gui})
*/
@Nullable
public Object getLocalGuiContainer(ModContainer mc, EntityPlayer player, int modGuiId, World world, int x, int y, int z)
@@ -277,12 +276,12 @@ public enum NetworkRegistry
}
/**
* Is there a channel with this name on this side?
* Is there a channel with this name on this Dist?
* @param channelName The name
* @param source the side
* @param source the Dist
* @return if there's a channel
*/
public boolean hasChannel(String channelName, Side source)
public boolean hasChannel(String channelName, Dist source)
{
return channels.get(source).containsKey(channelName);
}
@@ -294,20 +293,23 @@ public enum NetworkRegistry
* @param remoteVersionRange the acceptable remote range
* @param asmHarvestedData internal data
*/
/*
public void register(ModContainer fmlModContainer, Class<?> clazz, @Nullable String remoteVersionRange, ASMDataTable asmHarvestedData)
{
NetworkModHolder networkModHolder = new NetworkModHolder(fmlModContainer, clazz, remoteVersionRange, asmHarvestedData);
registry.put(fmlModContainer, networkModHolder);
networkModHolder.testVanillaAcceptance();
}
*/
public boolean isVanillaAccepted(Side from)
/*
public boolean isVanillaAccepted(Dist from)
{
return registry.values().stream()
.allMatch(mod -> mod.acceptsVanilla(from));
}
public Collection<String> getRequiredMods(Side from)
public Collection<String> getRequiredMods(Dist from)
{
return registry.values().stream()
.filter(mod -> !mod.acceptsVanilla(from))
@@ -315,6 +317,7 @@ public enum NetworkRegistry
.sorted()
.collect(Collectors.toList());
}
*/
public Map<ModContainer,NetworkModHolder> registry()
{
@@ -322,21 +325,21 @@ public enum NetworkRegistry
}
/**
* All the valid channel names for a side
* @param side the side
* All the valid channel names for a Dist
* @param Dist the Dist
* @return the set of channel names
*/
public Set<String> channelNamesFor(Side side)
public Set<String> channelNamesFor(Dist Dist)
{
return channels.get(side).keySet();
return channels.get(Dist).keySet();
}
/**
* INTERNAL fire a handshake to all channels
* @param networkDispatcher The dispatcher firing
* @param origin which side the dispatcher is on
* @param origin which Dist the dispatcher is on
*/
public void fireNetworkHandshake(NetworkDispatcher networkDispatcher, Side origin)
public void fireNetworkHandshake(NetworkDispatcher networkDispatcher, Dist origin)
{
/*
NetworkHandshakeEstablished handshake = new NetworkHandshakeEstablished(networkDispatcher, networkDispatcher.getNetHandler(), origin);
@@ -31,13 +31,13 @@ import com.google.common.util.concurrent.Futures;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.handshake.FMLHandshakeMessage.ServerHello;
import net.minecraftforge.fml.common.network.internal.FMLMessage;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
@@ -33,7 +33,7 @@ import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.internal.FMLMessage;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
@@ -65,7 +65,7 @@ import net.minecraftforge.fml.common.network.PacketLoggingHandler;
import net.minecraftforge.fml.common.network.internal.FMLMessage;
import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.network.ConnectionType;
import net.minecraftforge.registries.ForgeRegistry;
// TODO build test suites to validate the behaviour of this stuff and make it less annoyingly magical
@@ -75,10 +75,6 @@ public class NetworkDispatcher extends SimpleChannelInboundHandler<Packet<?>> im
OPENING, AWAITING_HANDSHAKE, HANDSHAKING, HANDSHAKECOMPLETE, FINALIZING, CONNECTED
}
public static enum ConnectionType {
MODDED, BUKKIT, VANILLA
}
public static NetworkDispatcher get(NetworkManager manager)
{
return manager.channel().attr(FML_DISPATCHER).get();
@@ -36,7 +36,7 @@ import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.registry.EntityRegistry.EntityRegistration;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.common.registry.IThrowableEntity;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
public abstract class FMLMessage {
public static class CompleteHandshake extends FMLMessage {
@@ -37,9 +37,12 @@ import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.server.management.PlayerList;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLContainer;
import net.minecraftforge.fml.FMLWorldPersistenceHook;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.ModContainer;
@@ -52,8 +55,6 @@ import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.internal.FMLMessage.CompleteHandshake;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry.EntityRegistration;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@@ -147,8 +148,10 @@ public class FMLNetworkHandler
* @return null if everything is fine, returns a string error message if there are mod rejections
*/
@Nullable
public static String checkModList(Map<String,String> listData, Side side)
public static String checkModList(Map<String,String> listData, LogicalSide side)
{
return null;
/*
List<Pair<ModContainer, String>> rejects = NetworkRegistry.INSTANCE.registry().entrySet().stream()
.map(entry -> Pair.of(entry.getKey(), entry.getValue().checkCompatible(listData, side)))
.filter(pair -> pair.getValue() != null)
@@ -170,9 +173,10 @@ public class FMLNetworkHandler
FMLLog.log.info("Rejecting connection {}: {}", side, rejectString);
return String.format("Server Mod rejections:\n%s", rejectString);
}
*/
}
@SideOnly(Side.CLIENT)
@OnlyIn(Dist.CLIENT)
private static void addClientHandlers()
{
ChannelPipeline pipeline = channelPair.get(Side.CLIENT).pipeline();
@@ -180,7 +184,7 @@ public class FMLNetworkHandler
pipeline.addAfter(targetName, "GuiHandler", new OpenGuiHandler());
pipeline.addAfter(targetName, "EntitySpawnHandler", new EntitySpawnHandler());
}
public static void registerChannel(FMLContainer container, Side side)
public static void registerChannel(FMLWorldPersistenceHook container, Side side)
{
channelPair = NetworkRegistry.INSTANCE.newChannel(container, "FML", new FMLRuntimeCodec(), new HandshakeCompletionHandler());
EmbeddedChannel embeddedChannel = channelPair.get(Side.SERVER);
@@ -38,7 +38,7 @@ import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.network.FMLNetworkException;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.api.distmarker.Dist;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.collect.Lists;
@@ -23,11 +23,9 @@ import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import net.minecraftforge.fml.common.network.NetworkCheckHandler;
import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion;
import net.minecraftforge.fml.common.versioning.InvalidVersionSpecificationException;
@@ -20,9 +20,11 @@
package net.minecraftforge.fml.common.network.simpleimpl;
import net.minecraftforge.api.distmarker.Dist;
/**
* A message handler based on {@link IMessage}. Implement and override {@link #onMessage(IMessage, MessageContext)} to
* process your packet. Supply the class to {@link SimpleNetworkWrapper#registerMessage(Class, Class, int, net.minecraftforge.fml.relauncher.Side)}
* process your packet. Supply the class to {@link SimpleNetworkWrapper#registerMessage(Class, Class, int, Side)}
* to register both the message type and it's associated handler.
*
* @author cpw
@@ -22,7 +22,7 @@ package net.minecraftforge.fml.common.network.simpleimpl;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.INetHandler;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
/**
* Context for the {@link IMessageHandler}
@@ -38,13 +38,13 @@ public class MessageContext {
public final INetHandler netHandler;
/**
* The Side this message has been received on
* The Dist this message has been received on
*/
public final Side side;
public final Dist side;
/**
* @param netHandler
*/
MessageContext(INetHandler netHandler, Side side)
MessageContext(INetHandler netHandler, Dist side)
{
this.netHandler = netHandler;
this.side = side;
@@ -19,7 +19,7 @@
package net.minecraftforge.fml.common.network.simpleimpl;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import org.apache.logging.log4j.Level;
import net.minecraft.network.INetHandler;
@@ -35,14 +35,14 @@ import io.netty.channel.SimpleChannelInboundHandler;
public class SimpleChannelHandlerWrapper<REQ extends IMessage, REPLY extends IMessage> extends SimpleChannelInboundHandler<REQ> {
private final IMessageHandler<? super REQ, ? extends REPLY> messageHandler;
private final Side side;
private final Dist side;
public SimpleChannelHandlerWrapper(Class<? extends IMessageHandler<? super REQ, ? extends REPLY>> handler, Side side, Class<REQ> requestType)
public SimpleChannelHandlerWrapper(Class<? extends IMessageHandler<? super REQ, ? extends REPLY>> handler, Dist side, Class<REQ> requestType)
{
this(SimpleNetworkWrapper.instantiate(handler), side, requestType);
}
public SimpleChannelHandlerWrapper(IMessageHandler<? super REQ, ? extends REPLY> handler, Side side, Class<REQ> requestType)
public SimpleChannelHandlerWrapper(IMessageHandler<? super REQ, ? extends REPLY> handler, Dist side, Class<REQ> requestType)
{
super(requestType);
messageHandler = Preconditions.checkNotNull(handler, "IMessageHandler must not be null");
@@ -33,7 +33,8 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.api.Side;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.FMLEmbeddedChannel;
@@ -50,7 +51,7 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
* Usage is simple:<ul>
* <li>construct, and store, an instance of this class. It will automatically register and configure your underlying netty channel.
*
* <li>Then, call {@link #registerMessage(Class, Class, int, Side)} for each message type you want to exchange
* <li>Then, call {@link #registerMessage(Class, Class, int, Dist)} for each message type you want to exchange
* providing an {@link IMessageHandler} implementation class as well as an {@link IMessage} implementation class. The side parameter
* to that method indicates which side (server or client) the <em>message processing</em> will occur on. The discriminator byte
* should be unique for this channelName - it is used to discriminate between different types of message that might
@@ -96,9 +97,9 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
* // Code in a {@link FMLPreInitializationEvent} or {@link FMLInitializationEvent} handler
* SimpleNetworkWrapper wrapper = NetworkRegistry.newSimpleChannel("MYCHANNEL");
* // Message1 is handled by the Message1Handler class, it has discriminator id 1 and it's on the client
* wrapper.registerMessage(Message1Handler.class, Message1.class, 1, Side.CLIENT);
* wrapper.registerMessage(Message1Handler.class, Message1.class, 1, Dist.CLIENT);
* // Message2 is handled by the Message2Handler class, it has discriminator id 2 and it's on the server
* wrapper.registerMessage(Message2Handler.class, Message2.class, 2, Side.SERVER);
* wrapper.registerMessage(Message2Handler.class, Message2.class, 2, Dist.DEDICATED_SERVER);
* </pre>
* </code>
*
@@ -111,7 +112,7 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
*
*/
public class SimpleNetworkWrapper {
private EnumMap<Side, FMLEmbeddedChannel> channels;
private EnumMap<LogicalSide, FMLEmbeddedChannel> channels;
private SimpleIndexedCodec packetCodec;
private static Class<?> defaultChannelPipeline;
private static Method generateName;
@@ -154,7 +155,7 @@ public class SimpleNetworkWrapper {
* @param discriminator a discriminator byte
* @param side the side for the handler
*/
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, int discriminator, Side side)
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> requestMessageType, int discriminator, Dist side)
{
registerMessage(instantiate(messageHandler), requestMessageType, discriminator, side);
}
@@ -180,12 +181,12 @@ public class SimpleNetworkWrapper {
* @param discriminator a discriminator byte
* @param side the side for the handler
*/
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestMessageType, int discriminator, Side side)
public <REQ extends IMessage, REPLY extends IMessage> void registerMessage(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestMessageType, int discriminator, Dist side)
{
packetCodec.addDiscriminator(discriminator, requestMessageType);
FMLEmbeddedChannel channel = channels.get(side);
String type = channel.findChannelHandlerNameForType(SimpleIndexedCodec.class);
if (side == Side.SERVER)
if (side == Dist.DEDICATED_SERVER)
{
addServerHandlerAfter(channel, type, messageHandler, requestMessageType);
}
@@ -197,17 +198,17 @@ public class SimpleNetworkWrapper {
private <REQ extends IMessage, REPLY extends IMessage, NH extends INetHandler> void addServerHandlerAfter(FMLEmbeddedChannel channel, String type, IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestType)
{
SimpleChannelHandlerWrapper<REQ, REPLY> handler = getHandlerWrapper(messageHandler, Side.SERVER, requestType);
SimpleChannelHandlerWrapper<REQ, REPLY> handler = getHandlerWrapper(messageHandler, Dist.DEDICATED_SERVER, requestType);
channel.pipeline().addAfter(type, generateName(channel.pipeline(), handler), handler);
}
private <REQ extends IMessage, REPLY extends IMessage, NH extends INetHandler> void addClientHandlerAfter(FMLEmbeddedChannel channel, String type, IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Class<REQ> requestType)
{
SimpleChannelHandlerWrapper<REQ, REPLY> handler = getHandlerWrapper(messageHandler, Side.CLIENT, requestType);
SimpleChannelHandlerWrapper<REQ, REPLY> handler = getHandlerWrapper(messageHandler, Dist.CLIENT, requestType);
channel.pipeline().addAfter(type, generateName(channel.pipeline(), handler), handler);
}
private <REPLY extends IMessage, REQ extends IMessage> SimpleChannelHandlerWrapper<REQ, REPLY> getHandlerWrapper(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Side side, Class<REQ> requestType)
private <REPLY extends IMessage, REQ extends IMessage> SimpleChannelHandlerWrapper<REQ, REPLY> getHandlerWrapper(IMessageHandler<? super REQ, ? extends REPLY> messageHandler, Dist side, Class<REQ> requestType)
{
return new SimpleChannelHandlerWrapper<REQ, REPLY>(messageHandler, side, requestType);
}
@@ -221,7 +222,7 @@ public class SimpleNetworkWrapper {
*/
public Packet<?> getPacketFrom(IMessage message)
{
return channels.get(Side.SERVER).generatePacketFrom(message);
return channels.get(Dist.DEDICATED_SERVER).generatePacketFrom(message);
}
/**
@@ -232,8 +233,8 @@ public class SimpleNetworkWrapper {
*/
public void sendToAll(IMessage message)
{
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);
channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
/**
@@ -245,9 +246,9 @@ public class SimpleNetworkWrapper {
*/
public void sendTo(IMessage message, EntityPlayerMP player)
{
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
/**
@@ -259,9 +260,9 @@ public class SimpleNetworkWrapper {
*/
public void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point)
{
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
/**
@@ -304,9 +305,9 @@ public class SimpleNetworkWrapper {
*/
public void sendToDimension(IMessage message, int dimensionId)
{
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);
channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);
channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);
channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);
channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
/**
@@ -317,7 +318,7 @@ public class SimpleNetworkWrapper {
*/
public void sendToServer(IMessage message)
{
channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
channels.get(Side.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
channels.get(Dist.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
channels.get(Dist.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
}
}
@@ -35,8 +35,8 @@ import java.util.regex.Pattern;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher;
import LZMA.LzmaInputStream;
@@ -28,11 +28,14 @@ import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.repackage.com.nothome.delta.Delta;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import java.util.logging.Logger;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
@@ -53,8 +56,7 @@ public class GenDiffSet {
String outputDir = args[3]; //Path to place generated .binpatch
String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch
Logger logger = LogManager.getLogger("FML.GENDIFF");
logger.info("Creating patches at {} for {} from {}", outputDir, sourceJar, targetDir);
LogManager.getLogger("GENDIFF").log(Level.INFO, String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
Delta delta = new Delta();
FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
remapper.setupLoadOnly(deobfData, false);
@@ -25,8 +25,6 @@ import java.util.Map;
import java.util.Set;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@@ -1,6 +1,6 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
* Copyright (c) 2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -17,17 +17,14 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.fml.common;
package net.minecraftforge.fml.common.thread;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import net.minecraftforge.fml.LogicalSide;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface API {
String owner();
String provides();
String apiVersion();
public class EffectiveSide
{
public static LogicalSide get() {
final ThreadGroup group = Thread.currentThread().getThreadGroup();
return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT;
}
}
@@ -19,20 +19,20 @@
package net.minecraftforge.fml.common.thread;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.LogicalSide;
import java.util.concurrent.ThreadFactory;
import javax.annotation.Nonnull;
/**
* A thread group and factory combination which belongs to a {@link Side}.
* A thread group and factory combination which belongs to a {@link LogicalSide}.
*/
public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory
{
private final Side side;
private final LogicalSide side;
SidedThreadGroup(final Side side)
SidedThreadGroup(final LogicalSide side)
{
super(side.name());
this.side = side;
@@ -43,7 +43,7 @@ public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory
*
* @return the side
*/
public Side getSide()
public LogicalSide getSide()
{
return this.side;
}
@@ -19,12 +19,12 @@
package net.minecraftforge.fml.common.thread;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.LogicalSide;
public final class SidedThreadGroups
{
public static final SidedThreadGroup CLIENT = new SidedThreadGroup(Side.CLIENT);
public static final SidedThreadGroup SERVER = new SidedThreadGroup(Side.SERVER);
public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT);
public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER);
private SidedThreadGroups() {
}
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more