Repository: parrt/simple-virtual-machine
Branch: shatter-stack
Commit: 82a6f4716696
Files: 10
Total size: 25.0 KB
Directory structure:
gitextract_oxlhz3h_/
├── .gitignore
├── LICENSE
├── README.md
├── simple-virtual-machine.iml
├── simple-virtual-machine.ipr
└── src/
└── vm/
├── Bytecode.java
├── Context.java
├── FuncMetaData.java
├── Test.java
└── VM.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
================================================
FILE: LICENSE
================================================
Copyright (c) 2014, Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
simple-virtual-machine
======================
A simple VM for a talk on building VMs in Java. See [video](https://www.youtube.com/watch?v=OjaAToVkoTw) and [slides](http://www.slideshare.net/parrt/how-to-build-a-virtual-machine).
There are multiple branches:
* [master](https://github.com/parrt/simple-virtual-machine). Basic instructions only (no function calls).
* [add-functions](https://github.com/parrt/simple-virtual-machine/tree/add-functions). Includes CALL/RET instructions, runs factorial test function.
* [split-stack](https://github.com/parrt/simple-virtual-machine/tree/split-stack). Split into operand stack and function call stack.
* [func-meta-info](https://github.com/parrt/simple-virtual-machine/tree/func-meta-info). CALL bytecode instruction takes an index into a metadata table for functions rather than an address and the number of arguments. This makes it much easier for bytecode compiler to generate code because it doesn't need to worry about forward references. This branch also properly allocates space for local variables.
* [shatter-stack](https://github.com/parrt/simple-virtual-machine/tree/shatter-stack). Broke apart the `Context[]` stack into a linked-list with `invokingContext` as parent pointer to caller. added call stack for trace.
See also a [C version derived from split-stack](https://github.com/parrt/simple-virtual-machine-C). Parts derived from [codyebberson's C implementation](https://github.com/codyebberson/vm).
================================================
FILE: simple-virtual-machine.iml
================================================
================================================
FILE: simple-virtual-machine.ipr
================================================
================================================
FILE: src/vm/Bytecode.java
================================================
package vm;
public class Bytecode {
public static class Instruction {
String name; // E.g., "iadd", "call"
int n = 0;
public Instruction(String name) { this(name,0); }
public Instruction(String name, int nargs) {
this.name = name;
this.n = nargs;
}
}
// INSTRUCTION BYTECODES (byte is signed; use a short to keep 0..255)
public static final short IADD = 1; // int add
public static final short ISUB = 2;
public static final short IMUL = 3;
public static final short ILT = 4; // int less than
public static final short IEQ = 5; // int equal
public static final short BR = 6; // branch
public static final short BRT = 7; // branch if true
public static final short BRF = 8; // branch if true
public static final short ICONST = 9; // push constant integer
public static final short LOAD = 10; // load from local context
public static final short GLOAD = 11; // load from global memory
public static final short STORE = 12; // store in local context
public static final short GSTORE = 13; // store in global memory
public static final short PRINT = 14; // print stack top
public static final short POP = 15; // throw away top of stack
public static final short CALL = 16;
public static final short RET = 17; // return with/without value
public static final short HALT = 18;
public static Instruction[] instructions = new Instruction[] {
null, //
new Instruction("iadd"), // index is the opcode
new Instruction("isub"),
new Instruction("imul"),
new Instruction("ilt"),
new Instruction("ieq"),
new Instruction("br", 1),
new Instruction("brt", 1),
new Instruction("brf", 1),
new Instruction("iconst", 1),
new Instruction("load", 1),
new Instruction("gload", 1),
new Instruction("store", 1),
new Instruction("gstore", 1),
new Instruction("print"),
new Instruction("pop"),
new Instruction("call", 1), // call index of function in meta-info table
new Instruction("ret"),
new Instruction("halt")
};
}
================================================
FILE: src/vm/Context.java
================================================
package vm;
/** To call, push one of these and pop to return */
public class Context {
Context invokingContext; // parent in the stack or "caller"
FuncMetaData metadata; // info about function we're executing
int returnip;
int[] locals; // args + locals, indexed from 0
public Context(Context invokingContext, int returnip, FuncMetaData metadata) {
this.invokingContext = invokingContext;
this.returnip = returnip;
this.metadata = metadata;
locals = new int[metadata.nargs+metadata.nlocals];
}
}
================================================
FILE: src/vm/FuncMetaData.java
================================================
package vm;
public class FuncMetaData {
public String name;
public int nargs;
public int nlocals;
public int address; // bytecode address
public FuncMetaData(String name, int nargs, int nlocals, int address) {
this.name = name;
this.nargs = nargs;
this.nlocals = nlocals;
this.address = address;
}
}
================================================
FILE: src/vm/Test.java
================================================
package vm;
import static vm.Bytecode.BR;
import static vm.Bytecode.BRF;
import static vm.Bytecode.CALL;
import static vm.Bytecode.GLOAD;
import static vm.Bytecode.GSTORE;
import static vm.Bytecode.HALT;
import static vm.Bytecode.IADD;
import static vm.Bytecode.ICONST;
import static vm.Bytecode.ILT;
import static vm.Bytecode.IMUL;
import static vm.Bytecode.ISUB;
import static vm.Bytecode.LOAD;
import static vm.Bytecode.PRINT;
import static vm.Bytecode.RET;
import static vm.Bytecode.STORE;
public class Test {
static int[] hello = {
ICONST, 1,
ICONST, 2,
IADD,
PRINT,
HALT
};
static int[] loop = {
// .GLOBALS 2; N, I
// N = 10 ADDRESS
ICONST, 10, // 0
GSTORE, 0, // 2
// I = 0
ICONST, 0, // 4
GSTORE, 1, // 6
// WHILE I stack = new ArrayList();
Context c = ctx;
while ( c!=null ) {
if ( c.metadata!=null ) {
stack.add(0, c.metadata.name);
}
c = c.invokingContext;
}
return "calls="+stack.toString();
}
protected String disInstr() {
int opcode = code[ip];
String opName = Bytecode.instructions[opcode].name;
StringBuilder buf = new StringBuilder();
buf.append(String.format("%04d:\t%-11s", ip, opName));
int nargs = Bytecode.instructions[opcode].n;
if ( opcode==CALL ) {
buf.append(metadata[code[ip+1]].name);
}
else if ( nargs>0 ) {
List operands = new ArrayList();
for (int i=ip+1; i<=ip+nargs; i++) {
operands.add(String.valueOf(code[i]));
}
for (int i = 0; i0 ) buf.append(", ");
buf.append(s);
}
}
return buf.toString();
}
protected void dumpDataMemory() {
System.err.println("Data memory:");
int addr = 0;
for (int o : globals) {
System.err.printf("%04d: %s\n", addr, o);
addr++;
}
System.err.println();
}
}