简体   繁体   中英

How is it possible for JVM to run generated machine code from a Java application via JIT?

How is it possible that JVM compiles bytecode into native code dynamically and then executes it? I can imagine that it is possible to write data values into memory but if I remember correctly, a program can't write to the memory that contains instructions (otherwise viruses could use this feature and proliferate quickly).

Very few architectures implement the level of memory protection (only the OS has write access to memory areas containing code) you're talking about, the ones where Java uses a JIT definitely don't.

And viruses do use this feature and even more to proliferate quickly. But when you think about it, there's nothing inherently dangerous in a process modifying its own code. It isn't any more dangerous than being able to write to a file and then load a library.

Normally, you can't write to the section of memory that contains code directly, but there are ways to override that. For JITs, often what is done is to have some read-write data space on the heap and then use an operation such as mprotect to make it executable.

OSes do provide facilities to allocate "executable" memory. The JVM needs to allocate the target memory in a different way than standard malloc() when generating JITed code.

For example, on Windows, use VirtualAlloc with PAGE_EXECUTE . Similar functions exist in Linux, AIX, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM