Saturday, March 12, 2016

Using Gradle to disassembles classes into bytecode format in a java project

apply plugin: 'java'import groovy.io.FileType

repositories {
    mavenCentral()
}



dependencies {
    testCompile 'junit:junit:4.12'    testCompile 'org.mockito:mockito-core:1.10.8'
}



task generateBytecode {
    dependsOn compileJava    doLast {
        readClassFiles()
    }
}


private void readClassFiles() {
    def list = []
    File srcDir = sourceSets.main.output.classesDir

    if (srcDir != null) {
        // iterate through all files in the build/classes directory        srcDir.eachFileRecurse(FileType.FILES) { file ->
            boolean b = checkIfIsClassFile(file)
            if (b) {
                // add the file to the list if it is an class file                list << file
            }
        }

        println 'starts generating bytecode files ... '        list.each {
            generateByteCodeFiles(it)
        }
    }
}

private boolean checkIfIsClassFile(File file) {
    String regex = ".*\\.class"    String filename = file.getName()
    boolean b = filename.matches(regex);
    b
}

def generateByteCodeFiles(File file) {

    //execute command and get the command line output as a String    def stdout = new ByteArrayOutputStream()
    exec {
        // javap -v -p -s -sysinfo -constants Subclass\$InnerClass.class        commandLine "javap", "-private", "-v", "-s", file;
        standardOutput = stdout
    }
    String resultString = stdout.toString();
    createFile(resultString, file);
}


def createFile(String result, File classFile) {
    String fname = classFile.name;

    // remove file name extension    int pos = fname.lastIndexOf(".");
    if (pos > 0) {
        fname = fname.substring(0, pos);
    }

    // create txt files to save the result    fname = fname + ".txt"    File textFile = new File(project.getBuildDir().toString() + "/bytecode/" + fname);
    textFile.getParentFile().mkdirs();
    textFile.createNewFile();
    println textFile

    // write the output String into the file    FileWriter fileWriter = new FileWriter(textFile);
    fileWriter.write(result);
    fileWriter.flush();
    fileWriter.close();

}

1 comment:

  1. The file formatting looks broken (eg missing carriage returns).

    ReplyDelete