I remember searching for resources on JIT compilation, assemblage and execution, in general, and for Haskell and not finding a lot.
After tinkering around, I’ve made this minimal template, which I care to share here:
import Data.Word (Word32)
import Foreign.C.Types (CSize(..), CInt(..), CLong(..))
import Foreign.Marshal.Array (withArray)
import Foreign.Ptr (FunPtr, castPtrToFunPtr, Ptr, nullPtr, plusPtr)
import Foreign.Storable (poke, sizeOf)
type COff = CLong
instRet :: Word32
instRet = 0xd65f03c0
insts = [0x52800540, instRet]
foreign import ccall "dynamic"
mkFun :: FunPtr (IO Int) -> IO Int
foreign import ccall "sys/mman.h mmap"
mmap :: Ptr a -> CSize -> CInt -> CInt -> CInt -> COff -> IO (Ptr a)
foreign import ccall "sys/mman.h mprotect"
mprotect :: Ptr a -> CSize -> CInt -> IO Int
foreign import ccall "sys/mman.h munmap"
munmap :: Ptr a -> CSize -> IO Int
readWrite = CInt 3
readExec = CInt 5
anonPriv = CInt 0x22
pgSize = CSize 4096
writeArray [] ptr = pure ()
writeArray (x:xs) ptr = poke ptr x *> writeArray xs (ptr `plusPtr` sizeOf x)
instantReturn :: IO ()
instantReturn = do
page <- mmap nullPtr pgSize readWrite anonPriv (CInt 0) (CLong 0)
writeArray insts page
mprotect page pgSize readExec
result <- mkFun $ castPtrToFunPtr page
munmap page pgSize
print result
main = do
putStrLn "About to jump into custom instructions"
instantReturn
putStrLn "Done"
At first, I was trying to achieve the same in MicroHaskell, but the syscalls I need are not on the blessed ffi list. I think it also doesn’t support foreign import ccall "dynamic".
With that in mind: this is a non-portable GHC-aarch64 program.
Feel free to use this as a reference point for whenever you write your own machine code at runtime.
Outlined, what you need to do is
- acquire memory from the operating system (regular heap allocation will not do)
- write your instructions into the region
- change memory protection to read+execute (you can ofc keep write, but it’s more prone to vulnerabilities and most of the time, not needed)
- do the game of
castPtrToFunPtrandforeign import ccall "dynamic"
This is possible because the function signature of the JIT code is known in advance. Otherwise, you might need to use libffi or similar.
What does my program do? It writes 42 into the return value register and immediately returns.