SlideShare una empresa de Scribd logo
1 de 62
Descargar para leer sin conexión
Interpreter, Compiler, JIT
from scratch
Jim Huang <jserv.tw@gmail.com>
● Brainf*ck: Turing complete programming language
● Interpreter
● Compiler
● JIT Compiler
Agenda
Brainf*ck
Brainf*ck Machine
● Assume we have unlimited length of buffer
Address 0 1 2 3 4 …
Value 0 0 0 0 0 …
Source: http://jonfwilkins.blogspot.tw/2011/06/happy-99th-birthday-alan-turing.html
Brainf*ck instructions
Increment the byte value at the data pointer.
Decrement the data pointer to point to the previous cell.
Increment the data pointer to point to the next cell.
Decrement the byte value at the data pointer.
Output the byte value at the data pointer.
Input one byte and store its value at the data pointer.
If the byte value at the data pointer is zero, jump to the
instruction following the matching ] bracket. Otherwise,
continue execution.
Unconditionally jump back to the matching [ bracket.
Turing Complete
● Brianfuck has 6 opcode + Input/Output commands
● gray area for I/O (implementation dependent)
– EOF
– tape length
– cell type
– newlines
● That is enough to program!
● Extension: self-modifying Brainfuck
https://soulsphere.org/hacks/smbf/
Brainf*ck
Address 0 1 2 3 4 …
Value 0 0 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 1 0 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 1 0 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 1 1 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 1 1 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 0 1 0 0 0 …
+ > + < -
Brainf*ck
Address 0 1 2 3 4 …
Value 64 0 0 0 0 …
. [ > , ]
Input Output
'A' 'B' '0'
Brainf*ck
Address 0 1 2 3 4 …
Value 64 0 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 0 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 0 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 0 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 66 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 66 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 66 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 66 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck
Address 0 1 2 3 4 …
Value 64 65 66 0 0 …
. [ > , ]
'A' 'B' '0' '@'
Input Output
Brainf*ck Interpreter
Initialization
● A Brainfuck program operates on a 30,000 element byte
array initialized to all zeros. It starts off with an instruction
pointer, that initially points to the first element in the data
array or “tape.”
// Initialize the tape with 30,000 zeroes.
uint8_t tape [30000] = { 0 };
// Set the pointer to the left most cell of the tape.
uint8_t* ptr = tape;
Data Pointer
● Operators, > and < increment and decrement the data
pointer.
case '>': ++ptr; break;
case '<': --ptr; break;
● One thing that could be bad is that because the interpreter is
written in C and we’re representing the tape as an array but
we’re not validating our inputs, there’s potential for stack
buffer overrun since we’re not performing bounds checks.
Again, punting and assuming well formed input to keep the
code and the point more precise.
Cells pointed to Data Pointer
● + and – operators are used for incrementing and
decrementing the cell pointed to by the data pointer by
one.
case '+': ++(*ptr); break;
case '-': --(*ptr); break;
Input and Output
● The operators . and , provide Brainfuck’s only means of
input or output, by writing the value pointed to by the
instruction pointer to stdout as an ASCII value, or reading
one byte from stdin as an ASCII value and writing it to the
cell pointed to by the instruction pointer.
case '.': putchar(*ptr); break;
case ',': *ptr = getchar(); break;
Loop
●
Looping constructs, [ and ].
– [: if the byte at the data pointer is zero, then instead of
moving the instruction pointer forward to the next
command, jump it forward to the command after the
matching ] command
– ]: if the byte at the data pointer is nonzero, then
instead of moving the instruction pointer forward to the
next command, jump it back to the command after the
matching [ command.
Loop
case '[':
if (!(*ptr)) {
int loop = 1;
while (loop > 0) {
uint8_t current_char =
input[++i];
if (current_char == ']') {
--loop;
} else if (current_char == '[') {
++loop;
}
}
}
break;
case ']':
if (*ptr) {
int loop = 1;
while (loop > 0) {
uint8_t current_char =
input[--i];
if (current_char == '[') {
--loop;
} else if (current_char == ']') {
++loop;
}
}
}
break;
Verify the simple interpreter
● Fetch and build
$ git clone https://github.com/embedded2015/jit-construct.git
$ cd jit-construct
$ make
$ ./interpreter progs/hello.bf
Hello World!
● Check interpreter.c which reads a byte and immediately performs
an action based on the operator.
● Benchmark on GNU/Linux for x86_64
$ time ./interpreter progs/mandelbrot.b
real 2m1.297s
user 2m1.368s
sys 0m0.004s
Brainf*ck Compiler
[x86_64/x64 backend]
Generate machine code
● How about if we want to compile the Brainfuck source
code to native machine code?
– Instruction Set Architecture (ISA)
– Application Binary Interface (ABI)
● Iterate over every character in the source file again,
switching on the recognized operator.
– print assembly instructions to stdout.
– Doing so requires running the compiler on an input file,
redirecting stdout to a file, then running the system
assembler and linker on that file.
Prologue for compiled x86_64
const char *const prologue =
".textn"
".globl _mainn"
"main:n"
" pushq %rbpn"
" movq %rsp, %rbpn"
" pushq %r12n" // store callee saved register
" subq $30008, %rspn" // allocate 30,008 B on stack, and realign
" leaq (%rsp), %rdin" // address of beginning of tape
" movl $0, %esin" // fill with 0's
" movq $30000, %rdxn" // length 30,000 B
" call memsetn" // memset
" movq %rsp, %r12";
Epilogue for compiled x86_64
const char *const epilogue =
" addq $30008, %rspn" // clean up tape from stack.
" popq %r12n" // restore callee saved register
" popq %rbpn"
" retn";
● During the linking phase, we ensure linking in libc so we can call
memset. What we do is backing up callee saved registers we’ll
be using, stack allocating the tape, realigning the stack, copying
the address of the only item on the stack into a register for our
first argument, setting the second argument to the constant 0,
the third arg to 30000, then calling memset.
● Finally, we use the callee saved register %r12 as our instruction
pointer, which is the address into a value on the stack.
Alignment
● We can expect the call to memset to result in a segfault if
simply subtract just 30000B, and not realign for the 2 registers
(64 b each, 8 B each) we pushed on the stack.
● The first pushed register aligns the stack on a 16 B boundary,
the second misaligns it; that’s why we allocate an additional 8
B on the stack.
Reference:
System V Application Binary Interface
AMD64 Architecture Processor Supplement
Draft Version 0.99.6
Data Pointers are straightforward
● Moving the instruction pointer (>, <) and modifying the
pointed to value (+, -)
case '>':
puts(" inc %r12");
break;
case '<':
puts(" dec %r12");
break;
case '+':
puts(" incb (%r12)");
break;
case '-':
puts(" decb (%r12)");
break;
Output
● Have to copy the pointed to byte into the register for the
first argument to putchar.
● We explicitly zero out the register before calling putchar,
since it takes an int (32 b), but we’re only copying a char (8
b) (C’s type promotion rules).
– x86-64 has an instruction that does both, movzXX, Where the first X is the
source size (b, w) and the second is the destination size (w, l, q).
– movzbl moves a byte (8 b) into a double word (32 b). %rdi and %edi are the
same register, but %rdi is the full 64 b register, while %edi is the lowest (or
least significant) 32 b.
case '.':
puts(" movzbl (%r12), %edi");
puts(" call putchar");
break;
Input
● Easily call getchar, move the resulting lowest byte into
the cell pointed to by the instruction pointer.
– %al is the lowest 8 b of the 64 b %rax register
case ',':
puts(" call getchar");
puts(" movb %al, (%r12)");
break;
Loop constructs [
● Have to match up jumps to matching labels
– labels must be unique.
● Instead, whenever we encounter an opening brace, push a
monotonically increasing number that represents the numbers of
opening brackets we’ve seen so far onto a stack like data structure.
– compare and jump to what will be the label that should be produced by the matching
close label.
– insert our starting label, and finally increment the number of brackets seen.
case '[':
stack_push(&stack, num_brackets);
puts (" cmpb $0, (%r12)");
printf(" je bracket_%d_endn", num_brackets);
printf("bracket_%d_start:n", num_brackets++);
break;
Loop constructs ]
● pop the number of brackets seen (or rather, number of pending open
brackets which we have yet to see a matching close bracket) off of the
stack, do our comparison, jump to the matching start label, and finally
place our end label.
case ']':
stack_pop(&stack, &matching_bracket);
puts(" cmpb $0, (%r12)");
printf(" jne bracket_%d_startn", matching_bracket);
printf("bracket_%d_end:n", matching_bracket);
break;
Code generation of Nested Loop
[ [ ] ]
cmpb $0, (%r12)
je bracket_0_end
bracket_0_start:
cmpb $0, (%r12)
je bracket_1_end
bracket_1_start:
cmpb $0, (%r12)
jne bracket_1_start
bracket_1_end:
cmpb $0, (%r12)
jne bracket_0_start
bracket_0_end:
Verify x86_64 compiler
● build
$ make && ./compiler-x64 progs/hello.b > hello.s
$ gcc -o hello-x64 hello.s && ./hello-x64
Hello World!
● Check interpreter.c which reads a byte and immediately
performs an action based on the operator.
● Benchmark on GNU/Linux for x86_64
$ ./compiler-x64 progs/mandelbrot.b > mandelbrot.s
$ gcc -o mandelbrot mandelbrot.s && time ./mandelbrot
real 0m9.366s
Brainf*ck Compiler
[ARM backend]
Prologue/Epilogue for ARM
const char *const prologue =
".globl mainn"
"main:n"
"LDR R4 ,= _arrayn"
"push {lr}n";
const char *const epilogue =
" pop {pc}n"
".datan"
".align 4n"
"_char: .asciz "%c"n"
"_array: .space 30000n";
Data Pointers
● Moving the instruction pointer (>, <) and modifying the
pointed to value (+, -)
case '>':
puts("ADD R4, R4, #1");
break;
case '<':
puts("SUB R4, R4, #1");
break;
case '+':
puts("LDRB R5, [R4]");
puts("ADD R5, R5, #1");
puts("STRB R5, [R4]");
break;
case '-':
puts("LDRB R5, [R4]");
puts("SUB R5, R5, #1");
puts("STRB R5, [R4]");
break;
Input/Output
case ',':
puts("BL getchar");
puts("STRB R0, [R4]");
break;
case '.':
puts("LDR R0 ,= _char ");
puts("LDRB R1, [R4]");
puts("BL printf");
break;
NOTE:in epilogue
"_char: .asciz "%c"n"
Loop constructs [
case '[':
stack_push(&stack, num_brackets);
printf("_in_%d:n", num_brackets);
puts ("LDRB R5, [R4]");
puts ("CMP R5, #0");
printf("BEQ _out_%dn", num_brackets);
num_brackets++;
break;
Loop constructs ]
case ']':
stack_pop(&stack, &matching_bracket);
printf("_out_%d:n", matching_bracket);
puts ("LDRB R5, [R4]");
puts ("CMP R5, #0");
printf("BNE _in_%dn", matching_bracket);
break;
Brainf*ck JIT Compiler
[x86_64 backend]
Minimal JIT
#include <sys/mman.h>
int main(int argc, char *argv[]) {
unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3};
int num = atoi(argv[1]);
memcpy(&code[1], &num, 4);
void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC,
MAP_ANON | MAP_PRIVATE, -1, 0);
memcpy(mem, code, sizeof(code));
int (*func)() = mem;
return func();
}
Machine code for:
● mov eax, 0
● ret
Overwrite immediate value "0"
in the instruction with the user's
value. This will make our code:
● mov eax, <user's value>
● ret
Allocate writable/executable memory.
● Note: real programs should not map
memory both writable and executable
because it is a security risk
Minimal JIT: Evaluate
$ make test
$ ./jit0-x64 42 ; echo $?
42
● use mmap() to allocate the memory instead of malloc(),
the normal way of getting memory from the heap.
– This is necessary because we need the memory to be
executable so we can jump to it without crashing the
program.
● On most systems the stack and heap are configured not
to allow execution because if you're jumping to the stack
or heap it means something has gone very wrong.
DynASM
● is a part of the most impressive LuaJIT project, but is totally
independent of the LuaJIT code and can be used separately.
● consists of two parts
– a preprocessor that converts a mixed C/assembly file
(*.dasc) to straight C
– A tiny runtime that links against the C to do the work that
must be deferred until runtime.
DynASM
|.arch x64
|.actionlist actions
#define Dst &state
int main(int argc, char *argv[]) {
int num = atoi(argv[1]);
dasm_State *state;
initjit(&state, actions);
| mov eax, num
| ret
int (*fptr)() = jitcode(&state);
int ret = fptr();
free_jitcode(fptr);
return ret;
}
JIT using DynASM(1)
|.arch x64
|.actionlist actions
|
|// Use rbx as our cell pointer.
|// Since rbx is a callee-save register, it will be preserved
|// across our calls to getchar and putchar.
|.define PTR, rbx
|
|// Macro for calling a function.
|// In cases where our target is <=2**32 away we can use
|// | call &addr
|// But since we don't know if it will be, we use this safe
|// sequence instead.
|.macro callp, addr
| mov64 rax, (uintptr_t)addr
| call rax
|.endmacro
JIT using DynASM(2)
#define Dst &state
#define MAX_NESTING 256
int main(int argc, char *argv[]) {
dasm_State *state;
initjit(&state, actions);
unsigned int maxpc = 0;
int pcstack[MAX_NESTING];
int *top = pcstack, *limit = pcstack + MAX_NESTING;
// Function prologue.
| push PTR
| mov PTR, rdi
JIT using DynASM(3)
for (char *p = argv[1]; *p; p++) {
switch (*p) {
case '>':
| inc PTR
break;
case '<':
| dec PTR
break;
case '+':
| inc byte [PTR]
break;
case '-':
| dec byte [PTR]
break;
case '.':
| movzx edi, byte [PTR]
| callp putchar
break;
case ',':
| callp getchar
| mov byte [PTR], al
break;
JIT using DynASM(4)
case '[':
if (top == limit)
err("Nesting too deep.");
// Each loop gets two pclabels: at the beginning and end.
// We store pclabel offsets in a stack to link the loop
// begin and end together.
maxpc += 2;
*top++ = maxpc;
dasm_growpc(&state, maxpc);
| cmp byte [PTR], 0
| je =>(maxpc-2)
|=>(maxpc-1):
break;
case ']':
if (top == pcstack)
err("Unmatched ']'");
top--;
| cmp byte [PTR], 0
| jne =>(*top-1)
|=>(*top-2):
break;
}
}
JIT using DynASM(5)
// Function epilogue.
| pop PTR
| ret
void (*fptr)(char*) = jitcode(&state);
char *mem = calloc(30000, 1);
fptr(mem);
free(mem);
free_jitcode(fptr);
return 0;
}
Verify JIT compiler
● Benchmark on GNU/Linux for x86_64
$ time ./jit-x64 progs/mandelbrot.b
real 0m3.614s
user 0m3.612s
sys 0m0.004s
● Interpreter, Compiler, JIT
https://nickdesaulniers.github.io/blog/2015/05/25/interpreter-compiler-jit/
● 実用 Brainf*ck プログラミ
● The Unofficial DynASM Documentation
https://corsix.github.io/dynasm-doc/
● Hello, JIT World: The Joy of Simple JITs
http://blog.reverberate.org/2012/12/hello-jit-world-joy-of-simple-jits.html
Reference

