assembly - How can I dynamically create and execute machine code at runtime? -


the closest i've gotten assembly building own java class library loads class files , allows create , decompile classes.

while endeavoring project, wondered how jvm generated native machine code @ runtime during jit optimizations.

my question, then, how 1 dynamically create machine code , execute @ runtime assembly?

your question changed substantially (in july 2017). initial variant referred ex (execute) instruction of ibm mainframes.

how 1 dynamically create machine code , execute @ runtime?

in practice, use jit compilation library, , there many of them. or use dynamic loader. @ lowest level, write byte sequences representing valid machine code -a sequence of many machine instructions- in memory segment (of virtual address space) has made executable (read nx bit), , of code jump indirectly address or more call indirectly it, call thru function pointer. jvm implementations use jit compilation techniques. operating systems provide system calls memory segment (e.g. mmap(2) on linux) , make executable (e.g. mprotect(2))

if use jit compilation library asmjit or libjit or libgccjit or llvm or many others, first construct in memory representation (similar abstract syntax tree) of code generated, ask jit library emit machine code it. write own jit compilation code, lot of work (you need understand details of instruction set, e.g. x86 pcs). btw, generating fast-running machine code difficult, because need optimize compilers (and care details instruction scheduling, register allocation, etc... see this), , why using existing jit compilation library (like libgccjit or llvm) preferable (a contrario, simpler jit libraries asmjit or libjit or gnu lightning don't optimize , generate poor machine code).

if use dynamic loader (e.g. dlopen(3) on posix) use external compiler produce shared library (that plugin) , ask dynamic linker load in process (and handle appropriate relocations) , name (using dlsym(3)) function addresses it.

some language implementations (notably sbcl common lisp) able emit on fly machine code @ every repl interaction. in essence runtime embark full compiler (containing jit compilation part).

a trick use on linux emit c (or c++) code @ runtime in temporary file (that compiling domain specific language c or c++), fork compilation of plugin, , dynamically load it. current (laptops, desktops, servers) computers fast enough stay compatible interactive loop.

read eval (in particular famous sicp book), metaprogramming, multistage programming, self-modifying code, continuations, compilers (the dragon book), scott's programming language pragmatics, , j.pitrat's blog.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -