문제

I know it is possible to write and read directly to memory by using Unsafe class within the jvm.

Apart from this being really unsafe and somehow counterproductive, I was instead wondering who/what is taking charge of checking the boundaries of the allowed memory location. And also if there's some mechanism that safeguard the already allocated memory to be overwritten. Related to this latest question, what possible damage can one does by overwriting what he shouldn't ? Well, this could be best reformed as: what type of memory is the one that can be written, or what kind of information are already stored in there ?

Thanks

도움이 되었습니까?

해결책

The underlying operating system will ensure that you do not write outside of the memory allocated to your application (which it can do easily, due to Virtual Memory). If you do, you will get a segmentation fault or similar error In addition to that, the JVM might do its own bound checking. You'll definitely not be allowed to write in any sensible (i.e. other applications) memory, and I doubt the JVM will allow you to overwrite internal structures, but I might be wrong there. So to summarize the answer to your question: The possible damage to overwriting where you shouldn't is in the best case your application malfunctioning and in the worst case the JVM crashing.

In regards to safeguards, not using Unsafe would be a pretty good one... Other than that, you can of course write your own memory allocator inside the memory allocated by Unsafe and flag some areas so your application code does not write into areas it shouldn't.

So the answer to your last question would be that if the JVM allows you to access memory outside of the allocated unsafe regions, then the information and type of memory you can access is any of your objects as well as any internal JVM structure. Obviously changing those would wreak havoc, so it's likely that attempting to do so would result in a crash.

다른 팁

By using the Unsafe class, you are taking charge of checking the boundaries of the allowed memory locations.

You shouldn't assume that there'll be some mechanism that will prevent you from corrupting parts of your process's memory that you're not supposed to touch.

The comment that accompanies Unsafe.getUnsafe() is pretty clear:

[the Unsafe instance] can be used to read and write data at arbitrary memory addresses.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top