sophiajt / jntrnr.github.io

6 stars 4 forks source link

Incorrect information in building a jit #1

Closed ehiggs closed 7 years ago

ehiggs commented 7 years ago

Now we're ready. We have something we can write into and then jump into. Since running JIT code is basically "no man's land" without any safeguards, it's easy to get yourself in trouble. One step that I add is to also fill the memory block with the RET instruction, which will let us return from our function even if we happen to accidentally run other memory in the block.

This won't work if a function pushes some registers to the stack; they need to be popped. So wouldn't it be better to segfault on a bad instruction (e.g. maybe jump -1(%rip)) or fill the buffer with nops?

alnsn commented 7 years ago

Jump is two bytes instruction, it won't work as a filler. I'd go with byte 0xff. Even though some instructions (jump above is one example) start with this byte, 0xff alone doesn't produce a valid instruction even if repeated 2-15 times. Instruction on Intel can't be longer than 15 bytes. IF you you're close to a page boundary, there is chance that bytes will form a valid instruction but it's quite unlikely.

alnsn commented 7 years ago

Another related issue is when you align code and don't fill gap bytes with nops, bad instructions may have a negative impact on execution pipeline.

sophiajt commented 7 years ago

@ehiggs - this is more of an introduction rather than an exhaustive post, though if someone does write a more exhaustive one I'd be happy to add a link to it.