Más contenido relacionado

La actualidad más candente

The Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPThe Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPGregor Schmidt
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールMITSUNARI Shigeo
 
イマドキC++erのモテカワリソース管理術
イマドキC++erのモテカワリソース管理術イマドキC++erのモテカワリソース管理術
イマドキC++erのモテカワリソース管理術Kohsuke Yuasa
 
Introduction to gdb
Introduction to gdbIntroduction to gdb
Introduction to gdbOwen Hsu
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDBLinaro
 
GNU ld的linker script簡介
GNU ld的linker script簡介GNU ld的linker script簡介
GNU ld的linker script簡介Wen Liao
 
[NDC16] Effective Git
[NDC16] Effective Git[NDC16] Effective Git
[NDC16] Effective GitChanwoong Kim
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu WorksZhen Wei
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCKernel TLV
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)Olve Maudal
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPUTomer Gabel
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!Mr. Vengineer
 
用十分鐘瞭解 《單晶片、機器人與電子元件》 (Arduino + Raspberry Pi)
用十分鐘瞭解  《單晶片、機器人與電子元件》  (Arduino + Raspberry Pi)用十分鐘瞭解  《單晶片、機器人與電子元件》  (Arduino + Raspberry Pi)
用十分鐘瞭解 《單晶片、機器人與電子元件》 (Arduino + Raspberry Pi)鍾誠 陳鍾誠
 
JJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
JJUG CCC 2018 Spring - I-7 (俺が)はじめての NettyJJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
JJUG CCC 2018 Spring - I-7 (俺が)はじめての NettyShinya Mochida
 

La actualidad más candente (20)

Embedded Virtualization applied in Mobile Devices
Embedded Virtualization applied in Mobile DevicesEmbedded Virtualization applied in Mobile Devices
Embedded Virtualization applied in Mobile Devices
 
The Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEPThe Microkernel Mach Under NeXTSTEP
The Microkernel Mach Under NeXTSTEP
 
Learn C Programming Language by Using GDB
Learn C Programming Language by Using GDBLearn C Programming Language by Using GDB
Learn C Programming Language by Using GDB
 
淺談探索 Linux 系統設計之道
淺談探索 Linux 系統設計之道 淺談探索 Linux 系統設計之道
淺談探索 Linux 系統設計之道
 
LLVM introduction
LLVM introductionLLVM introduction
LLVM introduction
 
Construct an Efficient and Secure Microkernel for IoT
Construct an Efficient and Secure Microkernel for IoTConstruct an Efficient and Secure Microkernel for IoT
Construct an Efficient and Secure Microkernel for IoT
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツール
 
イマドキC++erのモテカワリソース管理術
イマドキC++erのモテカワリソース管理術イマドキC++erのモテカワリソース管理術
イマドキC++erのモテカワリソース管理術
 
