From ac74f62ae623219fa15b5bf332e9e0b309940625 Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Thu, 30 Mar 2023 20:02:05 +0200 Subject: [PATCH 1/7] Use Log4j for logging --- build.gradle | 2 + gradle.properties | 1 + src/main/java/matcher/Matcher.java | 26 ++- src/main/java/matcher/Util.java | 3 +- .../matcher/classifier/ClassClassifier.java | 2 +- .../matcher/classifier/ClassifierUtil.java | 18 +- src/main/java/matcher/gui/Gui.java | 4 + src/main/java/matcher/gui/MatchPaneDst.java | 17 +- src/main/java/matcher/gui/MatchPaneSrc.java | 3 +- src/main/java/matcher/gui/menu/UidMenu.java | 2 +- src/main/java/matcher/gui/tab/WebViewTab.java | 2 +- .../matcher/mapping/MappingPropagator.java | 9 +- src/main/java/matcher/mapping/Mappings.java | 39 ++-- src/main/java/matcher/serdes/MatchesIo.java | 33 +-- src/main/java/matcher/srcprocess/Cfr.java | 21 +- .../java/matcher/srcprocess/Fernflower.java | 12 +- src/main/java/matcher/srcprocess/Procyon.java | 5 +- .../java/matcher/srcprocess/SrcDecorator.java | 11 +- src/main/java/matcher/type/Analysis.java | 191 +++++++++--------- .../java/matcher/type/ClassEnvironment.java | 3 +- .../matcher/type/ClassFeatureExtractor.java | 7 +- src/main/java/module-info.java | 1 + src/main/resources/log4j2.xml | 13 ++ 23 files changed, 235 insertions(+), 190 deletions(-) create mode 100644 src/main/resources/log4j2.xml diff --git a/build.gradle b/build.gradle index a9fe4b88..bc5a84ea 100644 --- a/build.gradle +++ b/build.gradle @@ -57,6 +57,7 @@ javafx { dependencies { api "org.ow2.asm:asm:${asm_version}" api "org.ow2.asm:asm-tree:${asm_version}" + api "org.apache.logging.log4j:log4j-api:${log4j_version}" api "net.fabricmc:mapping-io:${mappingio_version}" implementation "org.ow2.asm:asm-commons:${asm_version}" implementation "org.ow2.asm:asm-util:${asm_version}" @@ -64,6 +65,7 @@ dependencies { implementation "net.fabricmc:cfr:${fabric_cfr_version}" implementation "net.fabricmc:fabric-fernflower:${fabric_fernflower_version}" implementation "org.bitbucket.mstrobel:procyon-compilertools:${procyon_version}" + runtimeOnly "org.apache.logging.log4j:log4j-core:${log4j_version}" // JavaFX for all platforms (needed for cross-platform fat jar) runtimeOnly "org.openjfx:javafx-base:${javafx_version}:win" diff --git a/gradle.properties b/gradle.properties index f3ccf2a6..f35007c9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,3 +18,4 @@ mappingio_version = 0.3.0 javaparser_version = 3.24.2 javafx_version = 17.0.2 checkstyle_version = 10.3.4 +log4j_version = 2.20.0 diff --git a/src/main/java/matcher/Matcher.java b/src/main/java/matcher/Matcher.java index 5c99baff..7d1340f9 100644 --- a/src/main/java/matcher/Matcher.java +++ b/src/main/java/matcher/Matcher.java @@ -26,6 +26,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; + import matcher.classifier.ClassClassifier; import matcher.classifier.ClassifierLevel; import matcher.classifier.FieldClassifier; @@ -166,7 +169,7 @@ public void match(ClassInstance a, ClassInstance b) { if (a.getArrayDimensions() != b.getArrayDimensions()) throw new IllegalArgumentException("the classes don't have the same amount of array dimensions"); if (a.getMatch() == b) return; - System.out.println("match class "+a+" -> "+b+(a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Matching class {} -> {}{}", a, b, (a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); if (a.getMatch() != null) { a.getMatch().setMatch(null); @@ -293,7 +296,7 @@ public void match(MethodInstance a, MethodInstance b) { if (a.getCls().getMatch() != b.getCls()) throw new IllegalArgumentException("the methods don't belong to the same class"); if (a.getMatch() == b) return; - System.out.println("match method "+a+" -> "+b+(a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Matching method {} -> {}{}", a, b, (a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); Set membersA = a.getAllHierarchyMembers(); Set membersB = b.getAllHierarchyMembers(); @@ -362,7 +365,7 @@ public void match(FieldInstance a, FieldInstance b) { if (a.getCls().getMatch() != b.getCls()) throw new IllegalArgumentException("the methods don't belong to the same class"); if (a.getMatch() == b) return; - System.out.println("match field "+a+" -> "+b+(a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Matching field {} -> {}{}", a, b, (a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); if (a.getMatch() != null) a.getMatch().setMatch(null); if (b.getMatch() != null) b.getMatch().setMatch(null); @@ -380,7 +383,7 @@ public void match(MethodVarInstance a, MethodVarInstance b) { if (a.isArg() != b.isArg()) throw new IllegalArgumentException("the method vars are not of the same kind"); if (a.getMatch() == b) return; - System.out.println("match method arg "+a+" -> "+b+(a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Matching method arg {} -> {}{}", a, b, (a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); if (a.getMatch() != null) a.getMatch().setMatch(null); if (b.getMatch() != null) b.getMatch().setMatch(null); @@ -395,7 +398,7 @@ public void unmatch(ClassInstance cls) { if (cls == null) throw new NullPointerException("null class"); if (cls.getMatch() == null) return; - System.out.println("unmatch class "+cls+" (was "+cls.getMatch()+")"+(cls.hasMappedName() ? " ("+cls.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Unmatching class {} (was {}){}", cls, cls.getMatch(), (cls.hasMappedName() ? " ("+cls.getName(NameType.MAPPED_PLAIN)+")" : "")); cls.getMatch().setMatch(null); cls.setMatch(null); @@ -417,7 +420,7 @@ public void unmatch(MemberInstance m) { if (m == null) throw new NullPointerException("null member"); if (m.getMatch() == null) return; - System.out.println("unmatch member "+m+" (was "+m.getMatch()+")"+(m.hasMappedName() ? " ("+m.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Unmatching member {} (was {}){}", m, m.getMatch(), (m.hasMappedName() ? " ("+m.getName(NameType.MAPPED_PLAIN)+")" : "")); if (m instanceof MethodInstance) { for (MethodVarInstance arg : ((MethodInstance) m).getArgs()) { @@ -445,7 +448,7 @@ public void unmatch(MethodVarInstance a) { if (a == null) throw new NullPointerException("null method var"); if (a.getMatch() == null) return; - System.out.println("unmatch method var "+a+" (was "+a.getMatch()+")"+(a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); + LOGGER.debug("Unmatching method var {} (was {}){}", a, a.getMatch(), (a.hasMappedName() ? " ("+a.getName(NameType.MAPPED_PLAIN)+")" : "")); a.getMatch().setMatch(null); a.setMatch(null); @@ -524,7 +527,7 @@ public boolean autoMatchClasses(ClassifierLevel level, double absThreshold, doub match(entry.getKey(), entry.getValue()); } - System.out.println("Auto matched "+matches.size()+" classes ("+(classes.size() - matches.size())+" unmatched, "+env.getClassesA().size()+" total)"); + LOGGER.info("Auto matched {} classes ({} unmatched, {} total)", matches.size(), (classes.size() - matches.size()), env.getClassesA().size()); return !matches.isEmpty(); } @@ -570,7 +573,7 @@ public boolean autoMatchMethods(ClassifierLevel level, double absThreshold, doub match(entry.getKey(), entry.getValue()); } - System.out.println("Auto matched "+matches.size()+" methods ("+totalUnmatched.get()+" unmatched)"); + LOGGER.info("Auto matched {} methods ({} unmatched)", matches.size(), totalUnmatched.get()); return !matches.isEmpty(); } @@ -591,7 +594,7 @@ public boolean autoMatchFields(ClassifierLevel level, double absThreshold, doubl match(entry.getKey(), entry.getValue()); } - System.out.println("Auto matched "+matches.size()+" fields ("+totalUnmatched.get()+" unmatched)"); + LOGGER.info("Auto matched {} fields ({} unmatched)", matches.size(), totalUnmatched.get()); return !matches.isEmpty(); } @@ -706,7 +709,7 @@ private boolean autoMatchMethodVars(boolean isArg, Function int compareInsns(AbstractInsnNode insnA, AbstractInsnNode ins implB.getOwner(), implB.getName(), implB.getDesc(), Util.isCallToInterface(implB), env) ? COMPARED_SIMILAR : COMPARED_DISTINCT; default: - System.out.println("unexpected impl tag: "+implA.getTag()); + Matcher.LOGGER.warn("Unexpected impl tag: "+implA.getTag()); } } else if (!Util.isIrrelevantBsm(a.bsm)) { - System.out.printf("unknown invokedynamic bsm: %s/%s%s (tag=%d iif=%b)%n", a.bsm.getOwner(), a.bsm.getName(), a.bsm.getDesc(), a.bsm.getTag(), a.bsm.isInterface()); + Matcher.LOGGER.warn("Unknown invokedynamic bsm: {}/{}{} (tag={} iif={})", + a.bsm.getOwner(), a.bsm.getName(), a.bsm.getDesc(), a.bsm.getTag(), a.bsm.isInterface()); } // TODO: implement @@ -622,10 +624,10 @@ private static int[] mapLists(T listA, T listB, ListElementRetriever int[] mapLists(T listA, T listB, ListElementRetriever= COMPARED_DISTINCT) { assert c - keepCost == COMPARED_DISTINCT; - //System.out.printf("%d/%d rep %s -> %s%n", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1))); + //Matcher.LOGGER.debug("{}/{} rep {} -> {}", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1))); ret[i - 1] = -1; } else { - //System.out.printf("%d/%d eq %s - %s%n", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1))); + //Matcher.LOGGER.debug("{}/{} eq {} - {}", i-1, j-1, toString(elementRetriever.apply(listA, i - 1)), toString(elementRetriever.apply(listB, j - 1))); ret[i - 1] = j - 1; /*U e = elementRetriever.apply(listA, i - 1); @@ -658,11 +660,11 @@ private static int[] mapLists(T listA, T listB, ListElementRetriever stack, RankResult for (String part : parts) { String op = part.toLowerCase(Locale.ENGLISH); - //System.out.printf("stack: %s, op: %s%n", stack, op); + //Matcher.LOGGER.debug("stack: {}, op: {}", stack, op); byte opTypeA = OP_TYPE_NONE; byte opTypeB = OP_TYPE_NONE; @@ -489,7 +490,7 @@ private Boolean evalFilter(List stack, RankResult if (type == OP_TYPE_NONE) continue; if (stack.isEmpty()) { - System.err.println("stack underflow"); + Matcher.LOGGER.error("Stack underflow"); return null; } @@ -504,7 +505,7 @@ private Boolean evalFilter(List stack, RankResult || type == OP_TYPE_COMPARABLE && operand instanceof Comparable; if (!valid) { - System.err.println("invalid operand type"); + Matcher.LOGGER.debug("Invalid operand type"); return null; } @@ -516,7 +517,7 @@ private Boolean evalFilter(List stack, RankResult ClassInstance cls = env.getClsByName((String) operand); if (cls == null) { - System.err.println("unknown class "+operand); + Matcher.LOGGER.debug("Unknown class "+operand); return null; } else { operand = cls; @@ -530,7 +531,7 @@ private Boolean evalFilter(List stack, RankResult } } - //System.out.printf("opA: %s, opB: %s%n", opA, opB); + //Matcher.LOGGER.debug("opA: {}, opB: {}", opA, opB); switch (op) { case "a": @@ -609,16 +610,16 @@ private Boolean evalFilter(List stack, RankResult } } - //System.out.printf("res stack: %s%n", stack); + //Matcher.LOGGER.debug("Res stack: {}", stack); if (stack.isEmpty() || stack.size() > 2) { - System.err.println("no result"); + Matcher.LOGGER.info("No result found"); return null; } else if (stack.size() == 1) { if (stack.get(0) instanceof Boolean) { return (Boolean) stack.get(0); } else { - System.err.println("invalid result"); + Matcher.LOGGER.error("Invalid result"); return null; } } else { // 2 elements on the stack, use equals diff --git a/src/main/java/matcher/gui/MatchPaneSrc.java b/src/main/java/matcher/gui/MatchPaneSrc.java index 341fe41c..19a81b7f 100644 --- a/src/main/java/matcher/gui/MatchPaneSrc.java +++ b/src/main/java/matcher/gui/MatchPaneSrc.java @@ -29,6 +29,7 @@ import javafx.scene.control.TreeView; import javafx.scene.paint.Color; +import matcher.Matcher; import matcher.NameType; import matcher.Util; import matcher.config.Config; @@ -123,7 +124,7 @@ private void retrieveCellTextColors() { try { css = parser.parse(Config.getTheme().getUrl().toURI().toURL()); } catch (IOException | URISyntaxException e) { - System.err.println("CSS parsing failed"); + Matcher.LOGGER.error("CSS parsing failed"); return; } diff --git a/src/main/java/matcher/gui/menu/UidMenu.java b/src/main/java/matcher/gui/menu/UidMenu.java index 37b04b01..84df5d9d 100644 --- a/src/main/java/matcher/gui/menu/UidMenu.java +++ b/src/main/java/matcher/gui/menu/UidMenu.java @@ -318,7 +318,7 @@ private void assignMissing() { } } - System.out.printf("uids assigned: %d class, %d method, %d field%n", + Matcher.LOGGER.info("UIDs assigned: {} class, {} method, {} field", nextClassUid - env.nextClassUid, nextMethodUid - env.nextMethodUid, nextFieldUid - env.nextFieldUid); diff --git a/src/main/java/matcher/gui/tab/WebViewTab.java b/src/main/java/matcher/gui/tab/WebViewTab.java index 555faa22..d5e75b3a 100644 --- a/src/main/java/matcher/gui/tab/WebViewTab.java +++ b/src/main/java/matcher/gui/tab/WebViewTab.java @@ -46,7 +46,7 @@ protected void displayHtml(String html) { html = template.replace("%text%", html) .replace("%theme_path%", Config.getTheme().getUrl().toExternalForm()); - // System.out.println(html); + //Matcher.LOGGER.debug(html); webView.getEngine().loadContent(html); } diff --git a/src/main/java/matcher/mapping/MappingPropagator.java b/src/main/java/matcher/mapping/MappingPropagator.java index f908ed1e..01586207 100644 --- a/src/main/java/matcher/mapping/MappingPropagator.java +++ b/src/main/java/matcher/mapping/MappingPropagator.java @@ -4,6 +4,7 @@ import java.util.Set; import java.util.function.DoubleConsumer; +import matcher.Matcher; import matcher.NameType; import matcher.Util; import matcher.type.ClassEnvironment; @@ -87,7 +88,7 @@ public static boolean propagateNames(ClassEnvironment env, DoubleConsumer progre } } - System.out.printf("Propagated %d method names, %d method arg names.", propagatedMethodNames, propagatedArgNames); + Matcher.LOGGER.info("Propagated {} method names and {} method arg names.", propagatedMethodNames, propagatedArgNames); return propagatedMethodNames > 0 || propagatedArgNames > 0; } @@ -114,10 +115,10 @@ public static boolean fixRecordMemberNames(ClassEnvironment env, NameType nameTy if (linkedMethod.isNameObfuscated() && (!field.isNameObfuscated() || !linkedMethod.hasMappedName() || field.hasMappedName())) { - System.out.println("copy record component name for method "+linkedMethod+" from field "+field+" -> "+fieldName); + Matcher.LOGGER.debug("Copying record component name for method {} from field {} -> {}", linkedMethod, field, fieldName); linkedMethod.setMappedName(fieldName); } else { - System.out.println("copy record component name for field "+field+" from method "+linkedMethod+" -> "+methodName); + Matcher.LOGGER.debug("Copying record component name for field {} from method {} -> {}", field, linkedMethod, methodName); field.setMappedName(methodName); } @@ -125,7 +126,7 @@ public static boolean fixRecordMemberNames(ClassEnvironment env, NameType nameTy } } - System.out.printf("Fixed %d names.%n", modified); + Matcher.LOGGER.info("Fixed {} record names.", modified); return modified > 0; } diff --git a/src/main/java/matcher/mapping/Mappings.java b/src/main/java/matcher/mapping/Mappings.java index 97827a78..fb957851 100644 --- a/src/main/java/matcher/mapping/Mappings.java +++ b/src/main/java/matcher/mapping/Mappings.java @@ -23,6 +23,7 @@ import net.fabricmc.mappingio.adapter.RegularAsFlatMappingVisitor; import net.fabricmc.mappingio.format.MappingFormat; +import matcher.Matcher; import matcher.NameType; import matcher.Util; import matcher.type.ClassEnv; @@ -86,7 +87,7 @@ public boolean visitClass(String srcName) { cur = cls = findClass(srcName, fieldSource, env); if (cls == null) { - if (warnedClasses.add(srcName)) System.out.println("can't find mapped class "+srcName); + if (warnedClasses.add(srcName)) Matcher.LOGGER.warn("Can't find mapped class {}", srcName); return false; } @@ -102,7 +103,7 @@ public boolean visitMethod(String srcName, String srcDesc) { cur = method = cls.getMethod(srcName, srcDesc, fieldSource.type); if (method == null || !method.isReal()) { - System.out.printf("can't find mapped method %s/%s%s%n", + Matcher.LOGGER.warn("Can't find mapped method {}/{}{}", cls.getName(fieldSource.type), srcName, srcDesc); return false; } @@ -138,28 +139,28 @@ public boolean visitMethodVar(int asmIndex, int lvIndex, int startOpIdx, String private MethodVarInstance getMethodVar(int varIndex, int lvIndex, int startOpIdx, int asmIndex, boolean isArg) { if (isArg && varIndex < -1 || varIndex >= method.getArgs().length) { - System.out.println("invalid var index "+varIndex+" for method "+method); + Matcher.LOGGER.warn("Invalid var index {} for method {}", varIndex, method); } else if (lvIndex < -1 || lvIndex >= (isArg ? method.getArgs() : method.getVars()).length * 2 + 1) { - System.out.println("invalid lv index "+lvIndex+" for method "+method); + Matcher.LOGGER.warn("Invalid lv index {} for method {}", lvIndex, method); } else if (asmIndex < -1) { - System.out.println("invalid lv asm index "+asmIndex+" for method "+method); + Matcher.LOGGER.warn("Invalid lv asm index {} for method {}", asmIndex, method); } else { if (!isArg || varIndex == -1) { if (asmIndex >= 0) { varIndex = findVarIndexByAsm(isArg ? method.getArgs() : method.getVars(), asmIndex); if (varIndex == -1) { - System.out.println("invalid lv asm index "+asmIndex+" for method "+method); + Matcher.LOGGER.warn("Invalid lv asm index {} for method {}", asmIndex, method); return null; } } else if (lvIndex <= -1) { - System.out.println("missing arg+lvt index "+lvIndex+" for method "+method); + Matcher.LOGGER.warn("Missing arg+lvt index {} for method {}", lvIndex, method); return null; } else { varIndex = findVarIndexByLv(isArg ? method.getArgs() : method.getVars(), lvIndex, startOpIdx); if (varIndex == -1) { - System.out.println("invalid lv index "+lvIndex+" for method "+method); + Matcher.LOGGER.warn("Invalid lv index {} for method {}", lvIndex, method); return null; } } @@ -168,12 +169,12 @@ private MethodVarInstance getMethodVar(int varIndex, int lvIndex, int startOpIdx MethodVarInstance var = isArg ? method.getArg(varIndex) : method.getVar(varIndex); if (lvIndex != -1 && var.getLvIndex() != lvIndex) { - System.out.println("mismatched lv index "+lvIndex+" for method "+method); + Matcher.LOGGER.warn("Mismatched lv index {} for method {}", lvIndex, method); return null; } if (asmIndex != -1 && var.getAsmIndex() != asmIndex) { - System.out.println("mismatched lv asm index "+asmIndex+" for method "+method); + Matcher.LOGGER.warn("Mismatched lv asm index {} for method {}", asmIndex, method); return null; } @@ -192,7 +193,7 @@ public boolean visitField(String srcName, String srcDesc) { cur = field = cls.getField(srcName, srcDesc, fieldSource.type); if (field == null || !field.isReal()) { - System.out.println("can't find mapped field "+cls.getName(fieldSource.type)+"/"+srcName); + Matcher.LOGGER.warn("Can't find mapped field {}/{}", cls.getName(fieldSource.type), srcName); return false; } @@ -231,7 +232,7 @@ public void visitDstName(MappedElementKind targetKind, int namespace, String nam String prefix = env.getGlobal().classUidPrefix; if (!name.startsWith(prefix)) { - System.out.println("Invalid uid class name "+name); + Matcher.LOGGER.warn("Invalid uid class name {}", name); return; } else { int innerNameStart = name.lastIndexOf('$') + 1; @@ -241,7 +242,7 @@ public void visitDstName(MappedElementKind targetKind, int namespace, String nam int subPrefixStart = prefix.lastIndexOf('/') + 1; if (!name.startsWith(prefix.substring(subPrefixStart), innerNameStart)) { - System.out.println("Invalid uid class name "+name); + Matcher.LOGGER.warn("Invalid uid class name {}", name); return; } else { uidStr = name.substring(innerNameStart + prefix.length() - subPrefixStart); @@ -253,7 +254,7 @@ public void visitDstName(MappedElementKind targetKind, int namespace, String nam int uid = Integer.parseInt(uidStr); if (uid < 0) { - System.out.println("Invalid class uid "+uid); + Matcher.LOGGER.warn("Invalid class uid {}", uid); return; } else if (cls.getUid() < 0 || cls.getUid() > uid || replace) { cls.setUid(uid); @@ -289,13 +290,13 @@ public void visitDstName(MappedElementKind targetKind, int namespace, String nam String prefix = env.getGlobal().fieldUidPrefix; if (!name.startsWith(prefix)) { - System.out.println("Invalid uid field name "+name); + Matcher.LOGGER.warn("Invalid uid field name {}", name); return; } else { int uid = Integer.parseInt(name.substring(prefix.length())); if (uid < 0) { - System.out.println("Invalid field uid "+uid); + Matcher.LOGGER.warn("Invalid field uid {}", uid); return; } else if (field.getUid() < 0 || field.getUid() > uid || replace) { for (FieldInstance f : field.getAllHierarchyMembers()) { @@ -333,13 +334,13 @@ public void visitDstName(MappedElementKind targetKind, int namespace, String nam String prefix = env.getGlobal().methodUidPrefix; if (!name.startsWith(prefix)) { - System.out.println("Invalid uid method name "+name); + Matcher.LOGGER.warn("Invalid uid method name {}", name); return; } else { int uid = Integer.parseInt(name.substring(prefix.length())); if (uid < 0) { - System.out.println("Invalid method uid "+uid); + Matcher.LOGGER.warn("Invalid method uid {}", uid); return; } else if (method.getUid() < 0 || method.getUid() > uid || replace) { for (MethodInstance m : method.getAllHierarchyMembers()) { @@ -416,7 +417,7 @@ public void visitComment(MappedElementKind targetKind, String comment) { throw t; } - System.out.printf("Loaded mappings for %d classes, %d methods (%d args, %d vars) and %d fields (comments: %d/%d/%d).%n", + Matcher.LOGGER.info("Loaded mappings for {} classes, {} methods ({} args, {} vars) and {} fields (comments: {}/{}/{}).", dstNameCounts[MatchableKind.CLASS.ordinal()], dstNameCounts[MatchableKind.METHOD.ordinal()], dstNameCounts[MatchableKind.METHOD_ARG.ordinal()], diff --git a/src/main/java/matcher/serdes/MatchesIo.java b/src/main/java/matcher/serdes/MatchesIo.java index 92043b43..f521190a 100644 --- a/src/main/java/matcher/serdes/MatchesIo.java +++ b/src/main/java/matcher/serdes/MatchesIo.java @@ -167,12 +167,12 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M ClassInstance target; if (currentClass == null) { - System.err.println("Unknown a class "+idA); + Matcher.LOGGER.error("Unknown a class {}", idA); } else if ((target = env.getLocalClsByIdB(idB)) == null) { - System.err.println("Unknown b class "+idA); + Matcher.LOGGER.error("Unknown b class {}", idA); currentClass = null; } else if (!currentClass.isMatchable() || !target.isMatchable()) { - System.err.println("Unmatchable a/b class "+idA+"/"+idB); + Matcher.LOGGER.error("Unmatchable a/b class {}/{}", idA, idB); currentClass = null; } else { currentClass.setMatchable(true); @@ -189,7 +189,7 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M currentMethod = null; if (cls == null) { - System.err.println("Unknown "+side+" class "+id); + Matcher.LOGGER.error("Unknown {} class {}", side, id); } else { if (cls.hasMatch()) matcher.unmatch(cls); cls.setMatchable(false); @@ -208,11 +208,11 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M MethodInstance b; if (a == null) { - System.err.println("Unknown a method "+idA+" in class "+currentClass); + Matcher.LOGGER.error("Unknown a method {} in class {}", idA, currentClass); } else if ((b = currentClass.getMatch().getMethod(idB)) == null) { - System.err.println("Unknown b method "+idB+" in class "+currentClass.getMatch()); + Matcher.LOGGER.error("Unknown b method {} in class {}", idB, currentClass.getMatch()); } else if (!a.isMatchable() || !b.isMatchable()) { - System.err.println("Unmatchable a/b method "+idA+"/"+idB); + Matcher.LOGGER.error("Unmatchable a/b method {}/{}", idA, idB); currentMethod = null; } else { a.setMatchable(true); @@ -224,11 +224,11 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M FieldInstance b; if (a == null) { - System.err.println("Unknown a field "+idA+" in class "+currentClass); + Matcher.LOGGER.error("Unknown a field {} in class {}", idA, currentClass); } else if ((b = currentClass.getMatch().getField(idB)) == null) { - System.err.println("Unknown b field "+idB+" in class "+currentClass.getMatch()); + Matcher.LOGGER.error("Unknown b field {} in class {}", idB, currentClass.getMatch()); } else if (!a.isMatchable() || !b.isMatchable()) { - System.err.println("Unmatchable a/b field "+idA+"/"+idB); + Matcher.LOGGER.error("Unmatchable a/b field {}/{}", idA, idB); } else { a.setMatchable(true); b.setMatchable(true); @@ -248,12 +248,12 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M MemberInstance member = line.charAt(1) == 'm' ? cls.getMethod(id) : cls.getField(id); if (member == null) { - System.err.println("Unknown member "+id+" in class "+cls); + Matcher.LOGGER.error("Unknown member {} in class {}", id, cls); } else { if (member.hasMatch()) matcher.unmatch(member); if (!member.setMatchable(false)) { - System.err.printf("can't mark %s as unmatchable, already matched?%n", member); + Matcher.LOGGER.error("Can't mark {} as unmatchable, already matched?", member); } } } else if (line.startsWith("\t\tma\t") || line.startsWith("\t\tmv\t")) { // method arg or method var @@ -280,11 +280,12 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M } if (idxA < 0 || idxA >= varsA.length) { - System.err.println("Unknown a method "+type+" "+idxA+" in method "+currentMethod); + Matcher.LOGGER.error("Unknown a method {} {} in method {}", type, idxA, currentMethod); } else if (idxB < 0 || idxB >= varsB.length) { - System.err.println("Unknown b method "+type+" "+idxB+" in method "+matchedMethod); + Matcher.LOGGER.error("Unknown b method {} {} in method {}", type, idxB, matchedMethod); } else if (!varsA[idxA].isMatchable() || !varsB[idxB].isMatchable()) { - System.err.println("Unmatchable a/b method "+type+" "+idxA+"/"+idxB+" in method "+currentMethod+"/"+matchedMethod); + Matcher.LOGGER.error("Unmatchable a/b method {} {}/{} in method {}/{}", + type, idxA, idxB, currentMethod, matchedMethod); currentMethod = null; } else { varsA[idxA].setMatchable(true); @@ -314,7 +315,7 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M } if (idx < 0 || idx >= vars.length) { - System.err.println("Unknown a method "+type+" "+idx+" in method "+method); + Matcher.LOGGER.error("Unknown a method {} {} in method {}", type, idx, method); continue; } else { MethodVarInstance var = vars[idx]; diff --git a/src/main/java/matcher/srcprocess/Cfr.java b/src/main/java/matcher/srcprocess/Cfr.java index 4edff929..13e3446b 100644 --- a/src/main/java/matcher/srcprocess/Cfr.java +++ b/src/main/java/matcher/srcprocess/Cfr.java @@ -13,6 +13,7 @@ import org.benf.cfr.reader.api.OutputSinkFactory; import org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair; +import matcher.Matcher; import matcher.NameType; import matcher.type.ClassFeatureExtractor; import matcher.type.ClassInstance; @@ -43,12 +44,12 @@ private static class Source implements ClassFileSource { @Override public void informAnalysisRelativePathDetail(String usePath, String classFilePath) { - //System.out.printf("informAnalysisRelativePathDetail %s %s%n", usePath, classFilePath); + //Matcher.LOGGER.debug("informAnalysisRelativePathDetail {} {}", usePath, classFilePath); } @Override public Collection addJar(String jarPath) { - System.out.printf("addJar %s%n", jarPath); + Matcher.LOGGER.debug("addJar {}", jarPath); throw new UnsupportedOperationException(); } @@ -61,7 +62,7 @@ public String getPossiblyRenamedPath(String path) { @Override public Pair getClassFileContent(String path) throws IOException { if (!path.endsWith(fileSuffix)) { - System.out.printf("getClassFileContent invalid path: %s%n", path); + Matcher.LOGGER.debug("getClassFileContent invalid path: {}", path); throw new NoSuchFileException(path); } @@ -69,12 +70,12 @@ public Pair getClassFileContent(String path) throws IOException ClassInstance cls = env.getClsByName(clsName, nameType); if (cls == null) { - System.out.printf("getClassFileContent missing cls: %s%n", clsName); + Matcher.LOGGER.debug("getClassFileContent missing cls: {}", clsName); throw new NoSuchFileException(path); } if (cls.getAsmNodes() == null) { - System.out.printf("getClassFileContent unknown cls: %s%n", clsName); + Matcher.LOGGER.debug("getClassFileContent unknown cls: {}", clsName); throw new NoSuchFileException(path); } @@ -97,16 +98,16 @@ public List getSupportedSinks(SinkType sinkType, Collection OutputSinkFactory.Sink getSink(SinkType sinkType, SinkClass sinkClass) { switch (sinkType) { case EXCEPTION: - return str -> System.out.println("e "+str); + return str -> Matcher.LOGGER.debug("e {}", str); case JAVA: return sb::append; case PROGRESS: - return str -> System.out.println("p "+str); + return str -> Matcher.LOGGER.debug("p {}", str); case SUMMARY: - return str -> System.out.println("s "+str); + return str -> Matcher.LOGGER.debug("s {}", str); default: - System.out.println("unknown sink type: "+sinkType); - return str -> System.out.println("* "+str); + Matcher.LOGGER.warn("Unknown CFR sink type: {}", sinkType); + return str -> Matcher.LOGGER.warn("* {}", str); } } diff --git a/src/main/java/matcher/srcprocess/Fernflower.java b/src/main/java/matcher/srcprocess/Fernflower.java index fb39c473..5e73faf1 100644 --- a/src/main/java/matcher/srcprocess/Fernflower.java +++ b/src/main/java/matcher/srcprocess/Fernflower.java @@ -34,6 +34,7 @@ import org.jetbrains.java.decompiler.util.DataInputFullStream; import org.jetbrains.java.decompiler.util.TextBuffer; +import matcher.Matcher; import matcher.NameType; import matcher.type.ClassEnv; import matcher.type.ClassFeatureExtractor; @@ -45,6 +46,7 @@ public String decompile(ClassInstance cls, ClassFeatureExtractor env, NameType n // invoke ff with on-demand class lookup into matcher's state and string based output Map properties = new HashMap<>(IFernflowerPreferences.DEFAULTS); properties.put(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1"); + properties.put(IFernflowerPreferences.LOG_LEVEL, IFernflowerLogger.Severity.WARN); ResultSaver resultSaver = new ResultSaver(); DecompiledData data = new DecompiledData(); @@ -140,7 +142,7 @@ public void addSpace(ClassInstance cls, boolean isOwn) { @Override public StructClass getClass(String name) { - if (DEBUG) System.out.printf("getClass(%s)%n", name); + if (DEBUG) Matcher.LOGGER.debug("getClass({})", name); // use classes as a cache, load anything missing on demand StructClass ret = classes.get(name); @@ -231,7 +233,7 @@ public void saveClassEntry(String path, String archiveName, String qualifiedName @Override public void saveClassFile(String path, String qualifiedName, String entryName, String content, int[] mapping) { - if (DEBUG) System.out.printf("saveClassFile(%s, %s, %s, %s, %s)%n", path, qualifiedName, entryName, content, Arrays.toString(mapping)); + if (DEBUG) Matcher.LOGGER.debug("saveClassFile({}, {}, {}, {}, {})", path, qualifiedName, entryName, content, Arrays.toString(mapping)); results.put(qualifiedName, content); } @@ -242,7 +244,7 @@ public void saveClassFile(String path, String qualifiedName, String entryName, S private static class DecompiledData implements IDecompiledData { @Override public String getClassEntryName(StructClass cl, String entryname) { - if (DEBUG) System.out.printf("getClassEntryName(%s, %s)%n", cl, entryname); + if (DEBUG) Matcher.LOGGER.debug("getClassEntryName({}, {})", cl, entryname); ClassNode node = classProcessor.getMapRootClasses().get(cl.qualifiedName); @@ -258,7 +260,7 @@ public String getClassEntryName(StructClass cl, String entryname) { @Override public String getClassContent(StructClass cl) { - if (DEBUG) System.out.printf("getClassContent(%s)%n", cl); + if (DEBUG) Matcher.LOGGER.debug("getClassContent({})", cl); try { TextBuffer buffer = new TextBuffer(ClassesProcessor.AVERAGE_CLASS_SIZE); @@ -283,7 +285,7 @@ private static class BytecodeProvider implements IBytecodeProvider { @Override public byte[] getBytecode(String externalPath, String internalPath) throws IOException { - if (DEBUG) System.out.printf("getBytecode(%s, %s)%n", externalPath, internalPath); + if (DEBUG) Matcher.LOGGER.debug("getBytecode({}, {})", externalPath, internalPath); if (externalPath.startsWith(pathPrefix) && externalPath.endsWith(pathSuffix)) { String name = externalPath.substring(pathPrefix.length(), externalPath.length() - pathSuffix.length()); diff --git a/src/main/java/matcher/srcprocess/Procyon.java b/src/main/java/matcher/srcprocess/Procyon.java index 08639f24..a2914d5f 100644 --- a/src/main/java/matcher/srcprocess/Procyon.java +++ b/src/main/java/matcher/srcprocess/Procyon.java @@ -10,6 +10,7 @@ import com.strobel.decompiler.DecompilerSettings; import com.strobel.decompiler.PlainTextOutput; +import matcher.Matcher; import matcher.NameType; import matcher.type.ClassFeatureExtractor; import matcher.type.ClassInstance; @@ -42,7 +43,7 @@ public boolean tryLoadType(String internalName, Buffer buffer) { if (cls == null) { if (checkWarn(internalName)) { - System.out.printf("missing cls: %s%n", internalName); + Matcher.LOGGER.debug("Missing cls: {}", internalName); } return false; @@ -50,7 +51,7 @@ public boolean tryLoadType(String internalName, Buffer buffer) { if (cls.getAsmNodes() == null) { if (checkWarn(internalName)) { - System.out.printf("unknown cls: %s%n", internalName); + Matcher.LOGGER.debug("Unknown cls: {}", internalName); } return false; diff --git a/src/main/java/matcher/srcprocess/SrcDecorator.java b/src/main/java/matcher/srcprocess/SrcDecorator.java index b31a3c43..96ac6a51 100644 --- a/src/main/java/matcher/srcprocess/SrcDecorator.java +++ b/src/main/java/matcher/srcprocess/SrcDecorator.java @@ -29,6 +29,7 @@ import com.github.javaparser.ast.comments.JavadocComment; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import matcher.Matcher; import matcher.NameType; import matcher.type.ClassInstance; import matcher.type.FieldInstance; @@ -174,7 +175,7 @@ private static String tryFixCodeFormat(String src, List problems) { } private static String moveStatement(String source, Range slice, Position to) { - System.out.println("Shifting " + slice + " to " + to); + Matcher.LOGGER.debug("Shifting " + slice + " to " + to); //Remember that lines are counted from 1 not 0, so the indexes have to be offset backwards List lines = new BufferedReader(new StringReader(source)).lines().collect(Collectors.toList()); @@ -284,7 +285,7 @@ public void visit(EnumDeclaration n, TypeResolver resolver) { private void visitCls(TypeDeclaration n, TypeResolver resolver) { ClassInstance cls = resolver.getCls(n); - //System.out.println("cls "+n.getName().getIdentifier()+" = "+cls+" at "+n.getRange()); + //Matcher.LOGGER.debug("cls "+n.getName().getIdentifier()+" = "+cls+" at "+n.getRange()); if (cls != null) { handleComment(cls.getMappedComment(), n); @@ -296,7 +297,7 @@ private void visitCls(TypeDeclaration n, TypeResolver resolver) { @Override public void visit(ConstructorDeclaration n, TypeResolver resolver) { MethodInstance m = resolver.getMethod(n); - //System.out.println("ctor "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); + //Matcher.LOGGER.debug("ctor "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); if (m != null) { handleMethodComment(m, n, resolver); @@ -316,7 +317,7 @@ public void visit(ConstructorDeclaration n, TypeResolver resolver) { @Override public void visit(MethodDeclaration n, TypeResolver resolver) { MethodInstance m = resolver.getMethod(n); - //System.out.println("mth "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); + //Matcher.LOGGER.debug("mth "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); if (m != null) { handleMethodComment(m, n, resolver); @@ -336,7 +337,7 @@ public void visit(FieldDeclaration n, TypeResolver resolver) { for (VariableDeclarator var : n.getVariables()) { FieldInstance f = resolver.getField(var); - //System.out.println("fld "+v.getName().getIdentifier()+" = "+f+" at "+v.getRange()); + //Matcher.LOGGER.debug("fld "+v.getName().getIdentifier()+" = "+f+" at "+v.getRange()); if (f != null) { if (f.getMappedComment() != null) { diff --git a/src/main/java/matcher/type/Analysis.java b/src/main/java/matcher/type/Analysis.java index 2d417e30..b2e1661a 100644 --- a/src/main/java/matcher/type/Analysis.java +++ b/src/main/java/matcher/type/Analysis.java @@ -1,6 +1,5 @@ package matcher.type; -import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayDeque; @@ -48,6 +47,7 @@ import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceMethodVisitor; +import matcher.Matcher; import matcher.NameType; import matcher.Util; @@ -56,7 +56,7 @@ static void analyzeMethod(MethodInstance method, CommonClasses common) { MethodNode asmNode = method.getAsmNode(); if (asmNode == null || (asmNode.access & Opcodes.ACC_ABSTRACT) != 0 || asmNode.instructions.size() == 0) return; - System.out.println(method.getDisplayName(NameType.MAPPED_PLAIN, true)); + Matcher.LOGGER.debug(method.getDisplayName(NameType.MAPPED_PLAIN, true)); dump(asmNode); StateRecorder rec = new StateRecorder(method, common); @@ -737,14 +737,14 @@ static void analyzeMethod(MethodInstance method, CommonClasses common) { } } - rec.dump(il, System.out); + rec.dump(il); BitSet entryPoints = getEntryPoints(asmNode, exitPoints); applyTryCatchExits(asmNode, entryPoints, exitPoints); addDirectExits(il, entryPoints, exitPoints); purgeLocals(il, rec, entryPoints, exitPoints); - rec.dump(il, System.out); + rec.dump(il); createLocalVariables(il, rec, entryPoints, exitPoints, asmNode.localVariables); } @@ -1144,12 +1144,12 @@ private static List createLocalVariables(InsnList il, StateRe lvToVar = null; - System.out.println("Local vars raw:"); + Matcher.LOGGER.debug("Local vars raw:"); for (int i = 0; i < varCount; i++) { ExecState state = rec.getState(startIndices[i]); - System.out.printf(" %d: LV %d @ %d - %d: %s\t\t(%s)%n", + Matcher.LOGGER.debug(" {}: LV {} @ {} - {}: {}\t\t({})", i, varToLv[i], startIndices[i], endIndices[i], state.locals[varToLv[i]].toString(), rec.varSources[state.localVarIds[varToLv[i]] - 1].name()); } @@ -1255,12 +1255,12 @@ private static List createLocalVariables(InsnList il, StateRe } } - System.out.println("Local vars:"); + Matcher.LOGGER.debug("Local vars:"); for (int i = 0; i < varCount; i++) { ExecState state = rec.getState(startIndices[i]); - System.out.printf(" %d: LV %d @ %d - %d: %s\t\t(%s)%n", + Matcher.LOGGER.debug(" {}: LV {} @ {} - {}: {}\t\t({})", i, varToLv[i], startIndices[i], endIndices[i], state.locals[varToLv[i]].toString(), rec.varSources[state.localVarIds[varToLv[i]] - 1].name()); } @@ -1282,14 +1282,15 @@ private static List createLocalVariables(InsnList il, StateRe } if (!mismatch) { - System.out.println("Existing vars matched!"); + Matcher.LOGGER.debug("Existing vars matched!"); } else { - System.out.println("Existing vars mismatch:"); + Matcher.LOGGER.debug("Existing vars mismatch:"); for (int i = 0; i < orig.size(); i++) { LocalVariableNode lvn = orig.get(i); - System.out.printf(" %d: LV %d @ %d - %d: %s%n", i, lvn.index, il.indexOf(lvn.start), il.indexOf(lvn.end) - 1, lvn.desc); + Matcher.LOGGER.debug(" {}: LV {} @ {} - {}: {}", + i, lvn.index, il.indexOf(lvn.start), il.indexOf(lvn.end) - 1, lvn.desc); } } } @@ -1717,70 +1718,72 @@ public int getNextVarId(VarSource source) { return ++nextVarId; } - public void dump(InsnList il, PrintStream ps) { + public void dump(InsnList il) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < states.length; i++) { ExecState state = states[i]; - ps.print(i); - ps.print(": "); + sb.append(i); + sb.append(": "); if (state != null) { - dumpVars(state.locals, state.localVarIds, ps); - ps.print(" | "); - dumpVars(state.stack, state.stackVarIds, ps); + dumpVars(state.locals, state.localVarIds, sb); + sb.append(" | "); + dumpVars(state.stack, state.stackVarIds, sb); } else { - ps.print(""); + sb.append(""); } - ps.print(" "); + sb.append(' '); AbstractInsnNode ain = il.get(i); int op = ain.getOpcode(); if (op != -1) { - ps.print(Printer.OPCODES[ain.getOpcode()]); + sb.append(Printer.OPCODES[ain.getOpcode()]); } switch (ain.getType()) { case AbstractInsnNode.INSN: break; case AbstractInsnNode.INT_INSN: - ps.print(' '); + sb.append(' '); if (op == Opcodes.BIPUSH || op == Opcodes.SIPUSH) { - ps.print(((IntInsnNode) ain).operand); + sb.append(((IntInsnNode) ain).operand); } else { - ps.print(Printer.TYPES[((IntInsnNode) ain).operand]); + sb.append(Printer.TYPES[((IntInsnNode) ain).operand]); } break; case AbstractInsnNode.VAR_INSN: - ps.print(' '); - ps.print(((VarInsnNode) ain).var); + sb.append(' '); + sb.append(((VarInsnNode) ain).var); break; case AbstractInsnNode.TYPE_INSN: - ps.print(' '); - ps.print(((TypeInsnNode) ain).desc); + sb.append(' '); + sb.append(((TypeInsnNode) ain).desc); break; case AbstractInsnNode.FIELD_INSN: { FieldInsnNode in = (FieldInsnNode) ain; - ps.print(' '); - ps.print(in.owner); - ps.print('/'); - ps.print(in.name); - ps.print(' '); - ps.print(in.desc); + sb.append(' '); + sb.append(in.owner); + sb.append('/'); + sb.append(in.name); + sb.append(' '); + sb.append(in.desc); break; } case AbstractInsnNode.METHOD_INSN: { MethodInsnNode in = (MethodInsnNode) ain; - ps.print(' '); - ps.print(in.owner); - ps.print('/'); - ps.print(in.name); - ps.print(in.desc); - ps.print(" itf="); - ps.print(in.itf); + sb.append(' '); + sb.append(in.owner); + sb.append('/'); + sb.append(in.name); + sb.append(in.desc); + sb.append(" itf="); + sb.append(in.itf); break; } case AbstractInsnNode.INVOKE_DYNAMIC_INSN: { @@ -1789,108 +1792,110 @@ public void dump(InsnList il, PrintStream ps) { break; } case AbstractInsnNode.JUMP_INSN: - ps.print(' '); - ps.print(il.indexOf(((JumpInsnNode) ain).label)); + sb.append(' '); + sb.append(il.indexOf(((JumpInsnNode) ain).label)); break; case AbstractInsnNode.LDC_INSN: - ps.print(' '); - ps.print(((LdcInsnNode) ain).cst); + sb.append(' '); + sb.append(((LdcInsnNode) ain).cst); break; case AbstractInsnNode.IINC_INSN: - ps.print(' '); - ps.print(((IincInsnNode) ain).var); - ps.print(' '); - ps.print(((IincInsnNode) ain).incr); + sb.append(' '); + sb.append(((IincInsnNode) ain).var); + sb.append(' '); + sb.append(((IincInsnNode) ain).incr); break; case AbstractInsnNode.TABLESWITCH_INSN: { TableSwitchInsnNode in = (TableSwitchInsnNode) ain; - ps.print(" min="); - ps.print(in.min); - ps.print(" max="); - ps.print(in.max); - ps.print(" def="); - ps.print(il.indexOf(in.dflt)); + sb.append(" min="); + sb.append(in.min); + sb.append(" max="); + sb.append(in.max); + sb.append(" def="); + sb.append(il.indexOf(in.dflt)); for (int j = 0; j < in.labels.size(); j++) { - ps.print(' '); - ps.print(il.indexOf(in.labels.get(j))); + sb.append(' '); + sb.append(il.indexOf(in.labels.get(j))); } break; } case AbstractInsnNode.LOOKUPSWITCH_INSN: { LookupSwitchInsnNode in = (LookupSwitchInsnNode) ain; - ps.print(" def="); - ps.print(il.indexOf(in.dflt)); + sb.append(" def="); + sb.append(il.indexOf(in.dflt)); for (int j = 0; j < in.keys.size(); j++) { - ps.print(' '); - ps.print(in.keys.get(j)); - ps.print('='); - ps.print(il.indexOf(in.labels.get(j))); + sb.append(' '); + sb.append(in.keys.get(j)); + sb.append('='); + sb.append(il.indexOf(in.labels.get(j))); } break; } case AbstractInsnNode.MULTIANEWARRAY_INSN: { MultiANewArrayInsnNode in = (MultiANewArrayInsnNode) ain; - ps.print(' '); - ps.print(in.desc); - ps.print(" dims="); - ps.print(in.dims); + sb.append(' '); + sb.append(in.desc); + sb.append(" dims="); + sb.append(in.dims); break; } case AbstractInsnNode.LABEL: - ps.print("LABEL "); - ps.print(i); + sb.append("LABEL "); + sb.append(i); break; case AbstractInsnNode.FRAME: - ps.print("FRAME"); + sb.append("FRAME"); break; case AbstractInsnNode.LINE: - ps.print("LINE "); - ps.print(((LineNumberNode) ain).line); + sb.append("LINE "); + sb.append(((LineNumberNode) ain).line); break; default: throw new UnsupportedOperationException("unknown insn: "+ain); } - ps.println(); + sb.append('\n'); } + + Matcher.LOGGER.debug(sb.toString()); } - private void dumpVars(ClassInstance[] types, int[] ids, PrintStream ps) { - ps.print('['); + private void dumpVars(ClassInstance[] types, int[] ids, StringBuilder sb) { + sb.append('['); for (int i = 0; i < types.length; i++) { - if (i != 0) ps.print(", "); + if (i != 0) sb.append(", "); ClassInstance type = types[i]; int id = ids[i]; if (id == 0) { if (type == common.TOP) { - ps.print("TOP"); + sb.append("TOP"); } else { assert type == null; - ps.print("X"); + sb.append("X"); } } else { assert type != null; assert type != common.TOP; - ps.print(getMappedVarId(id)); - ps.print(':'); + sb.append(getMappedVarId(id)); + sb.append(':'); if (type != common.NULL) { - ps.print(type.toString()); + sb.append(type.toString()); } else { - ps.print("null"); + sb.append("null"); } } } - ps.print(']'); + sb.append(']'); } final ExecState[] states; // state at the start of every instruction index @@ -1974,7 +1979,7 @@ static void checkInitializer(FieldInstance field, ClassFeatureExtractor context) AbstractInsnNode fieldWrite = null; //dump(method.asmNode); - //System.out.println("\n------------------------\n"); + //Matcher.LOGGER.debug("\n------------------------\n"); for (Iterator it = il.iterator(); it.hasNext(); ) { AbstractInsnNode aInsn = it.next(); @@ -2078,10 +2083,10 @@ static void checkInitializer(FieldInstance field, ClassFeatureExtractor context) in = il.get(pos); initIl.add(in); - /*System.out.print(pos+": "); + /*Matcher.LOGGER.debug(pos+": "); il.get(pos).accept(visitor); - System.out.print(textifier.getText().get(0)); + Matcher.LOGGER.debug(textifier.getText().get(0)); textifier.getText().clear();*/ pos++; @@ -2092,7 +2097,7 @@ static void checkInitializer(FieldInstance field, ClassFeatureExtractor context) /* int pos = fieldWritePos; for (int i = 0; i < 100; i++) { - System.out.println(i+" ("+pos+"):"); + Matcher.LOGGER.debug(i+" ("+pos+"):"); Frame frame = frames[pos]; Frame nextFrame = frames[pos + 1]; @@ -2102,24 +2107,24 @@ static void checkInitializer(FieldInstance field, ClassFeatureExtractor context) SourceValue value = frame.getStack(frame.getStackSize() - 1); if (value.insns.isEmpty()) { - System.out.println("empty"); + Matcher.LOGGER.debug("empty"); break; } for (AbstractInsnNode ain : value.insns) { ain.accept(visitor); - System.out.print(textifier.getText().get(0)); + Matcher.LOGGER.debug(textifier.getText().get(0)); textifier.getText().clear(); } pos = method.asmNode.instructions.indexOf(value.insns.iterator().next()); }*/ - /*System.out.println(frame); - System.out.println("\n------------------------\n"); + /*Matcher.LOGGER.debug(frame); + Matcher.LOGGER.debug("\n------------------------\n"); dump(frame.getStack(frame.getStackSize() - 1).insns);*/ - //System.out.println(); + //Matcher.LOGGER.debug(); } private static int getStackDemand(AbstractInsnNode ain, Frame frame) { @@ -2386,7 +2391,7 @@ private static void dump(MethodNode method) { textifier.print(pw); } - System.out.println(writer.toString()); + Matcher.LOGGER.debug(writer.toString()); } private static void dump(Iterable il) { @@ -2404,6 +2409,6 @@ private static void dump(Iterable il) { textifier.print(pw); } - System.out.println(writer.toString()); + Matcher.LOGGER.debug(writer.toString()); } } diff --git a/src/main/java/matcher/type/ClassEnvironment.java b/src/main/java/matcher/type/ClassEnvironment.java index 7bb0cd9b..63b170bc 100644 --- a/src/main/java/matcher/type/ClassEnvironment.java +++ b/src/main/java/matcher/type/ClassEnvironment.java @@ -33,6 +33,7 @@ import org.objectweb.asm.tree.InnerClassNode; import org.objectweb.asm.tree.MethodNode; +import matcher.Matcher; import matcher.NameType; import matcher.Util; import matcher.classifier.ClassifierUtil; @@ -582,7 +583,7 @@ private static void addOuterClass(ClassInstance cls, String name, boolean create outerClass = cls.getEnv().getCreateClassInstance(ClassInstance.getId(name), createUnknown); if (outerClass == null) { - System.err.println("missing outer cls: "+name+" for "+cls); + Matcher.LOGGER.error("missing outer cls: {} for {}", name, cls); return; } } diff --git a/src/main/java/matcher/type/ClassFeatureExtractor.java b/src/main/java/matcher/type/ClassFeatureExtractor.java index 605ba5be..06459278 100644 --- a/src/main/java/matcher/type/ClassFeatureExtractor.java +++ b/src/main/java/matcher/type/ClassFeatureExtractor.java @@ -28,6 +28,7 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.TypeInsnNode; +import matcher.Matcher; import matcher.NameType; import matcher.Util; import matcher.type.Analysis.CommonClasses; @@ -240,7 +241,7 @@ private void processClassB(ClassInstance cls) { private void processMethodInsns(MethodInstance method) { if (!method.isReal()) { // artificial method to capture calls to types with incomplete/unknown hierarchy/super type method info - System.out.println("skipping empty method "+method); + Matcher.LOGGER.debug("Skipping empty method "+method); return; } @@ -303,7 +304,7 @@ private void processMethodInsns(MethodInstance method) { Util.isCallToInterface(impl), impl.getTag() == Opcodes.H_INVOKESTATIC); break; default: - System.out.println("unexpected impl tag: "+impl.getTag()); + Matcher.LOGGER.warn("Unexpected impl tag: "+impl.getTag()); } break; @@ -328,7 +329,7 @@ private MethodInstance resolveMethod(String owner, String name, String desc, boo MethodInstance ret = cls.resolveMethod(name, desc, toInterface); if (ret == null && create) { - System.out.printf("creating synthetic method %s/%s%s%n", owner, name, desc); + Matcher.LOGGER.debug("Creating synthetic method {}/{}{}", owner, name, desc); ret = new MethodInstance(cls, name, desc, isStatic); cls.addMethod(ret); diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index 861c1551..977ca918 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -11,6 +11,7 @@ exports matcher.bcremap; exports matcher.serdes; + requires transitive org.apache.logging.log4j; requires cfr; requires com.github.javaparser.core; requires intellij.fernflower; diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 00000000..ef422131 --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + From 74b13f994948041504caa9b278526a1dbdad832f Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Wed, 12 Apr 2023 15:50:42 +0200 Subject: [PATCH 2/7] Address PR feedback --- src/main/java/matcher/Util.java | 2 +- src/main/java/matcher/gui/Gui.java | 4 --- .../matcher/mapping/MappingPropagator.java | 2 +- src/main/java/matcher/serdes/MatchesIo.java | 32 +++++++++---------- src/main/java/matcher/srcprocess/Cfr.java | 10 +++--- src/main/java/matcher/type/Analysis.java | 1 + 6 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/main/java/matcher/Util.java b/src/main/java/matcher/Util.java index 2c784b8f..6670b9bf 100644 --- a/src/main/java/matcher/Util.java +++ b/src/main/java/matcher/Util.java @@ -204,7 +204,7 @@ public static Handle getTargetHandle(Handle bsm, Object[] bsmArgs) { } else if (isIrrelevantBsm(bsm)) { return null; } else { - Matcher.LOGGER.warn("unknown invokedynamic bsm: {}/{}{} (tag={} iif={})", + Matcher.LOGGER.warn("Unknown invokedynamic bsm: {}/{}{} (tag={} iif={})", bsm.getOwner(), bsm.getName(), bsm.getDesc(), bsm.getTag(), bsm.isInterface()); return null; diff --git a/src/main/java/matcher/gui/Gui.java b/src/main/java/matcher/gui/Gui.java index 17aa14fa..19269ac1 100644 --- a/src/main/java/matcher/gui/Gui.java +++ b/src/main/java/matcher/gui/Gui.java @@ -52,10 +52,6 @@ public class Gui extends Application { @Override public void start(Stage stage) { Matcher.init(); - Matcher.LOGGER.debug("Debug message"); - Matcher.LOGGER.info("Info message"); - Matcher.LOGGER.warn("Warn message"); - Matcher.LOGGER.error("Error message"); env = new ClassEnvironment(); matcher = new Matcher(env); diff --git a/src/main/java/matcher/mapping/MappingPropagator.java b/src/main/java/matcher/mapping/MappingPropagator.java index 01586207..5aab9841 100644 --- a/src/main/java/matcher/mapping/MappingPropagator.java +++ b/src/main/java/matcher/mapping/MappingPropagator.java @@ -88,7 +88,7 @@ public static boolean propagateNames(ClassEnvironment env, DoubleConsumer progre } } - Matcher.LOGGER.info("Propagated {} method names and {} method arg names.", propagatedMethodNames, propagatedArgNames); + Matcher.LOGGER.info("Propagated {} method names and {} method arg names", propagatedMethodNames, propagatedArgNames); return propagatedMethodNames > 0 || propagatedArgNames > 0; } diff --git a/src/main/java/matcher/serdes/MatchesIo.java b/src/main/java/matcher/serdes/MatchesIo.java index f521190a..eb659976 100644 --- a/src/main/java/matcher/serdes/MatchesIo.java +++ b/src/main/java/matcher/serdes/MatchesIo.java @@ -167,12 +167,12 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M ClassInstance target; if (currentClass == null) { - Matcher.LOGGER.error("Unknown a class {}", idA); + Matcher.LOGGER.warn("Unknown a class {}", idA); } else if ((target = env.getLocalClsByIdB(idB)) == null) { - Matcher.LOGGER.error("Unknown b class {}", idA); + Matcher.LOGGER.warn("Unknown b class {}", idA); currentClass = null; } else if (!currentClass.isMatchable() || !target.isMatchable()) { - Matcher.LOGGER.error("Unmatchable a/b class {}/{}", idA, idB); + Matcher.LOGGER.warn("Unmatchable a/b class {}/{}", idA, idB); currentClass = null; } else { currentClass.setMatchable(true); @@ -189,7 +189,7 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M currentMethod = null; if (cls == null) { - Matcher.LOGGER.error("Unknown {} class {}", side, id); + Matcher.LOGGER.warn("Unknown {} class {}", side, id); } else { if (cls.hasMatch()) matcher.unmatch(cls); cls.setMatchable(false); @@ -208,11 +208,11 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M MethodInstance b; if (a == null) { - Matcher.LOGGER.error("Unknown a method {} in class {}", idA, currentClass); + Matcher.LOGGER.warn("Unknown a method {} in class {}", idA, currentClass); } else if ((b = currentClass.getMatch().getMethod(idB)) == null) { - Matcher.LOGGER.error("Unknown b method {} in class {}", idB, currentClass.getMatch()); + Matcher.LOGGER.warn("Unknown b method {} in class {}", idB, currentClass.getMatch()); } else if (!a.isMatchable() || !b.isMatchable()) { - Matcher.LOGGER.error("Unmatchable a/b method {}/{}", idA, idB); + Matcher.LOGGER.warn("Unmatchable a/b method {}/{}", idA, idB); currentMethod = null; } else { a.setMatchable(true); @@ -224,11 +224,11 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M FieldInstance b; if (a == null) { - Matcher.LOGGER.error("Unknown a field {} in class {}", idA, currentClass); + Matcher.LOGGER.warn("Unknown a field {} in class {}", idA, currentClass); } else if ((b = currentClass.getMatch().getField(idB)) == null) { - Matcher.LOGGER.error("Unknown b field {} in class {}", idB, currentClass.getMatch()); + Matcher.LOGGER.warn("Unknown b field {} in class {}", idB, currentClass.getMatch()); } else if (!a.isMatchable() || !b.isMatchable()) { - Matcher.LOGGER.error("Unmatchable a/b field {}/{}", idA, idB); + Matcher.LOGGER.warn("Unmatchable a/b field {}/{}", idA, idB); } else { a.setMatchable(true); b.setMatchable(true); @@ -248,12 +248,12 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M MemberInstance member = line.charAt(1) == 'm' ? cls.getMethod(id) : cls.getField(id); if (member == null) { - Matcher.LOGGER.error("Unknown member {} in class {}", id, cls); + Matcher.LOGGER.warn("Unknown member {} in class {}", id, cls); } else { if (member.hasMatch()) matcher.unmatch(member); if (!member.setMatchable(false)) { - Matcher.LOGGER.error("Can't mark {} as unmatchable, already matched?", member); + Matcher.LOGGER.warn("Can't mark {} as unmatchable, already matched?", member); } } } else if (line.startsWith("\t\tma\t") || line.startsWith("\t\tmv\t")) { // method arg or method var @@ -280,11 +280,11 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M } if (idxA < 0 || idxA >= varsA.length) { - Matcher.LOGGER.error("Unknown a method {} {} in method {}", type, idxA, currentMethod); + Matcher.LOGGER.warn("Unknown a method {} {} in method {}", type, idxA, currentMethod); } else if (idxB < 0 || idxB >= varsB.length) { - Matcher.LOGGER.error("Unknown b method {} {} in method {}", type, idxB, matchedMethod); + Matcher.LOGGER.warn("Unknown b method {} {} in method {}", type, idxB, matchedMethod); } else if (!varsA[idxA].isMatchable() || !varsB[idxB].isMatchable()) { - Matcher.LOGGER.error("Unmatchable a/b method {} {}/{} in method {}/{}", + Matcher.LOGGER.warn("Unmatchable a/b method {} {}/{} in method {}/{}", type, idxA, idxB, currentMethod, matchedMethod); currentMethod = null; } else { @@ -315,7 +315,7 @@ public static void read(Path path, List inputDirs, boolean verifyInputs, M } if (idx < 0 || idx >= vars.length) { - Matcher.LOGGER.error("Unknown a method {} {} in method {}", type, idx, method); + Matcher.LOGGER.warn("Unknown a method {} {} in method {}", type, idx, method); continue; } else { MethodVarInstance var = vars[idx]; diff --git a/src/main/java/matcher/srcprocess/Cfr.java b/src/main/java/matcher/srcprocess/Cfr.java index 13e3446b..2f00d994 100644 --- a/src/main/java/matcher/srcprocess/Cfr.java +++ b/src/main/java/matcher/srcprocess/Cfr.java @@ -98,16 +98,16 @@ public List getSupportedSinks(SinkType sinkType, Collection OutputSinkFactory.Sink getSink(SinkType sinkType, SinkClass sinkClass) { switch (sinkType) { case EXCEPTION: - return str -> Matcher.LOGGER.debug("e {}", str); + return str -> Matcher.LOGGER.error("CFR exception: {}", str); case JAVA: return sb::append; case PROGRESS: - return str -> Matcher.LOGGER.debug("p {}", str); + return str -> Matcher.LOGGER.debug("CFR progress: {}", str); case SUMMARY: - return str -> Matcher.LOGGER.debug("s {}", str); + return str -> Matcher.LOGGER.debug("CFR summary: {}", str); default: - Matcher.LOGGER.warn("Unknown CFR sink type: {}", sinkType); - return str -> Matcher.LOGGER.warn("* {}", str); + Matcher.LOGGER.debug("Unknown CFR sink type: {}", sinkType); + return str -> Matcher.LOGGER.debug("{}", str); } } diff --git a/src/main/java/matcher/type/Analysis.java b/src/main/java/matcher/type/Analysis.java index b2e1661a..53d9666e 100644 --- a/src/main/java/matcher/type/Analysis.java +++ b/src/main/java/matcher/type/Analysis.java @@ -1896,6 +1896,7 @@ private void dumpVars(ClassInstance[] types, int[] ids, StringBuilder sb) { } sb.append(']'); + Matcher.LOGGER.debug(sb.toString()); } final ExecState[] states; // state at the start of every instruction index From 3c59870c3321945a09994aaa25bf5273e84ed9fe Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Wed, 12 Apr 2023 16:58:00 +0200 Subject: [PATCH 3/7] Switch to SLF4J and Tinylog --- build.gradle | 5 +++-- gradle.properties | 3 ++- src/main/java/matcher/Matcher.java | 6 +++--- src/main/java/module-info.java | 2 +- src/main/resources/log4j2.xml | 13 ------------- src/main/resources/tinylog.properties | 5 +++++ 6 files changed, 14 insertions(+), 20 deletions(-) delete mode 100644 src/main/resources/log4j2.xml create mode 100644 src/main/resources/tinylog.properties diff --git a/build.gradle b/build.gradle index bc5a84ea..1135e11a 100644 --- a/build.gradle +++ b/build.gradle @@ -57,7 +57,7 @@ javafx { dependencies { api "org.ow2.asm:asm:${asm_version}" api "org.ow2.asm:asm-tree:${asm_version}" - api "org.apache.logging.log4j:log4j-api:${log4j_version}" + api "org.slf4j:slf4j-api:${slf4j_version}" api "net.fabricmc:mapping-io:${mappingio_version}" implementation "org.ow2.asm:asm-commons:${asm_version}" implementation "org.ow2.asm:asm-util:${asm_version}" @@ -65,7 +65,8 @@ dependencies { implementation "net.fabricmc:cfr:${fabric_cfr_version}" implementation "net.fabricmc:fabric-fernflower:${fabric_fernflower_version}" implementation "org.bitbucket.mstrobel:procyon-compilertools:${procyon_version}" - runtimeOnly "org.apache.logging.log4j:log4j-core:${log4j_version}" + runtimeOnly "org.tinylog:tinylog-impl:${tinylog_version}" + runtimeOnly "org.tinylog:slf4j-tinylog:${tinylog_version}" // JavaFX for all platforms (needed for cross-platform fat jar) runtimeOnly "org.openjfx:javafx-base:${javafx_version}:win" diff --git a/gradle.properties b/gradle.properties index f35007c9..84757303 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,4 +18,5 @@ mappingio_version = 0.3.0 javaparser_version = 3.24.2 javafx_version = 17.0.2 checkstyle_version = 10.3.4 -log4j_version = 2.20.0 +slf4j_version = 2.0.9 +tinylog_version = 2.6.2 diff --git a/src/main/java/matcher/Matcher.java b/src/main/java/matcher/Matcher.java index 7d1340f9..09103e11 100644 --- a/src/main/java/matcher/Matcher.java +++ b/src/main/java/matcher/Matcher.java @@ -26,8 +26,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import matcher.classifier.ClassClassifier; import matcher.classifier.ClassifierLevel; @@ -839,7 +839,7 @@ public static class MatchingStatus { } public static final ExecutorService threadPool = Executors.newWorkStealingPool(); - public static final Logger LOGGER = LogManager.getLogger("Matcher"); + public static final Logger LOGGER = LoggerFactory.getLogger("Matcher"); private final ClassEnvironment env; private final ClassifierLevel autoMatchLevel = ClassifierLevel.Extra; diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index 977ca918..4ceb47b0 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -11,7 +11,7 @@ exports matcher.bcremap; exports matcher.serdes; - requires transitive org.apache.logging.log4j; + requires transitive org.slf4j; requires cfr; requires com.github.javaparser.core; requires intellij.fernflower; diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml deleted file mode 100644 index ef422131..00000000 --- a/src/main/resources/log4j2.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/src/main/resources/tinylog.properties b/src/main/resources/tinylog.properties new file mode 100644 index 00000000..1419eab1 --- /dev/null +++ b/src/main/resources/tinylog.properties @@ -0,0 +1,5 @@ +writingthread = true + +writer = console +writer.format = {date: HH:mm:ss} [{level}]: {message} +writer.level = info From bff20aae1e165693b8a0caad5395e27caecd35bd Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Wed, 12 Apr 2023 17:14:19 +0200 Subject: [PATCH 4/7] Log more details while in dev-env --- build.gradle | 4 ++++ src/main/resources/tinylog-dev.properties | 5 +++++ 2 files changed, 9 insertions(+) create mode 100644 src/main/resources/tinylog-dev.properties diff --git a/build.gradle b/build.gradle index 1135e11a..26df8c16 100644 --- a/build.gradle +++ b/build.gradle @@ -107,6 +107,10 @@ application { mainClass = 'matcher.Main' } +jar { + processResources.exclude('tinylog-dev.properties') +} + publishing { publications { mavenJava(MavenPublication) { diff --git a/src/main/resources/tinylog-dev.properties b/src/main/resources/tinylog-dev.properties new file mode 100644 index 00000000..378ad419 --- /dev/null +++ b/src/main/resources/tinylog-dev.properties @@ -0,0 +1,5 @@ +writingthread = true + +writer = console +writer.format = {date: HH:mm:ss.SSS} [{thread}/{level}]: {message} +writer.level = debug From 1556751d0d452e6043ebdd912e8fb98b1b377707 Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Wed, 12 Apr 2023 17:17:25 +0200 Subject: [PATCH 5/7] Switch spammy log lines to `trace` level --- src/main/java/matcher/type/ClassEnvironment.java | 2 +- src/main/java/matcher/type/ClassFeatureExtractor.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/matcher/type/ClassEnvironment.java b/src/main/java/matcher/type/ClassEnvironment.java index 63b170bc..b8b81983 100644 --- a/src/main/java/matcher/type/ClassEnvironment.java +++ b/src/main/java/matcher/type/ClassEnvironment.java @@ -583,7 +583,7 @@ private static void addOuterClass(ClassInstance cls, String name, boolean create outerClass = cls.getEnv().getCreateClassInstance(ClassInstance.getId(name), createUnknown); if (outerClass == null) { - Matcher.LOGGER.error("missing outer cls: {} for {}", name, cls); + Matcher.LOGGER.trace("Missing outer cls: {} for {}", name, cls); return; } } diff --git a/src/main/java/matcher/type/ClassFeatureExtractor.java b/src/main/java/matcher/type/ClassFeatureExtractor.java index 06459278..681acab2 100644 --- a/src/main/java/matcher/type/ClassFeatureExtractor.java +++ b/src/main/java/matcher/type/ClassFeatureExtractor.java @@ -329,7 +329,7 @@ private MethodInstance resolveMethod(String owner, String name, String desc, boo MethodInstance ret = cls.resolveMethod(name, desc, toInterface); if (ret == null && create) { - Matcher.LOGGER.debug("Creating synthetic method {}/{}{}", owner, name, desc); + Matcher.LOGGER.trace("Creating synthetic method {}/{}{}", owner, name, desc); ret = new MethodInstance(cls, name, desc, isStatic); cls.addMethod(ret); From 4182ff3042d841648b59d67d3ea5ab8be30c97bc Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Wed, 11 Oct 2023 10:03:29 +0200 Subject: [PATCH 6/7] Address reviews --- src/main/java/matcher/classifier/ClassifierUtil.java | 2 +- src/main/java/matcher/gui/MatchPaneDst.java | 2 +- src/main/java/matcher/gui/MatchPaneSrc.java | 2 +- src/main/java/matcher/srcprocess/SrcDecorator.java | 8 ++++---- src/main/java/matcher/type/ClassFeatureExtractor.java | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/matcher/classifier/ClassifierUtil.java b/src/main/java/matcher/classifier/ClassifierUtil.java index 26fb9c01..4939c747 100644 --- a/src/main/java/matcher/classifier/ClassifierUtil.java +++ b/src/main/java/matcher/classifier/ClassifierUtil.java @@ -378,7 +378,7 @@ private static int compareInsns(AbstractInsnNode insnA, AbstractInsnNode ins implB.getOwner(), implB.getName(), implB.getDesc(), Util.isCallToInterface(implB), env) ? COMPARED_SIMILAR : COMPARED_DISTINCT; default: - Matcher.LOGGER.warn("Unexpected impl tag: "+implA.getTag()); + Matcher.LOGGER.warn("Unexpected impl tag: {}", implA.getTag()); } } else if (!Util.isIrrelevantBsm(a.bsm)) { Matcher.LOGGER.warn("Unknown invokedynamic bsm: {}/{}{} (tag={} iif={})", diff --git a/src/main/java/matcher/gui/MatchPaneDst.java b/src/main/java/matcher/gui/MatchPaneDst.java index 88e90da7..33875eab 100644 --- a/src/main/java/matcher/gui/MatchPaneDst.java +++ b/src/main/java/matcher/gui/MatchPaneDst.java @@ -517,7 +517,7 @@ private Boolean evalFilter(List stack, RankResult ClassInstance cls = env.getClsByName((String) operand); if (cls == null) { - Matcher.LOGGER.debug("Unknown class "+operand); + Matcher.LOGGER.debug("Unknown class {}", operand); return null; } else { operand = cls; diff --git a/src/main/java/matcher/gui/MatchPaneSrc.java b/src/main/java/matcher/gui/MatchPaneSrc.java index 19a81b7f..c5f8f43e 100644 --- a/src/main/java/matcher/gui/MatchPaneSrc.java +++ b/src/main/java/matcher/gui/MatchPaneSrc.java @@ -124,7 +124,7 @@ private void retrieveCellTextColors() { try { css = parser.parse(Config.getTheme().getUrl().toURI().toURL()); } catch (IOException | URISyntaxException e) { - Matcher.LOGGER.error("CSS parsing failed"); + Matcher.LOGGER.error("CSS parsing failed", e); return; } diff --git a/src/main/java/matcher/srcprocess/SrcDecorator.java b/src/main/java/matcher/srcprocess/SrcDecorator.java index 96ac6a51..f694af43 100644 --- a/src/main/java/matcher/srcprocess/SrcDecorator.java +++ b/src/main/java/matcher/srcprocess/SrcDecorator.java @@ -285,7 +285,7 @@ public void visit(EnumDeclaration n, TypeResolver resolver) { private void visitCls(TypeDeclaration n, TypeResolver resolver) { ClassInstance cls = resolver.getCls(n); - //Matcher.LOGGER.debug("cls "+n.getName().getIdentifier()+" = "+cls+" at "+n.getRange()); + // Matcher.LOGGER.debug("cls {} = {} at {}", n.getName().getIdentifier(), cls, n.getRange()); if (cls != null) { handleComment(cls.getMappedComment(), n); @@ -297,7 +297,7 @@ private void visitCls(TypeDeclaration n, TypeResolver resolver) { @Override public void visit(ConstructorDeclaration n, TypeResolver resolver) { MethodInstance m = resolver.getMethod(n); - //Matcher.LOGGER.debug("ctor "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); + // Matcher.LOGGER.debug("ctor {} = {} at {}", n.getName().getIdentifier(), m, n.getRange()); if (m != null) { handleMethodComment(m, n, resolver); @@ -317,7 +317,7 @@ public void visit(ConstructorDeclaration n, TypeResolver resolver) { @Override public void visit(MethodDeclaration n, TypeResolver resolver) { MethodInstance m = resolver.getMethod(n); - //Matcher.LOGGER.debug("mth "+n.getName().getIdentifier()+" = "+m+" at "+n.getRange()); + // Matcher.LOGGER.debug("mth {}, = {} at {}", n.getName().getIdentifier(), m, n.getRange()); if (m != null) { handleMethodComment(m, n, resolver); @@ -337,7 +337,7 @@ public void visit(FieldDeclaration n, TypeResolver resolver) { for (VariableDeclarator var : n.getVariables()) { FieldInstance f = resolver.getField(var); - //Matcher.LOGGER.debug("fld "+v.getName().getIdentifier()+" = "+f+" at "+v.getRange()); + // Matcher.LOGGER.debug("fld {} = {} at {}", v.getName().getIdentifier(), f, v.getRange()); if (f != null) { if (f.getMappedComment() != null) { diff --git a/src/main/java/matcher/type/ClassFeatureExtractor.java b/src/main/java/matcher/type/ClassFeatureExtractor.java index 681acab2..dcafb6f7 100644 --- a/src/main/java/matcher/type/ClassFeatureExtractor.java +++ b/src/main/java/matcher/type/ClassFeatureExtractor.java @@ -241,7 +241,7 @@ private void processClassB(ClassInstance cls) { private void processMethodInsns(MethodInstance method) { if (!method.isReal()) { // artificial method to capture calls to types with incomplete/unknown hierarchy/super type method info - Matcher.LOGGER.debug("Skipping empty method "+method); + Matcher.LOGGER.debug("Skipping empty method {}", method); return; } @@ -304,7 +304,7 @@ private void processMethodInsns(MethodInstance method) { Util.isCallToInterface(impl), impl.getTag() == Opcodes.H_INVOKESTATIC); break; default: - Matcher.LOGGER.warn("Unexpected impl tag: "+impl.getTag()); + Matcher.LOGGER.warn("Unexpected impl tag: {}", impl.getTag()); } break; From 5fed4fcef06b3612672ad78191caff503a9f5ba2 Mon Sep 17 00:00:00 2001 From: NebelNidas Date: Thu, 12 Oct 2023 00:25:19 +0200 Subject: [PATCH 7/7] Don't use dedicated logging thread --- src/main/resources/tinylog-dev.properties | 2 -- src/main/resources/tinylog.properties | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/main/resources/tinylog-dev.properties b/src/main/resources/tinylog-dev.properties index 378ad419..5688dfda 100644 --- a/src/main/resources/tinylog-dev.properties +++ b/src/main/resources/tinylog-dev.properties @@ -1,5 +1,3 @@ -writingthread = true - writer = console writer.format = {date: HH:mm:ss.SSS} [{thread}/{level}]: {message} writer.level = debug diff --git a/src/main/resources/tinylog.properties b/src/main/resources/tinylog.properties index 1419eab1..d90124ce 100644 --- a/src/main/resources/tinylog.properties +++ b/src/main/resources/tinylog.properties @@ -1,5 +1,3 @@ -writingthread = true - writer = console writer.format = {date: HH:mm:ss} [{level}]: {message} writer.level = info