ring64

quickstart

run two x86-64 instructions that add 40 and 2.

npm install ring64

download add.ts and run node add.ts. it prints 42n from rax.

view add.ts
add.ts
import { createCpu, loadCpuCompiler, type Limits } from 'ring64';

const entry = 0x1000n;
// mov eax, 40; add eax, 2
const code = Uint8Array.of(0xb8, 0x28, 0x00, 0x00, 0x00, 0x83, 0xc0, 0x02);
const limits = {
  maxInstructions: 128,
  maxSourceBytes: 2048,
  maxArtifactBytes: 262144,
  maxCachedArtifacts: 32,
  maxCachedBytes: 4194304,
  maxTranslationsPerRun: 32,
} satisfies Limits;

const cpu = await createCpu({
  compiler: await loadCpuCompiler(),
  code: { base: entry, bytes: code },
  ram: { base: 0x8000n, bytes: new Uint8Array(32) },
  limits,
});

try {
  const result = await cpu.run({ budget: 10n, stop: entry + BigInt(code.length) });
  if (result.reason !== 'stop') throw new Error(`guest stopped with ${result.reason}`);
  console.log(result.state.registers[0]); // rax = 42n
} finally {
  cpu.dispose();
}

if node reports an unknown .ts extension, use node --experimental-strip-types add.ts.

run in a browser

bundle the same add.ts and put both standalone wasm files beside the bundle. the sdk requests the one your browser supports.

terminal
npx esbuild add.ts --bundle --format=esm \
  --outfile=public/add.js
cp node_modules/ring64/ring64.wasm node_modules/ring64/ring64-memory64.wasm public/

add this to public/index.html.

<script type="module" src="./add.js"></script>

serve public/ over http and open the page. 42n appears in the browser console.

run a binary

pass raw x86 instructions as a Uint8Array in code.bytes. set code.base to the guest address where execution starts.

for an elf or pe file, your app maps its sections and sets up the initial guest state.

example · load a c function

use clang and llvm-objcopy to extract the function's instruction bytes.

add.c
unsigned long long add(unsigned long long left, unsigned long long right) {
    return left + right;
}
terminal
clang --target=x86_64-unknown-none-elf -O2 -ffreestanding \
  -fno-stack-protector -fomit-frame-pointer -mno-red-zone \
  -c add.c -o add.o
llvm-objcopy -O binary --only-section=.text add.o add.bin

add-c.ts passes arguments in rdi and rsi and places a return address on the guest stack.

follow the browser steps with add-c.ts and put add.bin beside the bundle. it prints 42n.

parallel example

use createMachine from ring64/parallel to run the same x86-64 addition on two vcpus with different inputs. each vcpu runs in its own worker. both share guest memory.

download parallel.ts and run node parallel.ts. it prints [42n, 12n].

view parallel.ts
parallel.ts
import type { Limits } from 'ring64';
import { createMachine, loadParallelCompiler } from 'ring64/parallel';

const entry = 0x1000n;
const code = Uint8Array.of(0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0); // mov rax, rdi; add rax, rsi
const inputs = [
  [19n, 23n],
  [5n, 7n],
] as const;
const limits = {
  maxInstructions: 128,
  maxSourceBytes: 2048,
  maxArtifactBytes: 262144,
  maxCachedArtifacts: 32,
  maxCachedBytes: 4194304,
  maxTranslationsPerRun: 32,
} satisfies Limits;

const machine = await createMachine({
  compiler: await loadParallelCompiler(),
  limits,
  memoryModel: 'linear',
  memory: {
    backings: [{ id: 'code', bytes: code }],
    mappings: [
      {
        base: entry,
        backing: 'code',
        offset: 0,
        length: code.length,
        permissions: { read: true, write: false, execute: true },
      },
    ],
  },
  memoryLimits: { maxBackings: 1, maxMappings: 1, maxBackingBytes: code.length },
  sharedRamCapacity: 4096,
  cpus: inputs.map(() => ({ entry })),
});

