Skip to content
systemcoding.dev
Virtualization

Dispatch bytecode with a switch inside a loop

Write the simplest bytecode interpreter in C, a for loop around a switch on the opcode, and see where its single indirect branch limits you.

2 min read
Summarize in AI

The baseline bytecode interpreter is a loop that reads an opcode and switches on it. Every other dispatch technique is a variation on this, so it is worth writing once, correctly.

vm.cc
#include <stdint.h>
#include <stdio.h>

enum { OP_PUSH, OP_ADD, OP_PRINT, OP_HALT };

void run(const uint8_t *ip) {
    int64_t stack[64], *sp = stack;
    for (;;) {
        switch (*ip++) {
        case OP_PUSH:  *sp++ = *ip++;           break;
        case OP_ADD:   sp--; sp[-1] += sp[0];   break;
        case OP_PRINT: printf("%lld\n", (long long)sp[-1]); break;
        case OP_HALT:  return;
        default:       fprintf(stderr, "bad opcode\n"); return;
        }
    }
}

int main(void) {
    const uint8_t prog[] = { OP_PUSH, 2, OP_PUSH, 3, OP_ADD, OP_PRINT, OP_HALT };
    run(prog);
}
Text
5

The compiler turns the switch into a bounds check plus one indirect jump through a table, shared by every opcode. That is the weakness: the CPU's branch predictor sees a single jump site with a different target each time, so on older cores it mispredicts often. Compilers can duplicate that jump into each handler on their own, but you cannot count on it. The next steps are computed goto and tail calls. Keep the default arm; it is your only defence against a corrupt program, and without it an out-of-range opcode is undefined behaviour in the table lookup. The stack here has no overflow check, so a real VM must add one.

Taggedc
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.