Skip to content
This repository has been archived by the owner on Jun 3, 2024. It is now read-only.

Commit

Permalink
1.16.4 only, and various fixes in the name of science.
Browse files Browse the repository at this point in the history
  • Loading branch information
TheGlitch76 committed Dec 29, 2020
1 parent 5caf0d3 commit 8059083
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 78 deletions.
39 changes: 36 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -107,23 +107,56 @@ task sourcesJar(type: Jar, dependsOn: classes) {

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
shadowJar {
minimize()
transform(com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer)
minimize {
exclude(dependency("org.dom4j:dom4j:2.1.3"))
exclude(dependency("org.apache.logging.log4j:log4j-core:2.13.2"))
exclude(dependency("net.minecrell:terminalconsoleappender:1.2.0"))
exclude(dependency("org.jline:jline-terminal-jansi:3.12.1"))
}
}

task shadowCliJar(type: ShadowJar, dependsOn: shadowJar) {
transform(com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer)
archiveClassifier.set("cli")
from sourceSets.cli.output
from zipTree(shadowJar.archiveFile.get())
configurations = [ configurations.cliRuntime ]
minimize()
minimize {
exclude(dependency("org.dom4j:dom4j:2.1.3"))
exclude(dependency("org.apache.logging.log4j:log4j-core:2.13.2"))
exclude(dependency("net.minecrell:terminalconsoleappender:1.2.0"))
exclude(dependency("org.jline:jline-terminal-jansi:3.12.1"))
}

manifest {
attributes(
'Implementation-Title': 'Patchwork Patcher (CLI)',
'Implementation-Version': archiveVersion,
'Main-Class': "net.patchworkmc.patcher.cli.PatchworkCLI"
)
}
}

task shadowUiJar(type: ShadowJar, dependsOn: shadowJar) {
transform(com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer)
archiveClassifier.set("ui")
from sourceSets.ui.output
from zipTree(shadowJar.archiveFile.get())
configurations = [ configurations.uiRuntime ]
minimize()
minimize {
exclude(dependency("org.dom4j:dom4j:2.1.3"))
exclude(dependency("org.apache.logging.log4j:log4j-core:2.13.2"))
exclude(dependency("net.minecrell:terminalconsoleappender:1.2.0"))
exclude(dependency("org.jline:jline-terminal-jansi:3.12.1"))
}
manifest {
attributes(
'Implementation-Title': 'Patchwork Patcher (UI)',
'Implementation-Version': archiveVersion,
'Main-Class': "net.patchworkmc.patcher.ui.PatchworkUI"
)
}
}

shadowJar.finalizedBy shadowCliJar
Expand Down
1 change: 0 additions & 1 deletion src/cli/resources/log4j2.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
<Loggers>
<Root level="all">
<AppenderRef ref="SysOut" level="trace"/>
<AppenderRef ref="net.patchworkmc.patcher.ui.UIAppender" level="info"/>
</Root>
</Loggers>
</Configuration>
16 changes: 8 additions & 8 deletions src/main/java/net/patchworkmc/patcher/Patchwork.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@

public class Patchwork {
// TODO use a "standard" log4j logger
public static final Logger LOGGER = LogManager.getFormatterLogger("Patchwork");
public static final Logger LOGGER = LogManager.getLogger("Patchwork");
private byte[] patchworkGreyscaleIcon;

private final MinecraftVersion minecraftVersion;
Expand Down Expand Up @@ -104,7 +104,7 @@ public int patchAndFinish() throws IOException {
}

// If any exceptions are encountered during remapping they are caught and the ForgeModJar's "processed" boolean will not be true.
LOGGER.warn("Patching %s mods", mods.size());
LOGGER.warn("Patching {} mods", mods.size());
remapJars(mods, this.minecraftJarSrg, this.forgeUniversalJar);

for (ForgeModJar mod : mods) {
Expand Down Expand Up @@ -139,7 +139,7 @@ private List<ForgeModJar> parseAllManifests(Stream<Path> modJars) {
private ForgeModJar parseModManifest(Path jarPath) throws IOException, ManifestParseException {
String mod = jarPath.getFileName().toString().split("\\.jar")[0];
// Load metadata
LOGGER.trace("Loading and parsing metadata for %s", mod);
LOGGER.trace("Loading and parsing metadata for {}", mod);

FileConfig toml;
ForgeAccessTransformer at = null;
Expand All @@ -161,11 +161,11 @@ private ForgeModJar parseModManifest(Path jarPath) throws IOException, ManifestP
ModManifest manifest = ModManifest.parse(map);

if (!manifest.getModLoader().equals("javafml")) {
LOGGER.error("Unsupported modloader %s", manifest.getModLoader());
LOGGER.error("Unsupported modloader {}", manifest.getModLoader());
}

if (at != null) {
at.remap(accessTransformerRemapper, ex -> LOGGER.log(Level.WARN, "Error remapping the access transformer for %s: %s", mod, ex.getMessage()));
at.remap(accessTransformerRemapper, ex -> LOGGER.log(Level.WARN, "Error remapping the access transformer for {}: {}", mod, ex.getMessage()));
}

return new ForgeModJar(jarPath, outputDir.resolve(jarPath.getFileName()), manifest, at);
Expand All @@ -175,14 +175,14 @@ private void rewriteMetadata(ForgeModJar forgeModJar) throws IOException, URISyn
Path output = forgeModJar.getOutputPath();

if (!forgeModJar.isProcessed()) {
LOGGER.warn("Skipping %s because it has not been successfully remapped!", forgeModJar.getOutputPath().getFileName());
LOGGER.warn("Skipping {} because it has not been successfully remapped!", forgeModJar.getOutputPath().getFileName());
return;
}

ModManifest manifest = forgeModJar.getManifest();
AnnotationStorage annotationStorage = forgeModJar.getAnnotationStorage();
String mod = output.getFileName().toString().split("\\.jar")[0];
LOGGER.info("Rewriting mod metadata for %s", mod);
LOGGER.info("Rewriting mod metadata for {}", mod);

Gson gson = new GsonBuilder().setPrettyPrinting().create();

Expand Down Expand Up @@ -348,7 +348,7 @@ private void remapJars(Collection<ForgeModJar> jars, Path... classpath) {
transformer.closeOutputConsumer();
forgeModJar.processed = true;
} catch (Exception ex) {
LOGGER.error("Skipping remapping mod %s due to errors:", forgeModJar.getInputPath().getFileName());
LOGGER.error("Skipping remapping mod {} due to errors:", forgeModJar.getInputPath().getFileName());
LOGGER.throwing(Level.ERROR, ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ static class AnnotationPrinter extends AnnotationVisitor {
public void visit(String name, Object value) {
super.visit(name, value);

Patchwork.LOGGER.warn("%s -> %s", name, value);
Patchwork.LOGGER.warn("{} -> {}", name, value);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -349,13 +349,13 @@ public AnnotationVisitor visitAnnotation(String annotation, boolean visible) {
// means that there are primitive type arguments

if (genericClass.contains("*")) {
Patchwork.LOGGER.error("Error while parsing event handler: %s.%s(%s):", className, this.name, eventClass);
Patchwork.LOGGER.error(" - FIXME: Not sure how to handle wildcards! We need to implement proper signature parsing: %s", genericClass);
Patchwork.LOGGER.error("Error while parsing event handler: {}.{}({}):", className, this.name, eventClass);
Patchwork.LOGGER.error(" - FIXME: Not sure how to handle wildcards! We need to implement proper signature parsing: {}", genericClass);

genericClass = null;
} else if ((genericClass.indexOf(';') != genericClass.lastIndexOf(';')) || !genericClass.startsWith("L") || !genericClass.endsWith(";")) {
Patchwork.LOGGER.error("Error while parsing event handler: %s.%s(%s):", className, this.name, eventClass);
Patchwork.LOGGER.error(" - FIXME: Generic events may only have one type parameter, but %s uses an event with multiple (Signature: %s)", name, this.signature);
Patchwork.LOGGER.error("Error while parsing event handler: {}.{}({}):", className, this.name, eventClass);
Patchwork.LOGGER.error(" - FIXME: Generic events may only have one type parameter, but {} uses an event with multiple (Signature: {})", name, this.signature);

genericClass = null;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static void accept(MethodVisitor method, @Nullable EventBusSubscriber ann
// TODO: Check targetModId

if (!annotation.isClient() || !annotation.isServer()) {
Patchwork.LOGGER.warn("Sided @EventBusSubscriber annotations are not supported yet, applying %s from %s : %s without sides.",
Patchwork.LOGGER.warn("Sided @EventBusSubscriber annotations are not supported yet, applying {} from {} : {} without sides.",
annotation, subscriber.getClassName(), annotation.getTargetModId());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ public static byte[] convertToWidener(ForgeAccessTransformer accessTransformer,
try {
writeWildcards(sb, targetClass.getName(), targetClass.getFieldWildcard(), targetClass.getMethodWildcard(), info);
} catch (MissingMappingException ex) {
Patchwork.LOGGER.log(Level.WARN, "Couldn't write wildcards for class %s: %s", targetClass.getName(), ex.getMessage());
Patchwork.LOGGER.log(Level.WARN, "Couldn't write wildcards for class {}: {}", targetClass.getName(), ex.getMessage());
}

for (TransformedField field : targetClass.getFields()) {
try {
writeField(sb, field, info);
} catch (MissingMappingException ex) {
Patchwork.LOGGER.log(Level.WARN, "Couldn't convert field %s in class %s: %s", field.getName(), field.getOwner(), ex.getMessage());
Patchwork.LOGGER.log(Level.WARN, "Couldn't convert field {} in class {}: {}", field.getName(), field.getOwner(), ex.getMessage());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void acceptMethod(IMappingProvider.Member method, String dstName) {

if (blacklistedMethods.contains(method.name)) {
if (DEBUG) {
Patchwork.LOGGER.debug("Another duplicated method mapping for %s (proposed %s)", method.name, dstName);
Patchwork.LOGGER.debug("Another duplicated method mapping for {} (proposed {})", method.name, dstName);
}

return;
Expand All @@ -62,7 +62,7 @@ public void acceptMethod(IMappingProvider.Member method, String dstName) {
naiveRemapper.methods.remove(method.name);

if (DEBUG) {
Patchwork.LOGGER.debug("Duplicated method mapping for %s (proposed %s, but already mapped to %s!)", method.name, dstName, presentName);
Patchwork.LOGGER.debug("Duplicated method mapping for {} (proposed {}, but already mapped to {}!)", method.name, dstName, presentName);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private String remap(String name) {
try {
name = remapper.getMethod(name);
} catch (AmbiguousMappingException e) {
Patchwork.LOGGER.warn("Failed to remap string constant: %s", e.getMessage());
Patchwork.LOGGER.warn("Failed to remap string constant: {}", e.getMessage());

return name;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,58 +13,76 @@
import net.patchworkmc.patcher.transformer.NodeTransformer;

public class SuperclassRedirectionTransformer extends NodeTransformer {
private static final Map<String, Redirection> redirects = new HashMap<>();
private static final Map<String, ClassRedirection> redirects = new HashMap<>();

static {
// redirects should be added in the form
// redirects.put("net/minecraft/intermediary", new Redirection("net/patchworkmc/WrapperClass","(Forge's <init> descriptor)V"))
redirects.put("net/minecraft/class_1761",
new ClassRedirection("net/patchworkmc/api/registries/PatchworkItemGroup")
.withMethod("method_7750()Lnet/minecraft/class_1799;", "patchwork$createIconHack"));
}

@Override
protected void transform(ClassNode node) {
if (redirects.containsKey(node.superName)) {
node.superName = redirects.get(node.superName).name;
ClassRedirection redirection = redirects.get(node.superName);

if (redirection != null) {
node.superName = redirects.get(node.superName).newName;

for (MethodNode method : node.methods) {
String rename = redirection.methods.get(method.name + method.desc);

if (rename != null) {
method.name = rename;
}
}
}

node.methods.forEach(this::transformMethod);
node.methods.forEach(this::redirectInstanceCreation);
}

private void transformMethod(MethodNode method) {
private void redirectInstanceCreation(MethodNode method) {
for (AbstractInsnNode in : method.instructions) {
if (!(in instanceof MethodInsnNode)) {
continue;
}

MethodInsnNode min = (MethodInsnNode) in;

if (min.getOpcode() == Opcodes.INVOKESPECIAL && min.name.equals("<init>") && redirects.containsKey(min.owner)) {
Redirection redirect = redirects.get(min.owner);
ClassRedirection classRedirection = redirects.get(min.owner);

if (min.desc.equals(redirect.initializerDescriptor)) {
AbstractInsnNode prev = min;
if (classRedirection == null) {
continue;
}

while (prev != null) {
prev = prev.getPrevious();
if (min.getOpcode() == Opcodes.INVOKESPECIAL && min.name.equals("<init>")) {
AbstractInsnNode prev = min;

if (prev instanceof TypeInsnNode && prev.getOpcode() == Opcodes.NEW && ((TypeInsnNode) prev).desc.equals(min.owner)) {
((TypeInsnNode) prev).desc = redirect.name;
break;
}
}
while (prev != null) {
prev = prev.getPrevious();

min.owner = redirect.name;
if (prev instanceof TypeInsnNode && prev.getOpcode() == Opcodes.NEW && ((TypeInsnNode) prev).desc.equals(min.owner)) {
((TypeInsnNode) prev).desc = classRedirection.newName;
break;
}
}

min.owner = classRedirection.newName;
}
}
}

private static class Redirection {
public final String name;
public final String initializerDescriptor;
private static class ClassRedirection {
final String newName;

final Map<String, String> methods = new HashMap<>();

ClassRedirection(String newName) {
this.newName = newName;
}

Redirection(String name, String initializerDescriptor) {
this.name = name;
this.initializerDescriptor = initializerDescriptor;
final ClassRedirection withMethod(String nameAndDesc, String newName) {
this.methods.put(nameAndDesc, newName);
return this;
}
}
}
35 changes: 5 additions & 30 deletions src/ui/java/net/patchworkmc/patcher/ui/PatchworkUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;
import java.security.Permission;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
Expand Down Expand Up @@ -262,13 +261,11 @@ protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirem
jPanel.setVisible(false);
service.submit(() -> {
try {
runWithNoExitCall(() -> {
try {
startPatching();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
});
try {
startPatching();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Expand All @@ -290,28 +287,6 @@ protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirem
LOGGER.info("Patchwork is still an early project, things might not work as expected! Let us know the issues on GitHub!");
}

private static void runWithNoExitCall(Runnable runnable) {
forbidSystemExitCall();
runnable.run();
enableSystemExitCall();
}

private static void forbidSystemExitCall() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission perm) {
if (perm.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}

private static void enableSystemExitCall() {
System.setSecurityManager(null);
}

private static void clearCache() throws IOException {
LOGGER.info("Clearing cache.");
FileUtils.deleteDirectory(new File(root, "data"));
Expand Down

0 comments on commit 8059083

Please sign in to comment.