try {
  const sums = await Promise.all(
    machine.cpus.map(async (cpu) => {
      const input = inputs[cpu.id];
      if (!input) throw new Error(`missing input for vcpu ${cpu.id}`);
      const state = await cpu.readState();
      state.registers[7] = input[0]; // rdi
      state.registers[6] = input[1]; // rsi
      await cpu.setState(state);

      const result = await cpu.run({ budget: 10n, stop: entry + BigInt(code.length) });
      if (result.reason !== 'stop') throw new Error(`guest stopped with ${result.reason}`);
      return result.state.registers[0];
    }),
  );
  console.log(sums); // [42n, 12n]
} finally {
  await machine.dispose();
}

if node reports an unknown .ts extension, use node --experimental-strip-types parallel.ts.

for a browser, see the parallel worker and isolation requirements.

cpu

create a standalone cpu, run the guest toward a stop address, then release the cpu. the quickstart shows how to prepare options.

run-cpu.ts
import { createCpu, type Options } from 'ring64';

export async function runCpu(options: Options, stop: bigint) {
  const cpu = await createCpu(options);
  try {
    return await cpu.run({ budget: 1_000n, stop });
  } finally {
    cpu.dispose();
  }
}

create and run

loadCpuCompiler(guestMemory?): Promise<WebAssembly.Module>
defaults to memory64 on hosts with wasm memory64 and multi-memory support. other hosts use memory32. pass 'memory32' or 'memory64' to select a profile explicitly. reuse the module across cpus.
createCpu(options: Options): Promise<Cpu>
pass a compiler as wasm bytes or a compiled module, plus limits and a memory configuration. context sets the initial execution mode and segments.
cpu.run(options: RunOptions): Promise<RunResult>
resumes from the current state. read or change state and memory between runs. run options and results describes the budget and stop reasons.

lifecycle

cpu.dispose(): void
releases the cpu. wait for any active run to settle before calling it.
cpu.reset(): void
resets an idle cpu in physical mode and preserves its memory.

interrupts

cpu.requestInterrupt(vector: number): boolean
queues an irq for an idle cpu. use a vector from 0 to 255. returns false if an irq is already queued.
cpu.requestNmi(): void
queues a non-maskable interrupt for an idle cpu.

diagnostics

cpu.inspectTranslations(): UnitMetadata[]
returns a snapshot of the cached translations.
cpu.creationMs: number
cpu creation time in milliseconds.

limits

set all six Limits fields as positive unsigned 32-bit integers. limits apply per vcpu. the quickstart shows a complete set.

maxInstructions, maxSourceBytes
cap the guest instructions and source bytes in one translation.
maxArtifactBytes
caps the bytes in one generated wasm module.
maxCachedArtifacts, maxCachedBytes
cap the module count and total bytes in the translation cache.
maxTranslationsPerRun
bounds translation attempts and retries per run.

run options and results

give cpu.run an instruction budget and an optional stop address. this example reads rax when execution reaches the stop address.

run-to.ts
import type { Cpu } from 'ring64';

export async function runTo(cpu: Cpu, stop: bigint) {
  const result = await cpu.run({ budget: 1_000n, stop });
  if (result.reason !== 'stop') throw new Error(result.reason);
  return result.state.registers[0]; // rax
}

options

budget: bigint
maximum guest instructions to retire.
stop?: bigint
stop before executing the instruction at this address.
repeatBudget?: bigint
maximum rep iterations. defaults to budget.
eventDelivery?: { budget: bigint }
exceptionDelivery?: { budget: bigint }
enables automatic guest event delivery with a separate budget. pass either spelling.

result fields

RunResult returns a state snapshot. retired and remaining track the instruction budget. repeatIterations and remainingRepeatBudget track the rep budget.

automatic delivery adds deliveryAttempts and remainingDeliveryBudget. resources counts translation and cache work. timings reports milliseconds.

