Skip to content

Commit

Permalink
Improve reflection helper methods (#4853)
Browse files Browse the repository at this point in the history
  • Loading branch information
bs2609 authored and mezz committed Nov 23, 2018
1 parent 896db63 commit d16472d
Show file tree
Hide file tree
Showing 13 changed files with 219 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.item.Item;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.IRegistry;
Expand All @@ -84,6 +83,7 @@
import net.minecraftforge.fml.common.ProgressManager;
import net.minecraftforge.fml.common.ProgressManager.ProgressBar;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.registries.IRegistryDelegate;

import org.apache.commons.lang3.tuple.Pair;
Expand Down Expand Up @@ -128,7 +128,7 @@ public boolean isLoading()
return isLoading;
}

private final boolean enableVerboseMissingInfo = (Boolean)Launch.blackboard.get("fml.deobfuscatedEnvironment") || Boolean.parseBoolean(System.getProperty("forge.verboseMissingModelLogging", "false"));
private final boolean enableVerboseMissingInfo = FMLLaunchHandler.isDeobfuscatedEnvironment() || Boolean.parseBoolean(System.getProperty("forge.verboseMissingModelLogging", "false"));
private final int verboseMissingInfoCount = Integer.parseInt(System.getProperty("forge.verboseMissingModelLoggingCount", "5"));

public ModelLoader(IResourceManager manager, TextureMap map, BlockModelShapes shapes)
Expand Down
9 changes: 4 additions & 5 deletions src/main/java/net/minecraftforge/common/ForgeHooks.java
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderState;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.common.eventhandler.Event;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher.ConnectionType;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryManager;

Expand Down Expand Up @@ -270,19 +270,19 @@ static void initTools()
}
toolInit = true;

Set<Block> blocks = ReflectionHelper.getPrivateValue(ItemPickaxe.class, null, 0);
Set<Block> blocks = ObfuscationReflectionHelper.getPrivateValue(ItemPickaxe.class, null, "field_150915"+"_c");
for (Block block : blocks)
{
block.setHarvestLevel("pickaxe", 0);
}

blocks = ReflectionHelper.getPrivateValue(ItemSpade.class, null, 0);
blocks = ObfuscationReflectionHelper.getPrivateValue(ItemSpade.class, null, "field_150916"+"_c");
for (Block block : blocks)
{
block.setHarvestLevel("shovel", 0);
}

