Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Java bytecode injection?

Tags:

What exactly is Java bytecode injection and why would one use it?

like image 757
Marcus Leon Avatar asked Aug 12 '10 18:08

Marcus Leon


People also ask

What is Java bytecode?

Java bytecode is the resulting compiled object code of a Java program. This bytecode can be run in any platform which has a Java installation in it.

What is Java bytecode and how is it used?

Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is where JVM comes into play. It is a machine-level language code that runs on the JVM. It adds portability to Java which resonates with the saying, “write once, read anywhere”.

What is Java bytecode in simple words?

Bytecode is computer object code that an interpreter converts into binary machine code so it can be read by a computer's hardware processor. The interpreter is typically implemented as a virtual machine (VM) that translates the bytecode for the target platform.

Why do we need bytecode in Java?

The only essential requirement for running the bytecode is the installation of basic java in any platform. Advantages of bytecode: It helps in achieving the platform-independent goal with the help of bytecode. The set of instructions for JVM may differ from one system to another but all systems can run the bytecode.


1 Answers

Java code compiles into bytecode (Foo.java ->> Foo.class). Bytecode injection is modifying Foo.classat runtime to inject code into it right before its loaded and run.

Imagine a scenario where I want to find out how many times method

public void bar(); 

is invoked in Foo.class. I could write an agent using java.lang.instrument that intercepts Foo.class during class load, modifies it using ASM so that bar() calls com.amir.agent.incrementCount() on method entry.

Now I can run my program:

$java -javagent:MyAgent Foo  //assuming Foo has a main() defined 

and at runtime, Foo.class will not only do its normal work, it will also do work I defined in MyAgent each time bar() is invoked.

For a pointer on writing an agent from scratch, start here.

like image 127
Amir Afghani Avatar answered Oct 04 '22 15:10

Amir Afghani