stop reasons

stop, budget, repeat-budget
reached the stop address or used up an execution budget.
event-budget, pending-exception, pending-interrupt
delivery reached its budget or an event is waiting in state.event.
halted, shutdown, paused
guest halt, guest shutdown or a parallel pause.
unsupported, resource-limit
unsupported operation or a translation limit.

fault details

guest faults return results. check reason to find the diagnostic. invalid options and host failures, such as a throwing provider, can reject the run.

fetch-fault, target-fault, data-fault
fault describes the address, access, width and cause.
page-fault
pageFault includes the linear address and guest paging error code.
physical-memory-fault
physicalMemoryFault describes the guest physical access.
segment-fault, protection-fault, system-memory-fault
segmentFault, protectionFault or systemMemoryFault.
alignment-fault, alignment-check, debug-exception
alignmentFault, alignmentCheck or debugException.
simd-exception, x87-exception, general-protection
simdException, x87Exception or generalProtectionFault.
invalid-encoding, device-not-available, divide-error
invalid-encoding can include numericControlFault. device-not-available can include deviceNotAvailable.

memory

copy bytes from a readable linear address to a writable one on an idle cpu.

import type { Cpu } from 'ring64';

export function copyGuestBytes(cpu: Cpu, from: bigint, to: bigint, length: number) {
  const bytes = cpu.readMemory(from, length);
  cpu.writeMemory(to, bytes);
}

memory models

linear
the default. pass code and ram as { base: bigint, bytes: Uint8Array }. execution starts at code.base. code is readable and executable, ram is readable and writable.
ia32e-paged
uses guest page tables in long64 or compatibility mode. pass paging.
physical
maps guest physical addresses. pass context and paging.

read and write

readPhysicalMemory(address: bigint, length: number): Uint8Array
writePhysicalMemory(address: bigint, bytes: Uint8Array): void
access guest physical mappings in ia32e-paged or physical. reads return a copy.

on a parallel machine, call shared memory and mapping methods on the machine. they return promises.

backings and mappings

custom linear maps, ia32e-paged and physical require entry, memoryLimits and memory: { backings, mappings }.

MemoryBackingInput
pairs an id with bytes. with memory64, set byteLength to reserve a larger backing. bytes beyond the initial data start at zero.
MemoryMapping
names a backing and supplies base, offset, length and permissions for read, write and execute. mappings must fit their backing and occupy distinct guest ranges.
MemoryLimits
requires maxBackingBytes, maxBackings and maxMappings.

state

read or update an idle cpu between runs. this example sets the first integer argument in rdi for an x86-64 system v function.

import type { Cpu } from 'ring64';

export function setFirstArgument(cpu: Cpu, value: bigint) {
  const state = cpu.readState();
  state.registers[7] = value; // rdi
  cpu.setState(state);
}

registers

readState(): StateSnapshot
setState(state: State): void
general-purpose registers, instruction pointer, flags, interruptibility, events and interrupts. the Registers tuple is ordered rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, then r8–r15.

execution and system state

readPagingState(): PagingState
setPagingState(state: PagingState): void
paging controls for ia32e-paged or physical memory.
readFastSystemState(): FastSystemState
setFastSystemState(state: FastSystemState): void
fast system call state for ia32e-paged or physical memory.

floating point and simd

readXmmState(): bigint[]
setXmmState(state: bigint[]): void
16 xmm registers as unsigned 128-bit bigints.
readMxcsr(): number
setMxcsr(value: number): void
simd floating-point control and status.
readXcr0(): bigint
setXcr0(value: bigint): void
the extended register state mask.

debug and time

parallel

create a machine with ring64/parallel. each vcpu has its own state and worker. this example runs all vcpus toward the same stop address. the complete example includes machine setup and cleanup.

import type { Machine } from 'ring64/parallel';