blocks = ReflectionHelper.getPrivateValue(ItemAxe.class, null, 0);
blocks = ObfuscationReflectionHelper.getPrivateValue(ItemAxe.class, null, "field_150917"+"_c");
for (Block block : blocks)
{
block.setHarvestLevel("axe", 0);
Expand Down Expand Up @@ -330,7 +330,6 @@ public ItemStack getStack(Random rand, int fortune)
return new ItemStack(Items.WHEAT_SEEDS, 1 + rand.nextInt(fortune * 2 + 1));
}
});
initTools();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ public static void firePlayerSavingEvent(EntityPlayer player, File playerDirecto
public static void firePlayerLoadingEvent(EntityPlayer player, IPlayerFileData playerFileData, String uuidString)
{
SaveHandler sh = (SaveHandler) playerFileData;
File dir = ObfuscationReflectionHelper.getPrivateValue(SaveHandler.class, sh, "playersDirectory", "field_"+"75771_c");
File dir = ObfuscationReflectionHelper.getPrivateValue(SaveHandler.class, sh, "field_"+"75771_c");
MinecraftForge.EVENT_BUS.post(new PlayerEvent.LoadFromFile(player, dir, uuidString));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,7 @@ public void logMissingTextureErrors()
Logger logger = LogManager.getLogger("FML.TEXTURE_ERRORS");
logger.error(Strings.repeat("+=", 25));
logger.error("The following texture errors were found.");
Map<String,FallbackResourceManager> resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager(), "domainResourceManagers", "field_110548"+"_a");
Map<String,FallbackResourceManager> resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager(), "field_110548"+"_a");
for (String resourceDomain : badTextureDomains)
{
Set<ResourceLocation> missing = missingTextures.get(resourceDomain);
Expand All @@ -976,7 +976,7 @@ public void logMissingTextureErrors()
}
else
{
List<IResourcePack> resPacks = ObfuscationReflectionHelper.getPrivateValue(FallbackResourceManager.class, fallbackResourceManager, "resourcePacks","field_110540"+"_a");
List<IResourcePack> resPacks = ObfuscationReflectionHelper.getPrivateValue(FallbackResourceManager.class, fallbackResourceManager, "field_110540"+"_a");
logger.error(" domain {} has {} location{}:",resourceDomain, resPacks.size(), resPacks.size() != 1 ? "s" :"");
for (IResourcePack resPack : resPacks)
{
Expand All @@ -988,7 +988,7 @@ public void logMissingTextureErrors()
else if (resPack instanceof AbstractResourcePack)
{
AbstractResourcePack resourcePack = (AbstractResourcePack) resPack;
File resPath = ObfuscationReflectionHelper.getPrivateValue(AbstractResourcePack.class, resourcePack, "resourcePackFile","field_110597"+"_b");
File resPath = ObfuscationReflectionHelper.getPrivateValue(AbstractResourcePack.class, resourcePack, "field_110597"+"_b");
logger.error(" resource pack at path {}",resPath.getPath());
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ public void handleServerStopped()
MinecraftServer server = getMinecraftServerInstance();
Loader.instance().serverStopped();
// FORCE the internal server to stop: hello optifine workaround!
if (server!=null) ObfuscationReflectionHelper.setPrivateValue(MinecraftServer.class, server, false, "field_71316"+"_v", "u", "serverStopped");
if (server!=null) ObfuscationReflectionHelper.setPrivateValue(MinecraftServer.class, server, false, "field_71316"+"_v");

// allow any pending exit to continue, clear exitLatch
CountDownLatch latch = exitLatch;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,18 @@

package net.minecraftforge.fml.common;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToAccessFieldException;
import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToFindFieldException;
import org.objectweb.asm.Type;

import org.apache.logging.log4j.Level;
import javax.annotation.Nullable;

/**
* Some reflection helper code.
Expand All @@ -36,6 +40,7 @@
*/
public class ObfuscationReflectionHelper
{
@Deprecated // TODO: remove
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, int fieldIndex)
{
try
Expand All @@ -49,6 +54,7 @@ public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instanc
}
}

@Deprecated // TODO: remove
public static String[] remapFieldNames(String className, String... fieldNames)
{
String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(className.replace('.', '/'));
Expand All @@ -61,6 +67,22 @@ public static String[] remapFieldNames(String className, String... fieldNames)
return mappedNames;
}

private static String remapFieldName(Class<?> clazz, String fieldName)
{
String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz));
return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null);
}

private static String remapMethodName(Class<?> clazz, String methodName, Class<?> returnType, Class<?>... parameterTypes)
{
String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz));
Type[] params = Arrays.stream(parameterTypes).map(Type::getType).toArray(Type[]::new);
String desc = Type.getMethodDescriptor(Type.getType(returnType), params);
return FMLDeobfuscatingRemapper.INSTANCE.mapMethodName(internalClassName, methodName, desc);
}

/** @deprecated use {@link #getPrivateValue(Class, Object, String)} */
@Deprecated // TODO: remove
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, String... fieldNames)
{
try
Expand All @@ -79,6 +101,12 @@ public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instanc
}
}

public static <T, E> T getPrivateValue(Class<? super E> classToAccess, @Nullable E instance, String srgName)
{
return ReflectionHelper.getPrivateValue(classToAccess, instance, remapFieldName(classToAccess, srgName), null);
}

@Deprecated // TODO: remove
public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T instance, E value, int fieldIndex)
{
try
Expand All @@ -92,6 +120,8 @@ public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T inst
}
}

/** @deprecated use {@link #setPrivateValue(Class, Object, Object, String)} */
@Deprecated // TODO: remove
public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T instance, E value, String... fieldNames)
{
try
Expand All @@ -109,4 +139,58 @@ public static <T, E> void setPrivateValue(Class<? super T> classToAccess, T inst
throw e;
}
}

public static <T, E> void setPrivateValue(Class<? super T> classToAccess, @Nullable T instance, @Nullable E value, String srgName)
{
ReflectionHelper.setPrivateValue(classToAccess, instance, value, remapFieldName(classToAccess, srgName), null);
}

