diff --git a/src/main/java/net/minecraftforge/fml/client/ClientHooks.java b/src/main/java/net/minecraftforge/fml/client/ClientHooks.java index f2601258db..c3a268afb3 100644 --- a/src/main/java/net/minecraftforge/fml/client/ClientHooks.java +++ b/src/main/java/net/minecraftforge/fml/client/ClientHooks.java @@ -58,10 +58,12 @@ import net.minecraft.network.ServerStatusResponse; import net.minecraft.resources.AbstractResourcePack; import net.minecraft.resources.FallbackResourceManager; import net.minecraft.resources.IResourcePack; +import net.minecraft.resources.SimpleReloadableResourceManager; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.WorldSummary; import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.client.gui.GuiAccessDenied; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.fml.packs.ModFileResourcePack; import net.minecraftforge.registries.GameData; @@ -233,7 +235,7 @@ public class ClientHooks // We can't handle many unicode points in the splash renderer return DISALLOWED_CHAR_MATCHER.removeFrom(net.minecraft.util.StringUtils.stripControlCodes(message)); } - + private static SetMultimap missingTextures = HashMultimap.create(); private static Set badTextureDomains = Sets.newHashSet(); private static Table> brokenTextures = HashBasedTable.create(); @@ -265,7 +267,7 @@ public class ClientHooks Logger logger = LogManager.getLogger("FML.TEXTURE_ERRORS"); logger.error(Strings.repeat("+=", 25)); logger.error("The following texture errors were found."); - Map resManagers = null;// TODO ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager(), "field_110548"+"_a"); + Map resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getInstance().getResourceManager(), "field_199014"+"_c"); for (String resourceDomain : badTextureDomains) { Set missing = missingTextures.get(resourceDomain); @@ -280,7 +282,7 @@ public class ClientHooks } else { - List resPacks = null;//ObfuscationReflectionHelper.getPrivateValue(FallbackResourceManager.class, fallbackResourceManager, "field_110540"+"_a"); + List resPacks = fallbackResourceManager.resourcePacks; logger.error(" domain {} has {} location{}:",resourceDomain, resPacks.size(), resPacks.size() != 1 ? "s" :""); for (IResourcePack resPack : resPacks) { @@ -291,9 +293,7 @@ public class ClientHooks } else if (resPack instanceof AbstractResourcePack) { - AbstractResourcePack resourcePack = (AbstractResourcePack) resPack; - File resPath = null;// TODO bfuscationReflectionHelper.getPrivateValue(AbstractResourcePack.class, resourcePack, "field_110597"+"_b"); - logger.error(" resource pack at path {}",resPath.getPath()); + logger.error(" resource pack at path {}", ((AbstractResourcePack)resPack).file.getPath()); } else { diff --git a/src/main/java/net/minecraftforge/fml/client/TextureTracker.java b/src/main/java/net/minecraftforge/fml/client/TextureTracker.java index aa61010f84..89dd3cebc6 100644 --- a/src/main/java/net/minecraftforge/fml/client/TextureTracker.java +++ b/src/main/java/net/minecraftforge/fml/client/TextureTracker.java @@ -52,84 +52,4 @@ public class TextureTracker } badType.add(resourceLocation); } - - public static void logMissingTextureErrors() - { -/* - if (missingTextures.isEmpty() && brokenTextures.isEmpty()) - { - return; - } - Logger logger = LogManager.getLogger("TEXTURE ERRORS"); - logger.error(Strings.repeat("+=", 25)); - logger.error("The following texture errors were found."); - Map resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getMinecraft().getResourceManager(), "domainResourceManagers", "field_110548"+"_a"); - for (String resourceDomain : badTextureDomains) - { - Set missing = missingTextures.get(resourceDomain); - logger.error(Strings.repeat("=", 50)); - logger.error(" DOMAIN {}", resourceDomain); - logger.error(Strings.repeat("-", 50)); - logger.error(" domain {} is missing {} texture{}",resourceDomain, missing.size(),missing.size()!=1 ? "s" : ""); - FallbackResourceManager fallbackResourceManager = resManagers.get(resourceDomain); - if (fallbackResourceManager == null) - { - logger.error(" domain {} is missing a resource manager - it is probably a side-effect of automatic texture processing", resourceDomain); - } - else - { - List resPacks = ObfuscationReflectionHelper.getPrivateValue(FallbackResourceManager.class, fallbackResourceManager, "resourcePacks","field_110540"+"_a"); - logger.error(" domain {} has {} location{}:",resourceDomain, resPacks.size(), resPacks.size() != 1 ? "s" :""); - for (IResourcePack resPack : resPacks) - { - if (resPack instanceof FMLContainerHolder) { - FMLContainerHolder containerHolder = (FMLContainerHolder) resPack; - ModContainer fmlContainer = containerHolder.getFMLContainer(); - logger.error(" mod {} resources at {}", fmlContainer.getModId(), fmlContainer.getSource().getPath()); - } - else if (resPack instanceof AbstractResourcePack) - { - AbstractResourcePack resourcePack = (AbstractResourcePack) resPack; - File resPath = ObfuscationReflectionHelper.getPrivateValue(AbstractResourcePack.class, resourcePack, "resourcePackFile","field_110597"+"_b"); - logger.error(" resource pack at path {}",resPath.getPath()); - } - else - { - logger.error(" unknown resourcepack type {} : {}", resPack.getClass().getName(), resPack.getPackName()); - } - } - } - logger.error(Strings.repeat("-", 25)); - if (missingTextures.containsKey(resourceDomain)) { - logger.error(" The missing resources for domain {} are:", resourceDomain); - for (ResourceLocation rl : missing) { - logger.error(" {}", rl.getResourcePath()); - } - logger.error(Strings.repeat("-", 25)); - } - if (!brokenTextures.containsRow(resourceDomain)) - { - logger.error(" No other errors exist for domain {}", resourceDomain); - } - else - { - logger.error(" The following other errors were reported for domain {}:",resourceDomain); - Map> resourceErrs = brokenTextures.row(resourceDomain); - for (String error: resourceErrs.keySet()) - { - logger.error(Strings.repeat("-", 25)); - logger.error(" Problem: {}", error); - for (ResourceLocation rl : resourceErrs.get(error)) - { - logger.error(" {}",rl.getResourcePath()); - } - } - } - logger.error(Strings.repeat("=", 50)); - } - logger.error(Strings.repeat("+=", 25)); -*/ - } - - } diff --git a/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java b/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java index a4730d306b..b0773e4acb 100644 --- a/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java +++ b/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java @@ -18,62 +18,98 @@ */ package net.minecraftforge.fml.common; -/* TODO ReflectionHelper -import java.util.Arrays; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.StringJoiner; -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 javax.annotation.Nonnull; + +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 com.google.common.base.Preconditions; /** * Some reflection helper code. + * This may not work properly in Java9 with their new more restrictive reflection management. + * As such, if issues are encountered, please report them and we can see what we can do to expand + * the compatibility. * - * @author cpw + * In other cases, AccessTransformers may be used. * - * / + * All field names should be passed in as SRG names, and this will automatically resolve if MCP mappings are detected. + * + */ +@SuppressWarnings({"serial", "unchecked"}) public class ObfuscationReflectionHelper { + private static final Logger LOGGER = LogManager.getLogger(); + private static final Marker REFLECTION = MarkerManager.getMarker("REFLECTION"); + private static final Map map = new HashMap<>(); + private static boolean loaded = false; + + + + public static String[] remapNames(String... names) + { + loadMappings(); + if (map.isEmpty()) + return names; + + String[] mappedNames = new String[names.length]; + int i = 0; + for (String name : names) + mappedNames[i++] = map.getOrDefault(name, name); + return mappedNames; + } + + public static String remapName(String name) + { + loadMappings(); + if (map.isEmpty()) + return name; + return map.getOrDefault(name, name); + } + public static T getPrivateValue(Class classToAccess, E instance, int fieldIndex) { try { - return ReflectionHelper.getPrivateValue(classToAccess, instance, fieldIndex); + Field f = classToAccess.getDeclaredFields()[fieldIndex]; + f.setAccessible(true); + return (T)f.get(instance); } - catch (UnableToAccessFieldException e) + catch (Exception e) { - LOGGER.error("There was a problem getting field index {} from {}", classToAccess.getName(), e); - throw e; + LOGGER.error(REFLECTION, "There was a problem getting field index {} from {}", classToAccess.getName(), e); + throw new UnableToAccessFieldException(e); } } - public static String[] remapFieldNames(String className, String... fieldNames) - { - String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(className.replace('.', '/')); - String[] mappedNames = new String[fieldNames.length]; - int i = 0; - for (String fName : fieldNames) - { - mappedNames[i++] = FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fName, null); - } - return mappedNames; - } - - public static T getPrivateValue(Class classToAccess, E instance, String... fieldNames) + public static T getPrivateValue(Class classToAccess, E instance, String fieldName) { try { - return ReflectionHelper.getPrivateValue(classToAccess, instance, remapFieldNames(classToAccess.getName(),fieldNames)); + return (T)findField(classToAccess, remapName(fieldName)).get(instance); } catch (UnableToFindFieldException e) { - LOGGER.error("Unable to locate any field {} on type {}", Arrays.toString(fieldNames), classToAccess.getName(), e); + LOGGER.error("Unable to locate field {} ({}) on type {}", fieldName, remapName(fieldName), classToAccess.getName(), e); throw e; } - catch (UnableToAccessFieldException e) + catch (IllegalAccessException e) { - LOGGER.error("Unable to access any field {} on type {}", classToAccess.getName(), e); - throw e; + LOGGER.error("Unable to access field {} ({}) on type {}", fieldName, remapName(fieldName), classToAccess.getName(), e); + throw new UnableToAccessFieldException(e); } } @@ -81,31 +117,181 @@ public class ObfuscationReflectionHelper { try { - ReflectionHelper.setPrivateValue(classToAccess, instance, value, fieldIndex); + Field f = classToAccess.getDeclaredFields()[fieldIndex]; + f.setAccessible(true); + f.set(instance, value); } - catch (UnableToAccessFieldException e) + catch (IllegalAccessException e) { LOGGER.error("There was a problem setting field index {} on type {}", classToAccess.getName(), e); - throw e; + throw new UnableToAccessFieldException(e); } } - public static void setPrivateValue(Class classToAccess, T instance, E value, String... fieldNames) + public static void setPrivateValue(Class classToAccess, T instance, E value, String fieldName) { try { - ReflectionHelper.setPrivateValue(classToAccess, instance, value, remapFieldNames(classToAccess.getName(), fieldNames)); + findField(classToAccess, remapName(fieldName)).set(instance, value); } catch (UnableToFindFieldException e) { LOGGER.error("Unable to locate any field {} on type {}", classToAccess.getName(), e); throw e; } - catch (UnableToAccessFieldException e) + catch (IllegalAccessException e) { LOGGER.error("Unable to set any field {} on type {}", classToAccess.getName(), e); - throw e; + throw new UnableToAccessFieldException(e); + } + } + + /** + * 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. + *

