我知道可以通过在 jvm 中使用 Unsafe 类直接写入和读取内存。
除了这确实不安全并且不知何故适得其反之外,我想知道谁/什么负责检查允许的内存位置的边界。并且如果有一些机制可以保护已经分配的内存被覆盖。与这个最新问题相关,一个人通过覆盖他不应该做的事情会造成什么可能的损害?好吧,最好将其改写为:可以写入的内存是哪种类型,或者其中已经存储了哪种信息?
谢谢
我知道可以通过在 jvm 中使用 Unsafe 类直接写入和读取内存。
除了这确实不安全并且不知何故适得其反之外,我想知道谁/什么负责检查允许的内存位置的边界。并且如果有一些机制可以保护已经分配的内存被覆盖。与这个最新问题相关,一个人通过覆盖他不应该做的事情会造成什么可能的损害?好吧,最好将其改写为:可以写入的内存是哪种类型,或者其中已经存储了哪种信息?
谢谢
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.