/**
* Finds a field with the specified name in the given class and makes it accessible.
* Note: for performance, store the returned value and avoid calling this repeatedly.
* <p>
* Throws an exception if the field is not found.
*
* @param clazz The class to find the field on.
* @param srgName The obfuscated name of the field to find.
*
* @return The field with the specified name in the given class.
*/
public static Field findField(Class<?> clazz, String srgName)
{
return ReflectionHelper.findField(clazz, remapFieldName(clazz, srgName), null);
}

/**
* Finds a method with the specified name and parameters in the given class and makes it accessible.
* Note: for performance, store the returned value and avoid calling this repeatedly.
* <p>
* Throws an exception if the method is not found.
*
* @param clazz The class to find the method on.
* @param srgName The obfuscated name of the method to find.
* @param returnType The return type of the method to find.
* @param parameterTypes The parameter types of the method to find.
*
* @return The method with the specified name and type signature in the given class.
*/
public static Method findMethod(Class<?> clazz, String srgName, Class<?> returnType, Class<?>... parameterTypes)
{
String mappedName = remapMethodName(clazz, srgName, returnType, parameterTypes);
return ReflectionHelper.findMethod(clazz, mappedName, null, parameterTypes);
}

/**
* Finds a constructor in the specified class that has matching parameter types.
*
* @param klass The class to find the constructor in
* @param parameterTypes The parameter types of the constructor.
* @param <T> The type
*
* @return The constructor
*/
public static <T> Constructor<T> findConstructor(Class<T> klass, Class<?>... parameterTypes)
{
return ReflectionHelper.findConstructor(klass, parameterTypes);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
import java.util.jar.Pack200;
import java.util.regex.Pattern;

import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.relauncher.FMLLaunchHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher;
import LZMA.LzmaInputStream;
Expand Down Expand Up @@ -172,7 +172,7 @@ public void setup(Side side)
InputStream binpatchesCompressed = getClass().getResourceAsStream("/binpatches.pack.lzma");
if (binpatchesCompressed==null)
{
if (!((Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")))
if (!FMLLaunchHandler.isDeobfuscatedEnvironment())
{
FMLLog.log.fatal("The binary patch set is missing, things are not going to work!");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
import net.minecraftforge.fml.relauncher.ReflectionHelper.UnknownConstructorException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
Expand Down Expand Up @@ -250,7 +251,7 @@ public final EntityEntryBuilder<E> egg(final int primaryColor, final int seconda
* @throws IllegalStateException If the entity id has not been provided
* @throws IllegalStateException If the entity name has not been provided
* @throws IllegalStateException If spawns have been provided for a non {@link EntityLiving}
* @throws ReflectionHelper.UnknownConstructorException If a {@link #factory} has not been provided
* @throws UnknownConstructorException If a {@link #factory} has not been provided
* and {@link #entity} does not have a constructor accepting {@link World}
*/
@Nonnull
Expand Down Expand Up @@ -293,7 +294,7 @@ static abstract class ConstructorFactory<E extends Entity> implements Function<W

ConstructorFactory(final Class<? extends E> entity)
{
this.constructor = ReflectionHelper.findConstructor(entity, World.class);
this.constructor = ObfuscationReflectionHelper.findConstructor(entity, World.class);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ public class CoreModManager {
private static List<String> ignoredModFiles = Lists.newArrayList();
private static Map<String, List<String>> transformers = Maps.newHashMap();
private static List<FMLPluginWrapper> loadPlugins;
private static boolean deobfuscatedEnvironment;
private static FMLTweaker tweaker;
private static File mcDir;
private static List<String> candidateModFiles = Lists.newArrayList();
private static List<String> accessTransformers = Lists.newArrayList();
private static Set<String> rootNames = Sets.newHashSet();

static boolean deobfuscatedEnvironment;

static
{
for(String cls : rootPlugins)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,8 @@ public static void appendCoreMods()
INSTANCE.injectPostfixTransformers();
}


public static boolean isDeobfuscatedEnvironment()
{
return CoreModManager.deobfuscatedEnvironment;
}
}
Loading

0 comments on commit d16472d

Please sign in to comment.