Introduction to gdb
Introduction to gdbIntroduction to gdb
Introduction to gdb
 
Pietのエディタを作った話
Pietのエディタを作った話Pietのエディタを作った話
Pietのエディタを作った話
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
 
GNU ld的linker script簡介
GNU ld的linker script簡介GNU ld的linker script簡介
GNU ld的linker script簡介
 
[NDC16] Effective Git
[NDC16] Effective Git[NDC16] Effective Git
[NDC16] Effective Git
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
 
ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!ARM Trusted FirmwareのBL31を単体で使う!
ARM Trusted FirmwareのBL31を単体で使う!
 
用十分鐘瞭解 《單晶片、機器人與電子元件》 (Arduino + Raspberry Pi)
用十分鐘瞭解  《單晶片、機器人與電子元件》  (Arduino + Raspberry Pi)用十分鐘瞭解  《單晶片、機器人與電子元件》  (Arduino + Raspberry Pi)
用十分鐘瞭解 《單晶片、機器人與電子元件》 (Arduino + Raspberry Pi)
 
JJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
JJUG CCC 2018 Spring - I-7 (俺が)はじめての NettyJJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
JJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
 

Similar a Interpreter, Compiler, JIT from scratch

Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
Ecet 340 Your world/newtonhelp.com
Ecet 340 Your world/newtonhelp.comEcet 340 Your world/newtonhelp.com
Ecet 340 Your world/newtonhelp.comamaranthbeg100
 
Ecet 340 Motivated Minds/newtonhelp.com
Ecet 340 Motivated Minds/newtonhelp.comEcet 340 Motivated Minds/newtonhelp.com
Ecet 340 Motivated Minds/newtonhelp.comamaranthbeg60
 
Ecet 340 Extraordinary Success/newtonhelp.com
Ecet 340 Extraordinary Success/newtonhelp.comEcet 340 Extraordinary Success/newtonhelp.com
Ecet 340 Extraordinary Success/newtonhelp.comamaranthbeg120
 
Ecet 340 Education is Power/newtonhelp.com
Ecet 340 Education is Power/newtonhelp.comEcet 340 Education is Power/newtonhelp.com
Ecet 340 Education is Power/newtonhelp.comamaranthbeg80
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfYodalee
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020Nikos Mouzakitis
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interruptTech_MX
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...AntareepMajumder
 
