Skip to content

Commit

Permalink
[truffle] Prefix file with our bytecode with a magic string
Browse files Browse the repository at this point in the history
  • Loading branch information
pmurias committed Jul 10, 2018
1 parent 0daebf1 commit d842cdc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/vm/jvm/runtime/org/perl6/nqp/truffle/ByteCodeReader.java
Expand Up @@ -3,6 +3,7 @@
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class ByteCodeReader {
private ByteBuffer buffer;
Expand Down Expand Up @@ -31,6 +32,13 @@ public double readNum() {
return buffer.getDouble();
}

public boolean hasMagicString() {
if (buffer.remaining() < ByteCodeWriter.MAGIC.length) return false;
byte maybeMagic[] = new byte[ByteCodeWriter.MAGIC.length];
buffer.get(maybeMagic);
return Arrays.equals(maybeMagic, ByteCodeWriter.MAGIC);
}

public String readStr() {
int length = buffer.getInt();
byte[] encoded = new byte[length];
Expand Down
6 changes: 6 additions & 0 deletions src/vm/jvm/runtime/org/perl6/nqp/truffle/ByteCodeWriter.java
Expand Up @@ -5,6 +5,7 @@
import java.nio.ByteOrder;

public class ByteCodeWriter {
static byte[] MAGIC = new byte[] {'T', 'R', 'U', 'F', 'F', 'L', 'E', '6', '\r', '\n'};
private ByteBuffer buffer;

ByteCodeWriter() {
Expand All @@ -29,6 +30,11 @@ private void growToHold(int required) {
}
}

public void writeMagicString() {
growToHold(MAGIC.length);
buffer.put(MAGIC);
}

public void writeOpCode(int opCode) {
growToHold(4);
buffer.putInt(opCode);
Expand Down
7 changes: 7 additions & 0 deletions src/vm/jvm/runtime/org/perl6/nqp/truffle/TruffleCompiler.java
Expand Up @@ -109,7 +109,10 @@ protected void childrenToByteCode(SixModelObject node, int from, ByteCodeWriter

public void writeByteCode(SixModelObject tast, String output, ThreadContext tc) {
ByteCodeWriter writer = new ByteCodeWriter();

writer.writeMagicString();
writer.writeVersion(0);

tastToByteCode(tast, writer, tc);

try {
Expand Down Expand Up @@ -145,6 +148,10 @@ public void runByteCode(String input) {
buffer.order(ByteOrder.LITTLE_ENDIAN);

ByteCodeReader reader = new ByteCodeReader(buffer);

if (!reader.hasMagicString()) {
throw new RuntimeException("Bytecode stream corrupt (missing magic string)");
}
long version = reader.readVersion();

FrameDescriptor frameDescriptor = new FrameDescriptor();
Expand Down

0 comments on commit d842cdc

Please sign in to comment.