Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking an existing method in Java

Tags:

java

hook

I want to hook the method System.out.print in Java and have the ability to read/change the variables used in the method before the part of the method is called that actually adds the string to whatever the output stream is.

In C++ I would just detour the function, or set an int3 instruction so I could access the registers but in java I have no idea how to accomplish something similar.

like image 527
Nowayz Avatar asked May 03 '11 00:05

Nowayz


3 Answers

You can reassign System.out (and System.err) to another object which does what you want to do with it. Said object usually gets the old System.out value so that output can be made in the end.

This is usually done in main() and influences the whole JVM.

We use this to have automatic wrapping at 130 columns in a very peculiar setting where longer lines are truncated.

like image 115
Thorbjørn Ravn Andersen Avatar answered Nov 08 '22 07:11

Thorbjørn Ravn Andersen


You can rewrite the byte code of the methods, and in the process capture/change the local variables. It is not trivial. See some notes here.

Maybe what you really want is a java debugger? You can connect a debugger to a remote process, add a breakpoint, and capture/change the local variables pretty easily using eclipse.

What is the real problem you are trying to solve?

like image 23
sbridges Avatar answered Nov 08 '22 05:11

sbridges


Have a look at this link.

He sneakily defines a static anonymous class so that System.out points to something different, and therefore print and println will route through that object.

like image 3
Mike Avatar answered Nov 08 '22 06:11

Mike