Computer Organization And Architecture lab manual
Computer Organization And Architecture lab manualComputer Organization And Architecture lab manual
Computer Organization And Architecture lab manualNitesh Dubey
 

Similar a Interpreter, Compiler, JIT from scratch (20)

Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
An Example MIPS
An Example  MIPSAn Example  MIPS
An Example MIPS
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Ecet 340 Your world/newtonhelp.com
Ecet 340 Your world/newtonhelp.comEcet 340 Your world/newtonhelp.com
Ecet 340 Your world/newtonhelp.com
 
Ecet 340 Motivated Minds/newtonhelp.com
Ecet 340 Motivated Minds/newtonhelp.comEcet 340 Motivated Minds/newtonhelp.com
Ecet 340 Motivated Minds/newtonhelp.com
 
Ecet 340 Extraordinary Success/newtonhelp.com
Ecet 340 Extraordinary Success/newtonhelp.comEcet 340 Extraordinary Success/newtonhelp.com
Ecet 340 Extraordinary Success/newtonhelp.com
 
Ecet 340 Education is Power/newtonhelp.com
Ecet 340 Education is Power/newtonhelp.comEcet 340 Education is Power/newtonhelp.com
Ecet 340 Education is Power/newtonhelp.com
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
 
Computer Organization And Architecture lab manual
Computer Organization And Architecture lab manualComputer Organization And Architecture lab manual
Computer Organization And Architecture lab manual
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

Más de National Cheng Kung University

PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimeNational Cheng Kung University
 
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明National Cheng Kung University
 
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明National Cheng Kung University
 
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明National Cheng Kung University
 
Develop Your Own Operating Systems using Cheap ARM Boards
Develop Your Own Operating Systems using Cheap ARM BoardsDevelop Your Own Operating Systems using Cheap ARM Boards
Develop Your Own Operating Systems using Cheap ARM BoardsNational Cheng Kung University
 
Lecture notice about Embedded Operating System Design and Implementation
Lecture notice about Embedded Operating System Design and ImplementationLecture notice about Embedded Operating System Design and Implementation
Lecture notice about Embedded Operating System Design and ImplementationNational Cheng Kung University
 
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學National Cheng Kung University
 
F9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded SystemsF9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded SystemsNational Cheng Kung University
 
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明National Cheng Kung University
 

Más de National Cheng Kung University (20)

PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
2016 年春季嵌入式作業系統課程說明
2016 年春季嵌入式作業系統課程說明2016 年春季嵌入式作業系統課程說明
2016 年春季嵌入式作業系統課程說明
 
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
進階嵌入式作業系統設計與實做 (2015 年秋季 ) 課程說明
 
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
 
從線上售票看作業系統設計議題
從線上售票看作業系統設計議題從線上售票看作業系統設計議題
從線上售票看作業系統設計議題
 
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
進階嵌入式系統開發與實做 (2014 年秋季 ) 課程說明
 
Xvisor: embedded and lightweight hypervisor
Xvisor: embedded and lightweight hypervisorXvisor: embedded and lightweight hypervisor
Xvisor: embedded and lightweight hypervisor
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
Implement Runtime Environments for HSA using LLVM
Implement Runtime Environments for HSA using LLVMImplement Runtime Environments for HSA using LLVM
Implement Runtime Environments for HSA using LLVM
 
Priority Inversion on Mars
Priority Inversion on MarsPriority Inversion on Mars
Priority Inversion on Mars
 
Develop Your Own Operating Systems using Cheap ARM Boards
Develop Your Own Operating Systems using Cheap ARM BoardsDevelop Your Own Operating Systems using Cheap ARM Boards
Develop Your Own Operating Systems using Cheap ARM Boards
 
Lecture notice about Embedded Operating System Design and Implementation
Lecture notice about Embedded Operating System Design and ImplementationLecture notice about Embedded Operating System Design and Implementation
Lecture notice about Embedded Operating System Design and Implementation
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
中輟生談教育: 完全用開放原始碼軟體進行 嵌入式系統教學
 
F9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded SystemsF9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
F9: A Secure and Efficient Microkernel Built for Deeply Embedded Systems
 
Open Source from Legend, Business, to Ecosystem
Open Source from Legend, Business, to EcosystemOpen Source from Legend, Business, to Ecosystem
Open Source from Legend, Business, to Ecosystem
 
Summer Project: Microkernel (2013)
Summer Project: Microkernel (2013)Summer Project: Microkernel (2013)
Summer Project: Microkernel (2013)
 
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明
進階嵌入式系統開發與實作 (2013 秋季班 ) 課程說明
 
Faults inside System Software
Faults inside System SoftwareFaults inside System Software
Faults inside System Software
 

Último

Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 

Último (20)

Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 

Interpreter, Compiler, JIT from scratch

  • 1. Interpreter, Compiler, JIT from scratch Jim Huang <jserv.tw@gmail.com>
  • 2. ● Brainf*ck: Turing complete programming language ● Interpreter ● Compiler ● JIT Compiler Agenda
  • 4. Brainf*ck Machine ● Assume we have unlimited length of buffer Address 0 1 2 3 4 … Value 0 0 0 0 0 … Source: http://jonfwilkins.blogspot.tw/2011/06/happy-99th-birthday-alan-turing.html
  • 5. Brainf*ck instructions Increment the byte value at the data pointer. Decrement the data pointer to point to the previous cell. Increment the data pointer to point to the next cell. Decrement the byte value at the data pointer. Output the byte value at the data pointer. Input one byte and store its value at the data pointer. If the byte value at the data pointer is zero, jump to the instruction following the matching ] bracket. Otherwise, continue execution. Unconditionally jump back to the matching [ bracket.
  • 6. Turing Complete ● Brianfuck has 6 opcode + Input/Output commands ● gray area for I/O (implementation dependent) – EOF – tape length – cell type – newlines ● That is enough to program! ● Extension: self-modifying Brainfuck https://soulsphere.org/hacks/smbf/
  • 7. Brainf*ck Address 0 1 2 3 4 … Value 0 0 0 0 0 … + > + < -
  • 8. Brainf*ck Address 0 1 2 3 4 … Value 1 0 0 0 0 … + > + < -
  • 9. Brainf*ck Address 0 1 2 3 4 … Value 1 0 0 0 0 … + > + < -
  • 10. Brainf*ck Address 0 1 2 3 4 … Value 1 1 0 0 0 … + > + < -
  • 11. Brainf*ck Address 0 1 2 3 4 … Value 1 1 0 0 0 … + > + < -
  • 12. Brainf*ck Address 0 1 2 3 4 … Value 0 1 0 0 0 … + > + < -
  • 13. Brainf*ck Address 0 1 2 3 4 … Value 64 0 0 0 0 … . [ > , ] Input Output 'A' 'B' '0'
  • 14. Brainf*ck Address 0 1 2 3 4 … Value 64 0 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 15. Brainf*ck Address 0 1 2 3 4 … Value 64 0 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 16. Brainf*ck Address 0 1 2 3 4 … Value 64 0 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 17. Brainf*ck Address 0 1 2 3 4 … Value 64 65 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 18. Brainf*ck Address 0 1 2 3 4 … Value 64 65 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 19. Brainf*ck Address 0 1 2 3 4 … Value 64 65 0 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 20. Brainf*ck Address 0 1 2 3 4 … Value 64 65 66 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 21. Brainf*ck Address 0 1 2 3 4 … Value 64 65 66 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 22. Brainf*ck Address 0 1 2 3 4 … Value 64 65 66 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 23. Brainf*ck Address 0 1 2 3 4 … Value 64 65 66 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 24. Brainf*ck Address 0 1 2 3 4 … Value 64 65 66 0 0 … . [ > , ] 'A' 'B' '0' '@' Input Output
  • 26. Initialization ● A Brainfuck program operates on a 30,000 element byte array initialized to all zeros. It starts off with an instruction pointer, that initially points to the first element in the data array or “tape.” // Initialize the tape with 30,000 zeroes. uint8_t tape [30000] = { 0 }; // Set the pointer to the left most cell of the tape. uint8_t* ptr = tape;
  • 27. Data Pointer ● Operators, > and < increment and decrement the data pointer. case '>': ++ptr; break; case '<': --ptr; break; ● One thing that could be bad is that because the interpreter is written in C and we’re representing the tape as an array but we’re not validating our inputs, there’s potential for stack buffer overrun since we’re not performing bounds checks. Again, punting and assuming well formed input to keep the code and the point more precise.
  • 28. Cells pointed to Data Pointer ● + and – operators are used for incrementing and decrementing the cell pointed to by the data pointer by one. case '+': ++(*ptr); break; case '-': --(*ptr); break;
  • 29. Input and Output ● The operators . and , provide Brainfuck’s only means of input or output, by writing the value pointed to by the instruction pointer to stdout as an ASCII value, or reading one byte from stdin as an ASCII value and writing it to the cell pointed to by the instruction pointer. case '.': putchar(*ptr); break; case ',': *ptr = getchar(); break;
  • 30. Loop ● Looping constructs, [ and ]. – [: if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command – ]: if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command.
  • 31. Loop case '[': if (!(*ptr)) { int loop = 1; while (loop > 0) { uint8_t current_char = input[++i]; if (current_char == ']') { --loop; } else if (current_char == '[') { ++loop; } } } break; case ']': if (*ptr) { int loop = 1; while (loop > 0) { uint8_t current_char = input[--i]; if (current_char == '[') { --loop; } else if (current_char == ']') { ++loop; } } } break;
  • 32. Verify the simple interpreter ● Fetch and build $ git clone https://github.com/embedded2015/jit-construct.git $ cd jit-construct $ make $ ./interpreter progs/hello.bf Hello World! ● Check interpreter.c which reads a byte and immediately performs an action based on the operator. ● Benchmark on GNU/Linux for x86_64 $ time ./interpreter progs/mandelbrot.b real 2m1.297s user 2m1.368s sys 0m0.004s
  • 34. Generate machine code ● How about if we want to compile the Brainfuck source code to native machine code? – Instruction Set Architecture (ISA) – Application Binary Interface (ABI) ● Iterate over every character in the source file again, switching on the recognized operator. – print assembly instructions to stdout. – Doing so requires running the compiler on an input file, redirecting stdout to a file, then running the system assembler and linker on that file.
  • 35. Prologue for compiled x86_64 const char *const prologue = ".textn" ".globl _mainn" "main:n" " pushq %rbpn" " movq %rsp, %rbpn" " pushq %r12n" // store callee saved register " subq $30008, %rspn" // allocate 30,008 B on stack, and realign " leaq (%rsp), %rdin" // address of beginning of tape " movl $0, %esin" // fill with 0's " movq $30000, %rdxn" // length 30,000 B " call memsetn" // memset " movq %rsp, %r12";
  • 36. Epilogue for compiled x86_64 const char *const epilogue = " addq $30008, %rspn" // clean up tape from stack. " popq %r12n" // restore callee saved register " popq %rbpn" " retn"; ● During the linking phase, we ensure linking in libc so we can call memset. What we do is backing up callee saved registers we’ll be using, stack allocating the tape, realigning the stack, copying the address of the only item on the stack into a register for our first argument, setting the second argument to the constant 0, the third arg to 30000, then calling memset. ● Finally, we use the callee saved register %r12 as our instruction pointer, which is the address into a value on the stack.
  • 37. Alignment ● We can expect the call to memset to result in a segfault if simply subtract just 30000B, and not realign for the 2 registers (64 b each, 8 B each) we pushed on the stack. ● The first pushed register aligns the stack on a 16 B boundary, the second misaligns it; that’s why we allocate an additional 8 B on the stack. Reference: System V Application Binary Interface AMD64 Architecture Processor Supplement Draft Version 0.99.6
  • 38. Data Pointers are straightforward ● Moving the instruction pointer (>, <) and modifying the pointed to value (+, -) case '>': puts(" inc %r12"); break; case '<': puts(" dec %r12"); break; case '+': puts(" incb (%r12)"); break; case '-': puts(" decb (%r12)"); break;
  • 39. Output ● Have to copy the pointed to byte into the register for the first argument to putchar. ● We explicitly zero out the register before calling putchar, since it takes an int (32 b), but we’re only copying a char (8 b) (C’s type promotion rules). – x86-64 has an instruction that does both, movzXX, Where the first X is the source size (b, w) and the second is the destination size (w, l, q). – movzbl moves a byte (8 b) into a double word (32 b). %rdi and %edi are the same register, but %rdi is the full 64 b register, while %edi is the lowest (or least significant) 32 b. case '.': puts(" movzbl (%r12), %edi"); puts(" call putchar"); break;
  • 40. Input ● Easily call getchar, move the resulting lowest byte into the cell pointed to by the instruction pointer. – %al is the lowest 8 b of the 64 b %rax register case ',': puts(" call getchar"); puts(" movb %al, (%r12)"); break;
  • 41. Loop constructs [ ● Have to match up jumps to matching labels – labels must be unique. ● Instead, whenever we encounter an opening brace, push a monotonically increasing number that represents the numbers of opening brackets we’ve seen so far onto a stack like data structure. – compare and jump to what will be the label that should be produced by the matching close label. – insert our starting label, and finally increment the number of brackets seen. case '[': stack_push(&stack, num_brackets); puts (" cmpb $0, (%r12)"); printf(" je bracket_%d_endn", num_brackets); printf("bracket_%d_start:n", num_brackets++); break;
  • 42. Loop constructs ] ● pop the number of brackets seen (or rather, number of pending open brackets which we have yet to see a matching close bracket) off of the stack, do our comparison, jump to the matching start label, and finally place our end label. case ']': stack_pop(&stack, &matching_bracket); puts(" cmpb $0, (%r12)"); printf(" jne bracket_%d_startn", matching_bracket); printf("bracket_%d_end:n", matching_bracket); break;
  • 43. Code generation of Nested Loop [ [ ] ] cmpb $0, (%r12) je bracket_0_end bracket_0_start: cmpb $0, (%r12) je bracket_1_end bracket_1_start: cmpb $0, (%r12) jne bracket_1_start bracket_1_end: cmpb $0, (%r12) jne bracket_0_start bracket_0_end:
  • 44. Verify x86_64 compiler ● build $ make && ./compiler-x64 progs/hello.b > hello.s $ gcc -o hello-x64 hello.s && ./hello-x64 Hello World! ● Check interpreter.c which reads a byte and immediately performs an action based on the operator. ● Benchmark on GNU/Linux for x86_64 $ ./compiler-x64 progs/mandelbrot.b > mandelbrot.s $ gcc -o mandelbrot mandelbrot.s && time ./mandelbrot real 0m9.366s
  • 46. Prologue/Epilogue for ARM const char *const prologue = ".globl mainn" "main:n" "LDR R4 ,= _arrayn" "push {lr}n"; const char *const epilogue = " pop {pc}n" ".datan" ".align 4n" "_char: .asciz "%c"n" "_array: .space 30000n";
  • 47. Data Pointers ● Moving the instruction pointer (>, <) and modifying the pointed to value (+, -) case '>': puts("ADD R4, R4, #1"); break; case '<': puts("SUB R4, R4, #1"); break; case '+': puts("LDRB R5, [R4]"); puts("ADD R5, R5, #1"); puts("STRB R5, [R4]"); break; case '-': puts("LDRB R5, [R4]"); puts("SUB R5, R5, #1"); puts("STRB R5, [R4]"); break;
  • 48. Input/Output case ',': puts("BL getchar"); puts("STRB R0, [R4]"); break; case '.': puts("LDR R0 ,= _char "); puts("LDRB R1, [R4]"); puts("BL printf"); break; NOTE:in epilogue "_char: .asciz "%c"n"
  • 49. Loop constructs [ case '[': stack_push(&stack, num_brackets); printf("_in_%d:n", num_brackets); puts ("LDRB R5, [R4]"); puts ("CMP R5, #0"); printf("BEQ _out_%dn", num_brackets); num_brackets++; break;
  • 50. Loop constructs ] case ']': stack_pop(&stack, &matching_bracket); printf("_out_%d:n", matching_bracket); puts ("LDRB R5, [R4]"); puts ("CMP R5, #0"); printf("BNE _in_%dn", matching_bracket); break;
  • 52. Minimal JIT #include <sys/mman.h> int main(int argc, char *argv[]) { unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3}; int num = atoi(argv[1]); memcpy(&code[1], &num, 4); void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0); memcpy(mem, code, sizeof(code)); int (*func)() = mem; return func(); } Machine code for: ● mov eax, 0 ● ret Overwrite immediate value "0" in the instruction with the user's value. This will make our code: ● mov eax, <user's value> ● ret Allocate writable/executable memory. ● Note: real programs should not map memory both writable and executable because it is a security risk
  • 53. Minimal JIT: Evaluate $ make test $ ./jit0-x64 42 ; echo $? 42 ● use mmap() to allocate the memory instead of malloc(), the normal way of getting memory from the heap. – This is necessary because we need the memory to be executable so we can jump to it without crashing the program. ● On most systems the stack and heap are configured not to allow execution because if you're jumping to the stack or heap it means something has gone very wrong.
  • 54. DynASM ● is a part of the most impressive LuaJIT project, but is totally independent of the LuaJIT code and can be used separately. ● consists of two parts – a preprocessor that converts a mixed C/assembly file (*.dasc) to straight C – A tiny runtime that links against the C to do the work that must be deferred until runtime.
  • 55. DynASM |.arch x64 |.actionlist actions #define Dst &state int main(int argc, char *argv[]) { int num = atoi(argv[1]); dasm_State *state; initjit(&state, actions); | mov eax, num | ret int (*fptr)() = jitcode(&state); int ret = fptr(); free_jitcode(fptr); return ret; }
  • 56. JIT using DynASM(1) |.arch x64 |.actionlist actions | |// Use rbx as our cell pointer. |// Since rbx is a callee-save register, it will be preserved |// across our calls to getchar and putchar. |.define PTR, rbx | |// Macro for calling a function. |// In cases where our target is <=2**32 away we can use |// | call &addr |// But since we don't know if it will be, we use this safe |// sequence instead. |.macro callp, addr | mov64 rax, (uintptr_t)addr | call rax |.endmacro
  • 57. JIT using DynASM(2) #define Dst &state #define MAX_NESTING 256 int main(int argc, char *argv[]) { dasm_State *state; initjit(&state, actions); unsigned int maxpc = 0; int pcstack[MAX_NESTING]; int *top = pcstack, *limit = pcstack + MAX_NESTING; // Function prologue. | push PTR | mov PTR, rdi
  • 58. JIT using DynASM(3) for (char *p = argv[1]; *p; p++) { switch (*p) { case '>': | inc PTR break; case '<': | dec PTR break; case '+': | inc byte [PTR] break; case '-': | dec byte [PTR] break; case '.': | movzx edi, byte [PTR] | callp putchar break; case ',': | callp getchar | mov byte [PTR], al break;
  • 59. JIT using DynASM(4) case '[': if (top == limit) err("Nesting too deep."); // Each loop gets two pclabels: at the beginning and end. // We store pclabel offsets in a stack to link the loop // begin and end together. maxpc += 2; *top++ = maxpc; dasm_growpc(&state, maxpc); | cmp byte [PTR], 0 | je =>(maxpc-2) |=>(maxpc-1): break; case ']': if (top == pcstack) err("Unmatched ']'"); top--; | cmp byte [PTR], 0 | jne =>(*top-1) |=>(*top-2): break; } }
  • 60. JIT using DynASM(5) // Function epilogue. | pop PTR | ret void (*fptr)(char*) = jitcode(&state); char *mem = calloc(30000, 1); fptr(mem); free(mem); free_jitcode(fptr); return 0; }
  • 61. Verify JIT compiler ● Benchmark on GNU/Linux for x86_64 $ time ./jit-x64 progs/mandelbrot.b real 0m3.614s user 0m3.612s sys 0m0.004s
  • 62. ● Interpreter, Compiler, JIT https://nickdesaulniers.github.io/blog/2015/05/25/interpreter-compiler-jit/ ● 実用 Brainf*ck プログラミ ● The Unofficial DynASM Documentation https://corsix.github.io/dynasm-doc/ ● Hello, JIT World: The Joy of Simple JITs http://blog.reverberate.org/2012/12/hello-jit-world-joy-of-simple-jits.html Reference