+ * Throws an exception if the method is not found. + * + * @param clazz The class to find the method on. + * @param methodName The name of the method to find (used in developer environments, i.e. "getWorldTime"). + * @param methodObfName The obfuscated name of the method to find (used in obfuscated environments, i.e. "func_72820_D"). + * If the name you are looking for is on a class that is never obfuscated, this should be null. + * @param parameterTypes The parameter types of the method to find. + * @return The method with the specified name and parameters in the given class. + */ + @Nonnull + public static Method findMethod(@Nonnull Class clazz, @Nonnull String methodName, Class... parameterTypes) + { + Preconditions.checkNotNull(clazz); + Preconditions.checkNotNull(methodName); + Preconditions.checkArgument(methodName.isEmpty(), "Method name cannot be empty"); + + try + { + Method m = clazz.getDeclaredMethod(remapName(methodName), parameterTypes); + m.setAccessible(true); + return m; + } + catch (Exception e) + { + throw new UnableToFindMethodException(e); + } + } + + /** + * 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 The type + * @return The constructor + * @throws NullPointerException if {@code klass} is null + * @throws NullPointerException if {@code parameterTypes} is null + * @throws UnknownConstructorException if the constructor could not be found + */ + @Nonnull + public static Constructor findConstructor(@Nonnull final Class klass, @Nonnull final Class... parameterTypes) + { + Preconditions.checkNotNull(klass, "class"); + Preconditions.checkNotNull(parameterTypes, "parameter types"); + + try + { + Constructor constructor = klass.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return constructor; + } + catch (final NoSuchMethodException e) + { + final StringBuilder desc = new StringBuilder(); + desc.append(klass.getSimpleName()); + + StringJoiner joiner = new StringJoiner(", ", "(", ")"); + for (Class type : parameterTypes) + { + joiner.add(type.getSimpleName()); + } + desc.append(joiner); + + throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + klass); + } + } + + private static Field findField(Class clazz, String name) + { + try + { + Field f = clazz.getDeclaredField(name); + f.setAccessible(true); + return f; + } + catch (Exception e) + { + throw new UnableToFindFieldException(e); + } + } + + private static void loadMappings() + { + if (loaded) + return; + + synchronized(map) //Just in case? + { + if (loaded) //Incase something else loaded while we were here, jump out + return; + for (String file : new String[]{"fields.csv", "methods.csv"}) + { + URL path = ClassLoader.getSystemResource(file); //We EXPLICITLY go throught the SystemClassLoader here because this is dev-time only. And will be on the root classpath. + if (path == null) + continue; + + int count = map.size(); + LOGGER.info(REFLECTION, "Loading Mappings: {}", path); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(path.openStream()))) + { + reader.lines().skip(1).map(e -> e.split(",")).forEach(e -> map.put(e[0], e[1])); + } + catch (IOException e1) + { + LOGGER.error(REFLECTION, "Error reading mappings", e1); + } + LOGGER.info(REFLECTION, "Loaded {} entries", map.size() - count); + } + loaded = true; + } + } + + //Add SRG names to these exception? + public static class UnableToAccessFieldException extends RuntimeException + { + private UnableToAccessFieldException(Exception e) + { + super(e); + } + } + + public static class UnableToFindFieldException extends RuntimeException + { + private UnableToFindFieldException(Exception e) + { + super(e); + } + } + + public static class UnableToFindMethodException extends RuntimeException + { + public UnableToFindMethodException(Throwable failed) + { + super(failed); + } + } + + public static class UnknownConstructorException extends RuntimeException + { + public UnknownConstructorException(final String message) + { + super(message); } } } -*/ diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java index a88cbfa9d2..54ab81368b 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java @@ -29,6 +29,7 @@ import java.util.Map.Entry; import javax.annotation.Nonnull; import net.minecraftforge.fml.ModThreadContext; +import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.loading.AdvancedLogMessageAdapter; import org.apache.commons.lang3.Validate; @@ -427,7 +428,7 @@ public class ForgeRegistry> implements IForgeRe { try { -// ReflectionHelper.findMethod(BitSet.class, "trimToSize", null).invoke(this.availabilityMap); + ObfuscationReflectionHelper.findMethod(BitSet.class, "trimToSize").invoke(this.availabilityMap); } catch (Exception e) {