创建一门新的编程语言-Flex&Bison-(4)-什么是jit

来源:互联网 发布:esp8266mod数据手册 编辑:程序博客网 时间:2024/05/17 14:20

jit这个概念我想大家在网上并不少见,特别是在看java,c#等资料的时候,jit这个词都被用烂了。

那什么是jit?这个地方反而在网上的资料中说的很含糊。“静态编译的程序在执行前全部被翻译为机器码,而直译执行的则是一句一句边运行边翻译。”,这是在wiki上唯一useful但又不useful的句子。

但有一篇博文写的很好,解释了jit的工作原理:http://eli.thegreenplace.net/2013/11/05/how-to-jit-an-introduction/

里面写了这么一段代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/mman.h>// Allocates RWX memory of given size and returns a pointer to it. On failure,// prints out the error and returns NULL.void* alloc_executable_memory(size_t size) {  void* ptr = mmap(0, size,                   PROT_READ | PROT_WRITE | PROT_EXEC,                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);  if (ptr == (void*)-1) {    perror("mmap");    return NULL;  }  return ptr;}void emit_code_into_memory(unsigned char* m) {  unsigned char code[] = {    0x48, 0x89, 0xf8,                   // mov %rdi, %rax    0x48, 0x83, 0xc0, 0x04,             // add $4, %rax    0xc3                                // ret  };  memcpy(m, code, sizeof(code));}const size_t SIZE = 1024;typedef long (*JittedFunc)(long);// Allocates RWX memory directly.void run_from_rwx() {  void* m = alloc_executable_memory(SIZE);  emit_code_into_memory(m);  JittedFunc func = m;  int result = func(2);  printf("result = %d\n", result);}

这段代码jit了一个简单的函数:

long add4(long num) {  return num + 4;}
可以看到,jit的工作原理就是把高级语言解释成汇编,再把汇编对应成机器码(bytes),且放入一个heap上的内存段里。

执行这段代码也很简单,只要建立一个相应的函数指针,并且把其指向我们机器码数据的开头便可。你是不是又对函数指针更理解了?:)


(4)-什么是jit 结束

0 0