diff --git a/README.md b/README.md index e3d9c8a..0dcac03 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/9A22t-SS) Разработать standalone приложение, которое имеет следующие возможности: Принимает на вход проект в виде .jar файла @@ -16,4 +17,13 @@ Гайд по использованию ASM: https://asm.ow2.io/asm4-guide.pdf -Дополнительное (необязательное задание): сделайте агента для сбора покрытия по строчкам \ No newline at end of file +Дополнительное (необязательное задание): сделайте агента для сбора покрытия по строчкам + +Чтобы получить агента для сбора покрытия по строчкам +``` +./gradlew shadowJar +``` +Запуск в режиме агента +``` +java -javaagent:build/libs/coverage-agent-1.0-all.jar -jar +``` \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 2b92afd..5c50553 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,9 +1,11 @@ plugins { id("java") + id("application") + id("com.github.johnrengelman.shadow") version "8.1.1" } group = "org.example" -version = "1.0-SNAPSHOT" +version = "1.0" repositories { mavenCentral() @@ -22,4 +24,50 @@ dependencies { tasks.test { useJUnitPlatform() +} + +application { + mainClass.set("org.example.coverage.agent.LineCoverageAgent") +} + +tasks.named("shadowJar") { + archiveBaseName.set("coverage-agent") + archiveClassifier.set("all") + + from(sourceSets.main.get().output) { + include("org/example/coverage/**") + } + + // Включаем все зависимости ASM + configurations = listOf(project.configurations.runtimeClasspath.get()) + + manifest { + attributes( + "Premain-Class" to "org.example.coverage.LineCoverageAgent", + "Agent-Class" to "org.example.coverage.LineCoverageAgent", + "Can-Redefine-Classes" to "true", + "Can-Retransform-Classes" to "true" + ) + } + + // Исключаем файлы, которые могут конфликтовать + exclude("META-INF/*.SF") + exclude("META-INF/*.DSA") + exclude("META-INF/*.RSA") + exclude("META-INF/*.txt") +} + +tasks.register("demoJar") { + archiveBaseName.set("demo-app") + archiveClassifier.set("") + + from(sourceSets.main.get().output) { + include("org/example/demo/**") + } + + manifest { + attributes("Main-Class" to "org.example.demo.Main") + } + + dependsOn("classes") } \ No newline at end of file diff --git a/src/main/java/org/example/Example.java b/src/main/java/org/example/Example.java deleted file mode 100644 index 52d0abe..0000000 --- a/src/main/java/org/example/Example.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.example; - -import org.example.visitor.ClassPrinter; -import org.objectweb.asm.ClassReader; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -public class Example { - - public static void main(String[] args) throws IOException { -// var printer = new ByteCodePrinter(); -// printer.printBubbleSortBytecode(); - try (JarFile sampleJar = new JarFile("src/main/resources/sample.jar")) { - Enumeration enumeration = sampleJar.entries(); - - while (enumeration.hasMoreElements()) { - JarEntry entry = enumeration.nextElement(); - if (entry.getName().endsWith(".class")) { - ClassPrinter cp = new ClassPrinter(); - ClassReader cr = new ClassReader(sampleJar.getInputStream(entry)); - cr.accept(cp, 0); - } - } - } - } -} diff --git a/src/main/java/org/example/Main.java b/src/main/java/org/example/Main.java new file mode 100644 index 0000000..240e455 --- /dev/null +++ b/src/main/java/org/example/Main.java @@ -0,0 +1,90 @@ +package org.example; + +import org.example.coverage.CoverageCollector; +import org.example.coverage.CoverageReport; +import org.example.coverage.CoverageTransformer; +import org.example.metrics.Metrics; +import org.example.visitor.ClassAnalyzer; +import org.objectweb.asm.ClassReader; + +import java.io.FileWriter; +import java.io.IOException; +import java.lang.instrument.Instrumentation; +import java.util.Enumeration; +import java.util.Locale; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +public class Main { + private static final CoverageCollector collector = CoverageCollector.getInstance(); + + public static void premain(String agentArgs, Instrumentation inst) { + inst.addTransformer(new CoverageTransformer(), true); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + System.out.println("[LineCoverageAgent] Saving coverage report..."); + CoverageReport report = collector.generateReport(); + try { + report.saveToFile("coverage-report.json"); + } catch (IOException e) { + throw new RuntimeException(e); + } + report.printSummary(); + })); + } + + public static void main(String[] args) throws IOException { + String inputJar = "src/main/resources/fescar.zip"; + String outputFile = "src/main/resources/output.json"; + + Metrics metrics = new Metrics(); + + try (JarFile inputJarFile = new JarFile(inputJar)) { + Enumeration enumeration = inputJarFile.entries(); + + while (enumeration.hasMoreElements()) { + JarEntry entry = enumeration.nextElement(); + if (entry.getName().endsWith(".class")) { + ClassReader reader = new ClassReader(inputJarFile.getInputStream(entry)); + ClassAnalyzer analyzer = new ClassAnalyzer(metrics); + reader.accept(analyzer, 0); + } + } + } + metrics.calculateClassesDepth(); + printMetricsToConsole(metrics); + saveMetricsToJson(metrics, outputFile); + } + + private static void printMetricsToConsole(Metrics metrics) { + System.out.println("Max Depth: " + metrics.getMaxDepth()); + System.out.println("Average Depth: " + metrics.getAverageDepth()); + System.out.println("Average ABC: " + metrics.getAverageAbc()); + System.out.println("Average Overridden Methods: " + metrics.getAverageFieldsCount()); + System.out.println("Average Fields Count: " + metrics.getAverageOverriddenMethods()); + + } + + private static void saveMetricsToJson(Metrics metrics, String outputFile) { + String json = String.format(Locale.US, + "{\n" + + " \"maxDepth\": %d,\n" + + " \"averageDepth\": %f,\n" + + " \"averageAbc\": %f,\n" + + " \"averageOverriddenMethods\": %f,\n" + + " \"averageFieldsCount\": %f\n" + + "}", + metrics.getMaxDepth(), + metrics.getAverageDepth(), + metrics.getAverageAbc(), + metrics.getAverageOverriddenMethods(), + metrics.getAverageFieldsCount() + ); + + try (FileWriter writer = new FileWriter(outputFile)) { + writer.write(json); + System.out.println("Metrics saved to file: " + outputFile); + } catch (IOException e) { + System.err.println("Error write file: " + e.getMessage()); + } + } +} diff --git a/src/main/java/org/example/coverage/CoverageClassVisitor.java b/src/main/java/org/example/coverage/CoverageClassVisitor.java new file mode 100644 index 0000000..635999d --- /dev/null +++ b/src/main/java/org/example/coverage/CoverageClassVisitor.java @@ -0,0 +1,47 @@ +package org.example.coverage; + +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.HashMap; +import java.util.Map; + +class CoverageClassVisitor extends ClassVisitor { + + private final String className; + private final Map lineMapping = new HashMap<>(); + + public CoverageClassVisitor(ClassVisitor cv, String className) { + super(Opcodes.ASM9, cv); + this.className = className; + } + + @Override + public void visitSource(String source, String debug) { + super.visitSource(source, debug); + } + + @Override + public MethodVisitor visitMethod(int access, String name, + String descriptor, + String signature, String[] exceptions) { + + MethodVisitor mv = super.visitMethod(access, name, descriptor, + signature, exceptions); + + // Пропускаем конструкторы и статические блоки инициализации + if (name.equals("") || name.equals("")) { + return mv; + } + + return new CoverageMethodVisitor(mv, className, name, descriptor, lineMapping); + } + + @Override + public void visitEnd() { + // Сохраняем маппинг строк для этого класса + CoverageCollector.getInstance().registerLineMapping(className, lineMapping); + super.visitEnd(); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/coverage/CoverageCollector.java b/src/main/java/org/example/coverage/CoverageCollector.java new file mode 100644 index 0000000..9e2fd66 --- /dev/null +++ b/src/main/java/org/example/coverage/CoverageCollector.java @@ -0,0 +1,90 @@ +package org.example.coverage; + +import java.util.*; + +public class CoverageCollector { + + private static CoverageCollector instance; + + private final Map> lineCoverage = new HashMap<>(); + private final Set executedMethods = new HashSet<>(); + private final Map> lineToMethodMapping = new HashMap<>(); + private final Map>> methodLines = new HashMap<>(); + + private CoverageCollector() {} + + public static CoverageCollector getInstance() { + if (instance == null) { + instance = new CoverageCollector(); + } + return instance; + } + + public static void methodEntered(String className, String methodName, String methodDesc) { + getInstance().recordMethodExecution(className, methodName, methodDesc); + } + + public static void lineExecuted(String className, String methodName, + String methodDesc, int lineNumber) { + getInstance().recordLineExecution(className, methodName, methodDesc, lineNumber); + } + + private void recordMethodExecution(String className, String methodName, String methodDesc) { + String methodKey = createMethodKey(className, methodName, methodDesc); + executedMethods.add(methodKey); + } + + private void recordLineExecution(String className, String methodName, + String methodDesc, int lineNumber) { + Map classLines = lineCoverage.computeIfAbsent( + className, k -> new HashMap<>()); + + int currentCount = classLines.getOrDefault(lineNumber, 0); + classLines.put(lineNumber, currentCount + 1); + + // Записываем, какой метод выполнил эту строку + Map mapping = lineToMethodMapping.computeIfAbsent( + className, k -> new HashMap<>()); + mapping.put(lineNumber, methodName); + } + + public void registerLineMapping(String className, Map mapping) { + lineToMethodMapping.put(className, new HashMap<>(mapping)); + } + + public void registerMethodLines(String className, String methodName, + String methodDesc, Set lines) { + Map> classMethods = methodLines.computeIfAbsent( + className, k -> new HashMap<>()); + + String methodKey = methodName + methodDesc; + classMethods.put(methodKey, new HashSet<>(lines)); + } + + public CoverageReport generateReport() { + CoverageReport report = new CoverageReport(); + + report.setTotalClasses(lineCoverage.size()); + report.setTotalMethods(executedMethods.size()); + report.setTotalCoveredLines(calculateTotalCoveredLines()); + report.setTotalExecutableLines(calculateTotalExecutableLines()); + + return report; + } + + private int calculateTotalCoveredLines() { + return lineCoverage.values().stream() + .mapToInt(Map::size) + .sum(); + } + + private int calculateTotalExecutableLines() { + return lineToMethodMapping.values().stream() + .mapToInt(Map::size) + .sum(); + } + + private String createMethodKey(String className, String methodName, String methodDesc) { + return className + "#" + methodName + methodDesc; + } +} \ No newline at end of file diff --git a/src/main/java/org/example/coverage/CoverageMethodVisitor.java b/src/main/java/org/example/coverage/CoverageMethodVisitor.java new file mode 100644 index 0000000..0cc02eb --- /dev/null +++ b/src/main/java/org/example/coverage/CoverageMethodVisitor.java @@ -0,0 +1,166 @@ +package org.example.coverage; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +class CoverageMethodVisitor extends MethodVisitor { + private final String className; + private final String methodName; + private final String methodDesc; + private final Map lineMapping; + private int currentLine = -1; + private final Set coveredLines = new HashSet<>(); + + private final Map lineLabels = new HashMap<>(); + + public CoverageMethodVisitor(MethodVisitor mv, String className, + String methodName, String methodDesc, + Map lineMapping) { + super(Opcodes.ASM9, mv); + this.className = className; + this.methodName = methodName; + this.methodDesc = methodDesc; + this.lineMapping = lineMapping; + } + + @Override + public void visitLineNumber(int line, Label start) { + currentLine = line; + lineLabels.put(line, start); + lineMapping.put(line, methodName); + + super.visitLineNumber(line, start); + } + + @Override + public void visitCode() { + super.visitCode(); + insertMethodEntryCall(); + } + + @Override + public void visitInsn(int opcode) { + insertLineCoverageIfNeeded(); + super.visitInsn(opcode); + } + + @Override + public void visitIntInsn(int opcode, int operand) { + insertLineCoverageIfNeeded(); + super.visitIntInsn(opcode, operand); + } + + @Override + public void visitVarInsn(int opcode, int var) { + insertLineCoverageIfNeeded(); + super.visitVarInsn(opcode, var); + } + + @Override + public void visitTypeInsn(int opcode, String type) { + insertLineCoverageIfNeeded(); + super.visitTypeInsn(opcode, type); + } + + @Override + public void visitFieldInsn(int opcode, String owner, + String name, String descriptor) { + insertLineCoverageIfNeeded(); + super.visitFieldInsn(opcode, owner, name, descriptor); + } + + @Override + public void visitMethodInsn(int opcode, String owner, + String name, String descriptor, + boolean isInterface) { + insertLineCoverageIfNeeded(); + super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); + } + + @Override + public void visitJumpInsn(int opcode, Label label) { + insertLineCoverageIfNeeded(); + super.visitJumpInsn(opcode, label); + } + + @Override + public void visitLabel(Label label) { + super.visitLabel(label); + } + + @Override + public void visitLdcInsn(Object value) { + insertLineCoverageIfNeeded(); + super.visitLdcInsn(value); + } + + @Override + public void visitIincInsn(int var, int increment) { + insertLineCoverageIfNeeded(); + super.visitIincInsn(var, increment); + } + + @Override + public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { + insertLineCoverageIfNeeded(); + super.visitTableSwitchInsn(min, max, dflt, labels); + } + + @Override + public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { + insertLineCoverageIfNeeded(); + super.visitLookupSwitchInsn(dflt, keys, labels); + } + + @Override + public void visitMultiANewArrayInsn(String descriptor, int numDimensions) { + insertLineCoverageIfNeeded(); + super.visitMultiANewArrayInsn(descriptor, numDimensions); + } + + @Override + public void visitEnd() { + CoverageCollector.getInstance().registerMethodLines( + className, methodName, methodDesc, coveredLines); + super.visitEnd(); + } + + private void insertLineCoverageIfNeeded() { + if (currentLine > 0 && !coveredLines.contains(currentLine)) { + // Вставляем вызов для отслеживания строки + insertLineCoverageCall(currentLine); + coveredLines.add(currentLine); + } + } + + private void insertMethodEntryCall() { + // Вставляем вызов в начале метода + super.visitLdcInsn(className); + super.visitLdcInsn(methodName); + super.visitLdcInsn(methodDesc); + super.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/example/coverage/CoverageCollector", + "methodEntered", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", + false); + } + + private void insertLineCoverageCall(int lineNumber) { + // Вставляем вызов для регистрации покрытия строки + super.visitLdcInsn(className); + super.visitLdcInsn(methodName); + super.visitLdcInsn(methodDesc); + super.visitLdcInsn(lineNumber); + super.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/example/coverage/CoverageCollector", + "lineExecuted", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V", + false); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/coverage/CoverageReport.java b/src/main/java/org/example/coverage/CoverageReport.java new file mode 100644 index 0000000..9b5ca2d --- /dev/null +++ b/src/main/java/org/example/coverage/CoverageReport.java @@ -0,0 +1,57 @@ +package org.example.coverage; + +import java.io.*; + +public class CoverageReport { + + private int totalClasses = 0; + private int totalMethods = 0; + private int totalCoveredLines = 0; + private int totalExecutableLines = 0; + + public void setTotalClasses(int totalClasses) { this.totalClasses = totalClasses; } + public void setTotalMethods(int totalMethods) { this.totalMethods = totalMethods; } + public void setTotalCoveredLines(int lines) { this.totalCoveredLines = lines; } + public void setTotalExecutableLines(int lines) { this.totalExecutableLines = lines; } + + public void saveToFile(String filename) throws IOException { + File file = new File(filename); + try (PrintWriter out = new PrintWriter(new FileWriter(file))) { + out.println(toJSON()); + } + } + + public void printSummary() { + System.out.println("\n" + "=".repeat(60)); + System.out.println("COVERAGE REPORT SUMMARY"); + System.out.println("=".repeat(60)); + + double overallCoverage = totalExecutableLines > 0 ? + (double) totalCoveredLines / totalExecutableLines * 100 : 0.0; + + System.out.printf("Total Classes: %d\n", totalClasses); + System.out.printf("Total Methods: %d\n", totalMethods); + System.out.printf("Executable Lines: %d\n", totalExecutableLines); + System.out.printf("Covered Lines: %d\n", totalCoveredLines); + System.out.printf("Overall Coverage: %.2f%%\n", overallCoverage); + } + + private String toJSON() { + StringBuilder json = new StringBuilder(); + json.append("{\n"); + json.append(" \"summary\": {\n"); + json.append(" \"totalClasses\": ").append(totalClasses).append(",\n"); + json.append(" \"totalMethods\": ").append(totalMethods).append(",\n"); + json.append(" \"totalExecutableLines\": ").append(totalExecutableLines).append(",\n"); + json.append(" \"totalCoveredLines\": ").append(totalCoveredLines).append(",\n"); + json.append(" \"overallCoverage\": ").append(calculateOverallCoverage()).append("\n"); + json.append(" }\n"); + json.append("}"); + return json.toString(); + } + + private double calculateOverallCoverage() { + return totalExecutableLines > 0 ? + (double) totalCoveredLines / totalExecutableLines * 100 : 0.0; + } +} \ No newline at end of file diff --git a/src/main/java/org/example/coverage/CoverageTransformer.java b/src/main/java/org/example/coverage/CoverageTransformer.java new file mode 100644 index 0000000..f640bf8 --- /dev/null +++ b/src/main/java/org/example/coverage/CoverageTransformer.java @@ -0,0 +1,41 @@ +package org.example.coverage; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; + +import java.lang.instrument.ClassFileTransformer; +import java.security.ProtectionDomain; + +public class CoverageTransformer implements ClassFileTransformer { + + @Override + public byte[] transform(ClassLoader loader, String className, + Class classBeingRedefined, + ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + // Пропускаем системные классы + if (isSystemClass(className)) { + return classfileBuffer; + } + + try { + ClassReader cr = new ClassReader(classfileBuffer); + ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + ClassVisitor cv = new CoverageClassVisitor(cw, className); + cr.accept(cv, ClassReader.EXPAND_FRAMES); + return cw.toByteArray(); + } catch (Exception e) { + System.err.println("[CoverageTransformer] Error instrumenting " + className + ": " + e.getMessage()); + return classfileBuffer; + } + } + + private boolean isSystemClass(String className) { + return className.startsWith("java/") || + className.startsWith("sun/") || + className.startsWith("jdk/") || + className.startsWith("com/sun/") || + className.startsWith("org/example/coverage/"); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/coverage/LineCoverageAgent.java b/src/main/java/org/example/coverage/LineCoverageAgent.java new file mode 100644 index 0000000..d1a31a6 --- /dev/null +++ b/src/main/java/org/example/coverage/LineCoverageAgent.java @@ -0,0 +1,25 @@ +package org.example.coverage; + +import java.io.IOException; +import java.lang.instrument.*; + +public class LineCoverageAgent { + private static final CoverageCollector collector = CoverageCollector.getInstance(); + + public static void premain(String agentArgs, Instrumentation inst) { + System.out.println("[LineCoverageAgent] Starting..."); + + inst.addTransformer(new CoverageTransformer(), true); + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + System.out.println("[LineCoverageAgent] Saving coverage report..."); + CoverageReport report = collector.generateReport(); + try { + report.saveToFile("coverage-report.json"); + } catch (IOException e) { + throw new RuntimeException(e); + } + report.printSummary(); + })); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/example/BubbleSort.java b/src/main/java/org/example/example/BubbleSort.java deleted file mode 100644 index 8a21c95..0000000 --- a/src/main/java/org/example/example/BubbleSort.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.example.example; - -public class BubbleSort { - - static void bubbleSort(int[] arr, int n) - { - int i, j, temp; - boolean swapped; - for (i = 0; i < n - 1; i++) { - swapped = false; - for (j = 0; j < n - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - - // Swap arr[j] and arr[j+1] - temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; - swapped = true; - } - } - - // If no two elements were - // swapped by inner loop, then break - if (!swapped) - break; - } - } - -} diff --git a/src/main/java/org/example/metrics/ABCMetrics.java b/src/main/java/org/example/metrics/ABCMetrics.java new file mode 100644 index 0000000..fbf1660 --- /dev/null +++ b/src/main/java/org/example/metrics/ABCMetrics.java @@ -0,0 +1,36 @@ +package org.example.metrics; + + +public class ABCMetrics { + private int assignments = 0; + private int branches = 0; + private int conditions = 0; + + public int getAssignments() { + return assignments; + } + + public void setAssignments(int assignments) { + this.assignments = assignments; + } + + public int getBranches() { + return branches; + } + + public void setBranches(int branches) { + this.branches = branches; + } + + public int getConditions() { + return conditions; + } + + public void setConditions(int conditions) { + this.conditions = conditions; + } + + public double getAbc() { + return Math.sqrt(assignments*assignments + branches*branches + conditions*conditions); + } +} diff --git a/src/main/java/org/example/metrics/ClassMetrics.java b/src/main/java/org/example/metrics/ClassMetrics.java new file mode 100644 index 0000000..2e0c172 --- /dev/null +++ b/src/main/java/org/example/metrics/ClassMetrics.java @@ -0,0 +1,34 @@ +package org.example.metrics; + +import java.util.ArrayList; +import java.util.List; + +public class ClassMetrics { + private String className; + private int fields = 0; + private final List methods = new ArrayList<>(); + + public List getMethods() { + return methods; + } + + public void addMethodMetrics(String methodMetrics) { + methods.add(methodMetrics); + } + + public void setClassName(String className) { + this.className = className; + } + + public String getClassName() { + return className; + } + + public int getFields() { + return fields; + } + + public void incrementFields() { + fields++; + } +} diff --git a/src/main/java/org/example/metrics/Metrics.java b/src/main/java/org/example/metrics/Metrics.java new file mode 100644 index 0000000..7da9c59 --- /dev/null +++ b/src/main/java/org/example/metrics/Metrics.java @@ -0,0 +1,117 @@ +package org.example.metrics; + +import java.util.*; + +public class Metrics { + private final Map overriddenMethodsCounter = new HashMap<>(); + private final Map> classMethods = new HashMap<>(); + private final Map classFields = new HashMap<>(); + private final Map classToSuperClass = new HashMap<>(); + private final Map extendsDepths = new HashMap<>(); + private final List abcMetricsList = new ArrayList<>(); + + public void putClassToSuperClass(String className, String superClassName) { + classToSuperClass.put(className, superClassName); + } + + public void addABCMetrics(ABCMetrics abcMetrics) { + abcMetricsList.add(abcMetrics); + } + + public void putClassFields(String className, int fields) { + this.classFields.put(className, fields); + } + + public void putClassMethods(String className, List methodSignatures) { + this.classMethods.put(className, methodSignatures); + } + + public void calculateClassesDepth() { + for (String className : classToSuperClass.keySet()) { + calculateDepth(className); + countOverriddenMethods(className); + } + } + + private int calculateDepth(String className) { + if (extendsDepths.containsKey(className)) { + return extendsDepths.get(className); + } + + String superClassName = classToSuperClass.get(className); + + int depth; + if (superClassName == null) { + depth = 1; + } else { + int superDepth = calculateDepth(superClassName); + depth = superDepth + 1; + } + + extendsDepths.put(className, depth); + return depth; + } + + private void countOverriddenMethods(String className) { + List methods = classMethods.get(className); + if (!classToSuperClass.containsKey(className)) { + overriddenMethodsCounter.put(className, 0); + return; + } + + String parentClassName = classToSuperClass.get(className); + Set allParentMethods = new HashSet<>(); + + while (parentClassName != null && classToSuperClass.containsKey(parentClassName)) { + if (classMethods.containsKey(parentClassName)) { + allParentMethods.addAll(classMethods.get(parentClassName)); + } + + parentClassName = classToSuperClass.get(parentClassName); + } + + int counter = 0; + + for (String method : methods) { + if (allParentMethods.contains(method)) { + counter++; + } + } + + overriddenMethodsCounter.put(className, counter); + } + + public int getMaxDepth() { + return extendsDepths.values().stream().max(Integer::compareTo).orElse(0); + } + + public double getAverageDepth() { + return extendsDepths.values().stream() + .mapToInt(Integer::intValue) + .average() + .orElse(0.0); + } + + public double getAverageAbc() { + return abcMetricsList.stream() + .map((ABCMetrics::getAbc)) + .mapToDouble(Double::intValue) + .average() + .orElse(0.0); + + } + + public double getAverageFieldsCount() { + return classFields.values().stream() + .mapToInt(Integer::intValue) + .average() + .orElse(0.0); + } + + public double getAverageOverriddenMethods() { + return overriddenMethodsCounter.values().stream() + .mapToInt(Integer::intValue) + .average() + .orElse(0.0); + } +} diff --git a/src/main/java/org/example/util/ByteCodePrinter.java b/src/main/java/org/example/util/ByteCodePrinter.java deleted file mode 100644 index 3d1ca38..0000000 --- a/src/main/java/org/example/util/ByteCodePrinter.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.example.util; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TryCatchBlockNode; -import org.objectweb.asm.tree.analysis.*; -import org.objectweb.asm.util.Textifier; -import org.objectweb.asm.util.TraceMethodVisitor; - -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Path; - -public class ByteCodePrinter { - - private static String getUnqualifiedName(final String name) { - var lastSlashIndex = name.lastIndexOf('/'); - if (lastSlashIndex == -1) { - return name; - } else { - int endIndex = name.length(); - if (name.charAt(endIndex - 1) == ';') { - endIndex--; - } - int lastBracketIndex = name.lastIndexOf('['); - if (lastBracketIndex == -1) { - return name.substring(lastSlashIndex + 1, endIndex); - } - return name.substring(0, lastBracketIndex + 1) + name.substring(lastSlashIndex + 1, endIndex); - } - } - private static void analyzeMethod( - final MethodNode method, final Analyzer analyzer, final PrintWriter printWriter) { - var textifier = new Textifier(); - var traceMethodVisitor = new TraceMethodVisitor(textifier); - - printWriter.println(method.name + method.desc); - for (int i = 0; i < method.instructions.size(); ++i) { - method.instructions.get(i).accept(traceMethodVisitor); - - var stringBuilder = new StringBuilder(); - var frame = analyzer.getFrames()[i]; - if (frame == null) { - stringBuilder.append('?'); - } else { - for (int j = 0; j < frame.getLocals(); ++j) { - stringBuilder.append(getUnqualifiedName(frame.getLocal(j).toString())).append(' '); - } - stringBuilder.append(" : "); - for (int j = 0; j < frame.getStackSize(); ++j) { - stringBuilder.append(getUnqualifiedName(frame.getStack(j).toString())).append(' '); - } - } - while (stringBuilder.length() < method.maxStack + method.maxLocals + 1) { - stringBuilder.append(' '); - } - printWriter.print(Integer.toString(i + 100000).substring(1)); - printWriter.print( - " " + stringBuilder + " : " + textifier.text.get(textifier.text.size() - 1)); - } - for (TryCatchBlockNode tryCatchBlock : method.tryCatchBlocks) { - tryCatchBlock.accept(traceMethodVisitor); - printWriter.print(" " + textifier.text.get(textifier.text.size() - 1)); - } - printWriter.println(); - } - - public void printBytecode(ClassNode cn) { - var sortMethod = cn.methods.get(1); - var analyzer = new CheckFrameAnalyzer<>(new BasicVerifier()); - try { - analyzer.analyze("dummy", sortMethod); - } catch (AnalyzerException e) { - throw new RuntimeException(e); - } - var pw = new PrintWriter(System.out); - analyzeMethod(sortMethod, analyzer, pw); - pw.flush(); - } - - public void printBubbleSortBytecode() throws IOException { - var cn = new ClassNode(); - var classFileBytes = Files.readAllBytes(Path.of("build/classes/java/main/org/itmo/lab1/example/BubbleSort.class")); - var classReader = new ClassReader(classFileBytes); - classReader.accept(cn, ClassReader.EXPAND_FRAMES); - printBytecode(cn); - } -} diff --git a/src/main/java/org/example/util/CheckFrameAnalyzer.java b/src/main/java/org/example/util/CheckFrameAnalyzer.java deleted file mode 100644 index 5231ca7..0000000 --- a/src/main/java/org/example/util/CheckFrameAnalyzer.java +++ /dev/null @@ -1,475 +0,0 @@ -package org.example.util; - -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -import java.util.Collections; -import java.util.List; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.LookupSwitchInsnNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TableSwitchInsnNode; -import org.objectweb.asm.tree.TryCatchBlockNode; -import org.objectweb.asm.tree.TypeInsnNode; -import org.objectweb.asm.tree.analysis.Analyzer; -import org.objectweb.asm.tree.analysis.AnalyzerException; -import org.objectweb.asm.tree.analysis.Frame; -import org.objectweb.asm.tree.analysis.Interpreter; -import org.objectweb.asm.tree.analysis.Value; - -/** - * An {@link Analyzer} subclass which checks that methods provide stack map frames where expected - * (i.e. at jump target and after instructions without immediate successor), and that these stack - * map frames are valid (for the provided interpreter; they may still be invalid for the JVM, if the - * {@link Interpreter} uses a simplified type system compared to the JVM verifier). This is done in - * two steps: - * - *
    - *
  • First, the stack map frames in {@link FrameNode}s are expanded, and stored at their - * respective instruction offsets. The expansion process uncompresses the APPEND, CHOP and - * SAME frames to FULL frames. It also converts the stack map frame verification types to - * {@link Value}s, via the provided {@link Interpreter}. The expansion is done in {@link - * #expandFrames}, by looking at each {@link FrameNode} in sequence (compressed frames are - * defined relatively to the previous {@link FrameNode}, or the implicit first frame). The - * actual decompression is done in {@link #expandFrame}, and the type conversion in {@link - * #newFrameValue}. - *
  • Next, the method instructions are checked in sequence. Starting from the implicit initial - * frame, the execution of each instruction i is simulated on the current stack map - * frame, with the {@link Frame#execute} method. This gives a new stack map frame f, - * representing the stack map frame state after the execution of i. Then: - *
      - *
    • If there is a next instruction and if the control flow cannot continue to it (e.g. if - * i is a RETURN or an ATHROW, for instance): an existing stack map frame - * f0 (coming from the first step) is expected after i. - *
    • If there is a next instruction and if the control flow can continue to it (e.g. if - * i is a ALOAD, for instance): either there an existing stack map frame - * f0 (coming from the first step) after i, or there is none. In the - * first case f and f0 must be compatible: the types in - * f must be sub types of the corresponding types in the existing frame - * f0 (otherwise an exception is thrown). In the second case, f0 is - * simply set to the value of f. - *
    • If the control flow can continue to some instruction j (e.g. if i - * is an IF_EQ, for instance): an existing stack map frame f0 (coming from the - * first step) is expected at j, which must be compatible with f (as - * defined previously). - *
    - * The sequential loop over the instructions is done in {@link #init}, which is called from - * the {@link Analyzer#analyze} method. Cases where the control flow cannot continue to the - * next instruction are handled in {@link #endControlFlow}. Cases where the control flow can - * continue to the next instruction, or jump to another instruction, are handled in {@link - * #checkFrame}. This method checks that an existing stack map frame is present when required, - * and checks the stack map frames compatibility with {@link #checkMerge}. - *
- * - * @author Eric Bruneton - * @param type of the {@link Value} used for the analysis. - */ -class CheckFrameAnalyzer extends Analyzer { - - /** The interpreter to use to symbolically interpret the bytecode instructions. */ - private final Interpreter interpreter; - - /** The instructions of the currently analyzed method. */ - private InsnList insnList; - - /** - * double values are represented with two elements. - */ - private int currentLocals; - - CheckFrameAnalyzer(final Interpreter interpreter) { - super(interpreter); - this.interpreter = interpreter; - } - - @Override - protected void init(final String owner, final MethodNode method) throws AnalyzerException { - insnList = method.instructions; - currentLocals = Type.getArgumentsAndReturnSizes(method.desc) >> 2; - - Frame[] frames = getFrames(); - Frame currentFrame = frames[0]; - expandFrames(owner, method, currentFrame); - for (int insnIndex = 0; insnIndex < insnList.size(); ++insnIndex) { - Frame oldFrame = frames[insnIndex]; - - // Simulate the execution of this instruction. - AbstractInsnNode insnNode = null; - try { - insnNode = method.instructions.get(insnIndex); - int insnOpcode = insnNode.getOpcode(); - int insnType = insnNode.getType(); - - if (insnType == AbstractInsnNode.LABEL - || insnType == AbstractInsnNode.LINE - || insnType == AbstractInsnNode.FRAME) { - checkFrame(insnIndex + 1, oldFrame, /* requireFrame = */ false); - } else { - currentFrame.init(oldFrame).execute(insnNode, interpreter); - - if (insnNode instanceof JumpInsnNode) { - if (insnOpcode == JSR) { - throw new AnalyzerException(insnNode, "JSR instructions are unsupported"); - } - JumpInsnNode jumpInsn = (JumpInsnNode) insnNode; - int targetInsnIndex = insnList.indexOf(jumpInsn.label); - checkFrame(targetInsnIndex, currentFrame, /* requireFrame = */ true); - if (insnOpcode == GOTO) { - endControlFlow(insnIndex); - } else { - checkFrame(insnIndex + 1, currentFrame, /* requireFrame = */ false); - } - } else if (insnNode instanceof LookupSwitchInsnNode) { - LookupSwitchInsnNode lookupSwitchInsn = (LookupSwitchInsnNode) insnNode; - int targetInsnIndex = insnList.indexOf(lookupSwitchInsn.dflt); - checkFrame(targetInsnIndex, currentFrame, /* requireFrame = */ true); - for (int i = 0; i < lookupSwitchInsn.labels.size(); ++i) { - LabelNode label = lookupSwitchInsn.labels.get(i); - targetInsnIndex = insnList.indexOf(label); - currentFrame.initJumpTarget(insnOpcode, label); - checkFrame(targetInsnIndex, currentFrame, /* requireFrame = */ true); - } - endControlFlow(insnIndex); - } else if (insnNode instanceof TableSwitchInsnNode) { - TableSwitchInsnNode tableSwitchInsn = (TableSwitchInsnNode) insnNode; - int targetInsnIndex = insnList.indexOf(tableSwitchInsn.dflt); - currentFrame.initJumpTarget(insnOpcode, tableSwitchInsn.dflt); - checkFrame(targetInsnIndex, currentFrame, /* requireFrame = */ true); - newControlFlowEdge(insnIndex, targetInsnIndex); - for (int i = 0; i < tableSwitchInsn.labels.size(); ++i) { - LabelNode label = tableSwitchInsn.labels.get(i); - currentFrame.initJumpTarget(insnOpcode, label); - targetInsnIndex = insnList.indexOf(label); - checkFrame(targetInsnIndex, currentFrame, /* requireFrame = */ true); - } - endControlFlow(insnIndex); - } else if (insnOpcode == RET) { - throw new AnalyzerException(insnNode, "RET instructions are unsupported"); - } else if (insnOpcode != ATHROW && (insnOpcode < IRETURN || insnOpcode > RETURN)) { - checkFrame(insnIndex + 1, currentFrame, /* requireFrame = */ false); - } else { - endControlFlow(insnIndex); - } - } - - List insnHandlers = getHandlers(insnIndex); - if (insnHandlers != null) { - for (TryCatchBlockNode tryCatchBlock : insnHandlers) { - Type catchType; - if (tryCatchBlock.type == null) { - catchType = Type.getObjectType("java/lang/Throwable"); - } else { - catchType = Type.getObjectType(tryCatchBlock.type); - } - Frame handler = newFrame(oldFrame); - handler.clearStack(); - handler.push(interpreter.newExceptionValue(tryCatchBlock, handler, catchType)); - checkFrame(insnList.indexOf(tryCatchBlock.handler), handler, /* requireFrame = */ true); - } - } - - if (!hasNextJvmInsnOrFrame(insnIndex)) { - break; - } - } catch (AnalyzerException e) { - throw new AnalyzerException( - e.node, "Error at instruction " + insnIndex + ": " + e.getMessage(), e); - } catch (RuntimeException e) { - // DontCheck(IllegalCatch): can't be fixed, for backward compatibility. - throw new AnalyzerException( - insnNode, "Error at instruction " + insnIndex + ": " + e.getMessage(), e); - } - } - } - - /** - * Expands the {@link FrameNode} "instructions" of the given method into {@link Frame} objects and - * also associated with the label and line number nodes immediately preceding each frame node. - * - * @param owner the internal name of the class to which 'method' belongs. - * @param method the method whose frames must be expanded. - * @param initialFrame the implicit initial frame of 'method'. - * @throws AnalyzerException if the stack map frames of 'method', i.e. its FrameNode - * "instructions", are invalid. - */ - private void expandFrames( - final String owner, final MethodNode method, final Frame initialFrame) - throws AnalyzerException { - int lastJvmOrFrameInsnIndex = -1; - Frame currentFrame = initialFrame; - int currentInsnIndex = 0; - for (AbstractInsnNode insnNode : method.instructions) { - if (insnNode instanceof FrameNode) { - try { - currentFrame = expandFrame(owner, currentFrame, (FrameNode) insnNode); - } catch (AnalyzerException e) { - throw new AnalyzerException( - e.node, "Error at instruction " + currentInsnIndex + ": " + e.getMessage(), e); - } - for (int index = lastJvmOrFrameInsnIndex + 1; index <= currentInsnIndex; ++index) { - getFrames()[index] = currentFrame; - } - } - if (isJvmInsnNode(insnNode) || insnNode instanceof FrameNode) { - lastJvmOrFrameInsnIndex = currentInsnIndex; - } - currentInsnIndex += 1; - } - } - - /** - * Returns the expanded representation of the given {@link FrameNode}. - * - * @param owner the internal name of the class to which 'frameNode' belongs. - * @param previousFrame the frame before 'frameNode', in expanded form. - * @param frameNode a possibly compressed stack map frame. - * @return the expanded version of 'frameNode'. - * @throws AnalyzerException if 'frameNode' is invalid. - */ - private Frame expandFrame( - final String owner, final Frame previousFrame, final FrameNode frameNode) - throws AnalyzerException { - Frame frame = newFrame(previousFrame); - List locals = frameNode.local == null ? Collections.emptyList() : frameNode.local; - int currentLocal = currentLocals; - switch (frameNode.type) { - case Opcodes.F_NEW: - case Opcodes.F_FULL: - currentLocal = 0; - // fall through - case Opcodes.F_APPEND: - for (Object type : locals) { - V value = newFrameValue(owner, frameNode, type); - if (currentLocal + value.getSize() > frame.getLocals()) { - throw new AnalyzerException(frameNode, "Cannot append more locals than maxLocals"); - } - frame.setLocal(currentLocal++, value); - if (value.getSize() == 2) { - frame.setLocal(currentLocal++, interpreter.newValue(null)); - } - } - break; - case Opcodes.F_CHOP: - for (Object unusedType : locals) { - if (currentLocal <= 0) { - throw new AnalyzerException(frameNode, "Cannot chop more locals than defined"); - } - if (currentLocal > 1 && frame.getLocal(currentLocal - 2).getSize() == 2) { - currentLocal -= 2; - } else { - currentLocal -= 1; - } - } - break; - case Opcodes.F_SAME: - case Opcodes.F_SAME1: - break; - default: - throw new AnalyzerException(frameNode, "Illegal frame type " + frameNode.type); - } - currentLocals = currentLocal; - while (currentLocal < frame.getLocals()) { - frame.setLocal(currentLocal++, interpreter.newValue(null)); - } - - List stack = frameNode.stack == null ? Collections.emptyList() : frameNode.stack; - frame.clearStack(); - for (Object type : stack) { - frame.push(newFrameValue(owner, frameNode, type)); - } - return frame; - } - - /** - * Creates a new {@link Value} that represents the given stack map frame type. - * - * @param owner the internal name of the class to which 'frameNode' belongs. - * @param frameNode the stack map frame to which 'type' belongs. - * @param type an Integer, String or LabelNode object representing a primitive, reference or - * uninitialized a stack map frame type, respectively. See {@link FrameNode}. - * @return a value that represents the given type. - * @throws AnalyzerException if 'type' is an invalid stack map frame type. - */ - private V newFrameValue(final String owner, final FrameNode frameNode, final Object type) - throws AnalyzerException { - if (type == Opcodes.TOP) { - return interpreter.newValue(null); - } else if (type == Opcodes.INTEGER) { - return interpreter.newValue(Type.INT_TYPE); - } else if (type == Opcodes.FLOAT) { - return interpreter.newValue(Type.FLOAT_TYPE); - } else if (type == Opcodes.LONG) { - return interpreter.newValue(Type.LONG_TYPE); - } else if (type == Opcodes.DOUBLE) { - return interpreter.newValue(Type.DOUBLE_TYPE); - } else if (type == Opcodes.NULL) { - return interpreter.newOperation(new InsnNode(Opcodes.ACONST_NULL)); - } else if (type == Opcodes.UNINITIALIZED_THIS) { - return interpreter.newValue(Type.getObjectType(owner)); - } else if (type instanceof String) { - return interpreter.newValue(Type.getObjectType((String) type)); - } else if (type instanceof LabelNode) { - AbstractInsnNode referencedNode = (LabelNode) type; - while (referencedNode != null && !isJvmInsnNode(referencedNode)) { - referencedNode = referencedNode.getNext(); - } - if (referencedNode == null || referencedNode.getOpcode() != Opcodes.NEW) { - throw new AnalyzerException(frameNode, "LabelNode does not designate a NEW instruction"); - } - return interpreter.newValue(Type.getObjectType(((TypeInsnNode) referencedNode).desc)); - } - throw new AnalyzerException(frameNode, "Illegal stack map frame value " + type); - } - - /** - * Checks that the given frame is compatible with the frame at the given instruction index, if - * any. If there is no frame at this instruction index and none is required, the frame at - * 'insnIndex' is set to the given frame. Otherwise, if the merge of the two frames is not equal - * to the current frame at 'insnIndex', an exception is thrown. - * - * @param insnIndex an instruction index. - * @param frame a frame. This frame is left unchanged by this method. - * 'insnIndex'. - * @throws AnalyzerException if the frames have incompatible sizes or if the frame at 'insnIndex' - * is missing (if required) or not compatible with 'frame'. - */ - private void checkFrame(final int insnIndex, final Frame frame, final boolean requireFrame) - throws AnalyzerException { - Frame oldFrame = getFrames()[insnIndex]; - if (oldFrame == null) { - if (requireFrame) { - throw new AnalyzerException(null, "Expected stack map frame at instruction " + insnIndex); - } - getFrames()[insnIndex] = newFrame(frame); - } else { - String error = checkMerge(frame, oldFrame); - if (error != null) { - throw new AnalyzerException( - null, - "Stack map frame incompatible with frame at instruction " - + insnIndex - + " (" - + error - + ")"); - } - } - } - - /** - * Checks that merging the two given frames would not produce any change, i.e. that the types in - * the source frame are sub types of the corresponding types in the destination frame. - * - * @param srcFrame a source frame. This frame is left unchanged by this method. - * @param dstFrame a destination frame. This frame is left unchanged by this method. - * @return an error message if the frames have incompatible sizes, or if a type in the source - * frame is not a sub type of the corresponding type in the destination frame. Returns - * {@literal null} otherwise. - */ - private String checkMerge(final Frame srcFrame, final Frame dstFrame) { - int numLocals = srcFrame.getLocals(); - if (numLocals != dstFrame.getLocals()) { - throw new AssertionError(); - } - for (int i = 0; i < numLocals; ++i) { - V v = interpreter.merge(srcFrame.getLocal(i), dstFrame.getLocal(i)); - if (!v.equals(dstFrame.getLocal(i))) { - return "incompatible types at local " - + i - + ": " - + srcFrame.getLocal(i) - + " and " - + dstFrame.getLocal(i); - } - } - int numStack = srcFrame.getStackSize(); - if (numStack != dstFrame.getStackSize()) { - return "incompatible stack heights"; - } - for (int i = 0; i < numStack; ++i) { - V v = interpreter.merge(srcFrame.getStack(i), dstFrame.getStack(i)); - if (!v.equals(dstFrame.getStack(i))) { - return "incompatible types at stack item " - + i - + ": " - + srcFrame.getStack(i) - + " and " - + dstFrame.getStack(i); - } - } - return null; - } - - /** - * Ends the control flow graph at the given instruction. This method checks that there is an - * existing frame for the next instruction, if any. - * - * @param insnIndex an instruction index. - * @throws AnalyzerException if 'insnIndex' is not the last instruction and there is no frame at - * 'insnIndex' + 1 in {@link #getFrames}. - */ - private void endControlFlow(final int insnIndex) throws AnalyzerException { - if (hasNextJvmInsnOrFrame(insnIndex) && getFrames()[insnIndex + 1] == null) { - throw new AnalyzerException( - null, "Expected stack map frame at instruction " + (insnIndex + 1)); - } - } - - /** - * Returns true if the given instruction is followed by a JVM instruction or a by stack map frame. - * - * @param insnIndex an instruction index. - * @return true if 'insnIndex' is followed by a JVM instruction or a by stack map frame. - */ - private boolean hasNextJvmInsnOrFrame(final int insnIndex) { - AbstractInsnNode insn = insnList.get(insnIndex).getNext(); - while (insn != null) { - if (isJvmInsnNode(insn) || insn instanceof FrameNode) { - return true; - } - insn = insn.getNext(); - } - return false; - } - - /** - * Returns true if the given instruction node corresponds to a real JVM instruction. - * - * @param insnNode an instruction node. - * @return true except for label, line number and stack map frame nodes. - */ - private static boolean isJvmInsnNode(final AbstractInsnNode insnNode) { - return insnNode.getOpcode() >= 0; - } -} diff --git a/src/main/java/org/example/visitor/ABCAnalyzer.java b/src/main/java/org/example/visitor/ABCAnalyzer.java new file mode 100644 index 0000000..a3a2177 --- /dev/null +++ b/src/main/java/org/example/visitor/ABCAnalyzer.java @@ -0,0 +1,56 @@ +package org.example.visitor; + +import org.example.metrics.ABCMetrics; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.util.Set; + +public class ABCAnalyzer extends MethodVisitor { + private static final Set CONDITIONAL_JUMPS = Set.of( + Opcodes.IFEQ, Opcodes.IFNE, Opcodes.IFLT, Opcodes.IFGE, Opcodes.IFGT, Opcodes.IFLE, + Opcodes.IF_ICMPEQ, Opcodes.IF_ICMPNE, Opcodes.IF_ICMPGE, Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE, + Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE, Opcodes.IFNULL, Opcodes.IFNONNULL + ); + ABCMetrics abcMetrics; + + public ABCAnalyzer(ABCMetrics abcMetrics) { + super(Opcodes.ASM9); + this.abcMetrics = abcMetrics; + } + + @Override + public void visitVarInsn(int opcode, int var) { + if ( + opcode == Opcodes.ISTORE || + opcode == Opcodes.LSTORE || + opcode == Opcodes.FSTORE || + opcode == Opcodes.DSTORE || + opcode == Opcodes.ASTORE + ) { + abcMetrics.setAssignments(abcMetrics.getAssignments() + 1); + } + } + + @Override + public void visitJumpInsn(int opcode, Label label) { + abcMetrics.setBranches(abcMetrics.getBranches() + 1); + if (CONDITIONAL_JUMPS.contains(opcode)) { + abcMetrics.setConditions(abcMetrics.getConditions() + 1); + } + } + + @Override + public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { + abcMetrics.setBranches(abcMetrics.getBranches() + 1); + abcMetrics.setConditions(abcMetrics.getConditions() + labels.length + 1); + } + + + @Override + public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { + abcMetrics.setBranches(abcMetrics.getBranches() + 1); + abcMetrics.setConditions(abcMetrics.getConditions() + labels.length + 1); + } +} diff --git a/src/main/java/org/example/visitor/ClassAnalyzer.java b/src/main/java/org/example/visitor/ClassAnalyzer.java new file mode 100644 index 0000000..1c33ca7 --- /dev/null +++ b/src/main/java/org/example/visitor/ClassAnalyzer.java @@ -0,0 +1,66 @@ +package org.example.visitor; + +import org.example.metrics.ABCMetrics; +import org.example.metrics.ClassMetrics; +import org.example.metrics.Metrics; +import org.objectweb.asm.*; + +public class ClassAnalyzer extends ClassVisitor { + private final Metrics metrics; + ClassMetrics classMetrics = new ClassMetrics(); + + public ClassAnalyzer(Metrics metrics) { + super(Opcodes.ASM9); + this.metrics = metrics; + } + + @Override + public void visit(int version, int access, String name, + String signature, String superName, String[] interfaces) { + + String className = name.replace('/', '.'); + String superClassName = null; + + if (superName != null && !superName.equals("java/lang/Object")) { + superClassName = superName.replace('/', '.'); + } + classMetrics.setClassName(className); + metrics.putClassToSuperClass(className, superClassName); + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, + String descriptor, + String signature, String[] exceptions) { + // Не обрабатываем конструкторы и статические поля + if (!name.equals("") && !name.equals("")) { + ABCMetrics abcMetrics = new ABCMetrics(); + metrics.addABCMetrics(abcMetrics); + classMetrics.addMethodMetrics(signature); + return new ABCAnalyzer(abcMetrics); + } + + return super.visitMethod(access, name, descriptor, signature, exceptions); + } + + @Override + public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { + classMetrics.incrementFields(); + return super.visitField(access, name, descriptor, signature, value); + } + + + @Override + public void visitEnd() { + metrics.putClassMethods( + classMetrics.getClassName(), + classMetrics.getMethods() + ); + metrics.putClassFields( + classMetrics.getClassName(), + classMetrics.getFields() + ); + super.visitEnd(); + } +} diff --git a/src/main/java/org/example/visitor/ClassPrinter.java b/src/main/java/org/example/visitor/ClassPrinter.java deleted file mode 100644 index ba1ab9f..0000000 --- a/src/main/java/org/example/visitor/ClassPrinter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.example.visitor; - -import org.objectweb.asm.*; - -import static org.objectweb.asm.Opcodes.ASM8; - -public class ClassPrinter extends ClassVisitor { - public ClassPrinter() { - super(ASM8); - } - - public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { - System.out.println("\n" + name + " extends " + superName + " {"); - } - - public void visitSource(String source, String debug) { - } - - public void visitOuterClass(String owner, String name, String desc) { - } - - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - return null; - } - - public void visitAttribute(Attribute attr) { - } - - public void visitInnerClass(String name, String outerName, String innerName, int access) { - } - - public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { - System.out.println(" " + desc + " " + name); - return null; - } - - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - System.out.println(" " + name + desc); - return null; - } - - public void visitEnd() { - System.out.println("}"); - } -} - diff --git a/src/main/resources/output.json b/src/main/resources/output.json new file mode 100644 index 0000000..9a4e9b2 --- /dev/null +++ b/src/main/resources/output.json @@ -0,0 +1,7 @@ +{ + "maxDepth": 5, + "averageDepth": 1.576812, + "averageAbc": 1.447946, + "averageOverriddenMethods": 1.527273, + "averageFieldsCount": 2.609091 +} \ No newline at end of file