Do your own static code analysis programmatically in Java | Similar to FindBugs using Apache BCEL

In this article we will understand another advanced variant of static code analysis which is byte code analysis. SpotBugs (Former FindBugs) does this kind of analysis using Apache commons-bcel library.

In earlier article we went through static code analysis using lexical analysis. Here is the link for the same to go through basics.

Do your own static code analysis programmatically in Java | Similar to checkstyle, PMD



What is Byte Code Analysis?

  • Java Byte Code
    • When Java source code is compiled, then source is converted into byte code which is nothing but set of certain instructions to JVM.
    • When JVM runs program, then it simply runs instructions from the byte code.
  • Op Code
    • A Java Virtual Machine “instructions” consists of an opcode specifying the operation to be performed.
    • Here is detailed documentations of op codes from Oracle – The Java Virtual Machine Instruction Set
  • Byte Code manipulation / analysis / engineering
    • Byte code manipulation is a process of accessing byte code of classes, analyzing it, modifying it etc.
    • There are libraries available like Apache commons-bcel, ASM which provides easy ways to go through class bytecode, methods, opcodes etc.
    • We can use such libraries, go through byte code & perform logic to find out possible issues or defects with the code & return them as result of static code analysis.



Example in this article

We will take example similar to what findbugs do in their code which might help relate to actual scenarios & to easily understand code of findbugs in case you wish to contribute.

  • In this article we will create a very simple static code analysis example using Apache commons-bcel library.
  • We will check if the java source code has an empty synchronized block.
  • If empty synchronized block is found, we will provide output with the line number & error message where empty synchronized block is found. Else will will output that class is all good.

Let start coding

For this code, we will need maven/gradle dependency which can be found here in maven repository.

Lets first create sample source code to analyze. We will create one bad class which will have empty synchronized block & another good class which has non-empty synchronized block as given below.




Now lets look at actual code to perform static code analysis. Code level comments are added to provide further understanding of code.




Here is the output of analysis. As you can see our program correctly identified class with empty synchronized block & provided line number & error message.




Complete source code can be found in GitHub repository here.

 

Leave a Reply

Your email address will not be published. Required fields are marked *