Accessing memory with Java

2019-04-29 04:48发布

问题:

I have a program loaded in the memory. Now I want to access the memory directly and change the OPCODE and DATA in the memory for that program. For this I need to write a Java program.

Can you please tell me if this is feasible? If yes, please let me know how to write such a program.

Thanks in advance!

回答1:

Java is not designed for this.
The main aim of Java is to let the JVM manage the memory for you. Thus, your programs are sandboxed.

However, there seems to be a backdoor in HotSpot JVM:

Java was initially designed as a safe, managed environment. Nevertheless, Java HotSpot VM contains a “backdoor” that provides a number of low-level operations to manipulate memory and threads directly. This backdoor – sun.misc.Unsafe – is widely used by JDK itself in the packages like java.nio or java.util.concurrent. It is hard to imagine a Java developer who uses this backdoor in any regular development because this API is extremely dangerous, non portable, and volatile. Nevertheless, Unsafe provides an easy way to look into HotSpot JVM internals and do some tricks. Sometimes it is simply funny, sometimes it can be used to study VM internals without C++ code debugging, sometimes it can be leveraged for profiling and development tools.

Source: http://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/

The Unsafe class is, however, undocumented. You may want to have a look at this SO answer for more details: https://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe

Unoffical Docs: http://mishadoff.github.io/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
Absolute Beginners' Guide http://java-performance.info/string-packing-converting-characters-to-bytes/
http://javapapers.com/core-java/address-of-a-java-object/

P.S. I am aware that I must post some of the content of the link here but since the articles are really very detailed, I have skipped that part



回答2:

You cannot directly reference memory in java, as their is no concept of pointers in java like c/c++

You must go through this referencing memory address

Hope it helps.