是否是翻译成elf格式,然后执行?调用系统API执行?
为什么要翻译成elf呢?给你一个我写的例子吧
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <sys/mman.h>
#include <stdint.h>
typedef struct test_s {
uint32_t a;
uint32_t b;
uint32_t c;
struct test_s *bp;
}test_t;
#define AREG0 "ebp"
#define AREG1 "ebx"
#define AREG2 "esi"
#define AREG3 "edi"
register test_t *st asm("ebp");
register uint32_t T0 asm("ebx");
register uint32_t T1 asm("esi");
register uint32_t T2 asm("edi");
#define wmb() __asm__ __volatile__ ("": : :"memory")
#define OP_BEGIN(f) __asm__ __volatile__ ("jmp
."f"_teawater_op_end
""."f"_teawater_op_begin:
")
#define OP_END(f) __asm__ __volatile__ ("."f"_teawater_op_end:
""movl
$."f"_teawater_op_begin,%0
""movl $."f"_teawater_op_end,%1
":"=g"(begin),
"=g"(end));
#define CBIT_SHIFT 29
#define CBIT ((unsigned)1L << CBIT_SHIFT)
test_t tmp;
void (*gen_func)(void);
volatile uint32_t pfun;
uint32_t
ldr(test_t * state,uint32_t addr)
{
printf("ldr addr:%d
",addr);
return(2315);
}
void
str(test_t * state,uint32_t addr,uint32_t data)
{
printf("str addr:%d data:%d
",addr,data);
}
int
main(int argc,char *argv[],char *envp[])
{
unsigned int begin=0,end=0;
OP_BEGIN("main");
T0 = 5873;
//T2 = ldr(st, T0);
__asm__ __volatile__ ("subl $0x8, %esp");
__asm__ __volatile__ ("push %"AREG1);
__asm__ __volatile__ ("push %"AREG0);
pfun = (uint32_t)ldr;
__asm__ __volatile__ ("call *pfun");
__asm__ __volatile__ ("addl $0x10, %esp");
__asm__ __volatile__ ("movl %eax, %"AREG3);
T1 = 6578;
//str(st, T1, T2)
__asm__ __volatile__ ("subl $0x4, %esp");
__asm__ __volatile__ ("push %"AREG3);
__asm__ __volatile__ ("push %"AREG2);
__asm__ __volatile__ ("push %"AREG0);
pfun = (uint32_t)str;
__asm__ __volatile__ ("call *pfun");
__asm__ __volatile__ ("addl $0x10, %esp");
__asm__ __volatile__ ("ret");
OP_END("main");
gen_func=mmap( NULL,1024,PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANONYMOUS,0,0);
if(gen_func== MAP_FAILED) {
perror("mmap");
return(-1);
}
memcpy(gen_func,(void *)begin,end-begin);
tmp.a=123;
tmp.bp=st;
st=&tmp;
gen_func();
st=tmp.bp;
munmap(gen_func,1024);
return(0);
}
OP_BEGIN("main");和OP_END("main");之间的部分就假定是你翻译以后的本地代码
gen_func();是对其的执行过程
不过提一下这只是我自己对动态翻译的想法 思想来自qemu
你提到的java虚拟机的具体实现形式我没有仔细了解过