export function runTogether(machine: Machine, stop: bigint) {
  const options = { budget: 1_000n, stop };
  return Promise.all(machine.cpus.map((cpu) => cpu.run(options)));
}
browser requirements

keep the package's worker modules and both parallel wasm files available at their relative urls. the browser needs shared memory with atomics and wasm multiple memories. serve the page with these headers to enable cross-origin isolation.

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

create a machine

loadParallelCompiler(guestMemory?): Promise<WebAssembly.Module>
defaults to memory64 on hosts with shared wasm memory64 and atomics. other hosts use memory32. the memory64 profile uses 32-bit wasm memory when the shared ram and metadata fit within 4 gib. pass 'memory32' or 'memory64' to select a profile explicitly.
createMachine(options: MachineOptions): Promise<Machine>
pass a parallel compiler, limits, memoryModel, memory and memoryLimits. set sharedRamCapacity to a positive multiple of 4096 bytes, allowing for each backing's size rounded up to 4096 bytes.
MachineOptions.cpus
supply at least two records with an entry address. paged and physical cpus need paging. physical cpus also need context.

run and pause

machine.cpus: readonly ParallelCpu[]
each vcpu handle has an id and asynchronous state methods.
cpu.run(options: RunOptions): Promise<ParallelRunResult>
runs one vcpu. the result has the same shape as for a standalone cpu.
cpu.pause(): Promise<void>
machine.pause(): Promise<void>
pause one vcpu or all active runs on the machine. a run that yields returns paused. machine pause waits for outstanding vcpu commands to settle. each command reports its own validation errors.

interrupts

cpu.requestInterrupt(vector: number): Promise<boolean>
cpu.requestNmi(): Promise<void>
queue a maskable or non-maskable interrupt on a vcpu, including during a run.

lifecycle

cpu.reset(): Promise<void>
machine.reset(): Promise<void>
physical mode only. reset one idle vcpu or pause active runs and reset all vcpus. both preserve shared memory. machine reset waits for outstanding vcpu commands to settle before resetting the vcpus.
machine.dispose(): Promise<void>
stops the workers and releases the machine.

port i/o

pass io: portOutput(onByte) to createCpu or createMachine. the provider calls onByte for each byte written to port 0xe9 and returns zero for reads.

import type { IoProvider } from 'ring64';

export function portOutput(onByte: (value: number) => void): IoProvider {
  return {
    read: () => 0,
    write(port, width, value) {
      if (port === 0xe9 && width === 8) onByte(value);
    },
  };
}

provider callbacks

ports are unsigned 16-bit numbers. IoWidth is 8 | 16 | 32 in bits. callbacks are synchronous and run on the host that created the cpu or machine. return from a callback before calling back into it.

read(port: number, width: IoWidth): number
return an unsigned integer that fits the width.
write(port: number, width: IoWidth, value: number): void
handle the unsigned value and return undefined.

memory-mapped i/o

pass mmio: byteRegister(0xf000n) to createCpu to attach a one-byte device register.

import type { MmioProvider } from 'ring64';

export function byteRegister(base: bigint): MmioProvider {
  let value = 0n;
  return {
    ranges: [{ base, length: 1 }],
    read: () => value,
    write: (_address, _width, next) => {
      value = next;
    },
  };
}

address ranges

the mmio option is available on a standalone cpu. ranges lists device regions as { base: bigint, length: number }. use linear addresses in linear mode and guest physical addresses otherwise. ranges occupy slots in maxMappings and must be disjoint from ram and each other.

a naturally aligned scalar mov wholly within one range can call the provider. instruction fetches, host memory methods and other guest memory operations see device addresses as unmapped.

provider callbacks

MmioWidth is 8 | 16 | 32 | 64 in bits. callbacks are synchronous. a throwing provider rejects the run.

read(address: bigint, width: MmioWidth): bigint
return an unsigned bigint that fits the width.
write(address: bigint, width: MmioWidth, value: bigint): void
handle the unsigned bigint and return undefined.