Make a host in Go, step 3: a driver shows hello

Text on a Terse32 screen comes from device 2, the terminal: 80 by 30 character cells. Rather than write it, use the device bus: each device is a separate program, a driver, that talks to your core over a Unix-domain socket. The Tersenet sources have a reference driver for every device. This step adds bus.go: start one driver, the terminal's, pass it the terminal's calls, and ask it for the grid to print.

The reference drivers are in the downloads' bus folder, for Linux, macOS and Windows. Or build them from the top folder of the sources:

cargo build --release -p terse-devices

Messages

Every message is a length (4 bytes, of the rest), an address (the machine, 4 bytes, always 0 here; a slot; 3 zero bytes) and a body whose first byte is its type. Integers are little-endian. send writes one; request writes one and reads the reply, whose type must be the request's plus REPLY. Anything else, an ERROR from the driver included, ends the run with status 3:

const (
    HELLO       = 0x01
    OPEN        = 0x03
    CALL        = 0x10
    BEGIN       = 0x30
    END         = 0x31
    STATE       = 0x40
    SHUTDOWN    = 0x60
    REPLY       = 0x80
    protocol    = 1
    addressSize = 8
    noSlot      = 0
)
func check(err error) {
    if err != nil {
        fmt.Fprintln(os.Stderr, "bus:", err)
        os.Exit(3)
    }
}

func words(b []byte, values ...uint32) []byte {
    for _, v := range values {
        b = le.AppendUint32(b, v)
    }
    return b
}

func (b *Bus) send(slot byte, body []byte) {
    message := words(nil, uint32(addressSize+len(body)))
    message = append(message, 0, 0, 0, 0, slot, 0, 0, 0)
    _, err := b.conn.Write(append(message, body...))
    check(err)
}

func (b *Bus) request(slot byte, body []byte) []byte {
    b.send(slot, body)
    var length uint32
    check(binary.Read(b.conn, le, &length))
    reply := make([]byte, length)
    _, err := io.ReadFull(b.conn, reply)
    check(err)
    reply = reply[addressSize:]
    if len(reply) == 0 || reply[0] != body[0]|REPLY {
        check(fmt.Errorf("the driver said %q", reply))
    }
    return reply
}

Starting the driver

type Bus struct {
    m      *Machine
    conn   net.Conn
    driver *exec.Cmd
    dir    string
    tables map[uint32]map[uint32][]byte
    Grants []byte
}

func Start(command string, m *Machine, file []byte,
    devices []Device) *Bus {
    dir, err := os.MkdirTemp("", "terse-bus")
    check(err)
    path := filepath.Join(dir, "bus.sock")
    listener, err := net.Listen("unix", path)
    check(err)
    driver := exec.Command(command)
    driver.Env = append(os.Environ(), "TERSE_BUS_SOCKET="+path)
    driver.Stdout, driver.Stderr = os.Stderr, os.Stderr
    check(driver.Start())
    conn, err := listener.Accept()
    check(err)
    listener.Close()
    b := &Bus{m: m, conn: conn, driver: driver, dir: dir,
        tables: map[uint32]map[uint32][]byte{}}

    var ask []byte
    for _, d := range devices {
        if d.Slot == Terminal || d.Slot == FullText {
            ask = append(ask, d.Slot)
        }
    }
    hello := []byte{HELLO, protocol, 0, 0, 0, 0, 0, 0}
    hello = append(append(hello, byte(len(ask))), ask...)
    hello = le.AppendUint16(hello, uint16(len(dir)))
    hello = append(append(hello, dir...), 0, 0)
    rest := b.request(noSlot, hello)[nameAt:]
    take := func(n int) []byte {
        taken := rest[:n]
        rest = rest[n:]
        return taken
    }
    length := le.Uint16(take(lengthSize))
    take(int(length) + nativeSize)
    versions := map[byte]byte{}
    for range take(1)[0] {
        slot, version := take(1)[0], take(1)[0]
        layers := int(take(1)[0])
        take(layerSize * layers)
        table := map[uint32][]byte{}
        for range take(1)[0] {
            entry := take(entrySize)
            table[uint32(entry[functionAt])] = entry
        }
        b.tables[uint32(slot)], versions[slot] = table, version
    }

    var has []byte
    for _, d := range devices {
        version, served := versions[d.Slot]
        granted := served && version == d.Version
        if !granted && !d.Optional {
            check(fmt.Errorf("no driver for device %d", d.Slot))
        }
        if d.Optional {
            b.Grants = append(b.Grants, byte(flag(granted)))
        }
        if granted {
            has = append(has, d.Slot, d.Version)
        }
    }
    id := blake3.Sum256(file)
    open := append([]byte{OPEN, 0, 0, 0}, id[:]...)
    open = words(open, uint32(len(m.ROM)), uint32(len(m.RAM)))
    open = append(open, 0, 0, byte(len(has)/deviceSize))
    open = append(append(open, has...), 0)
    reply := b.request(noSlot, append(open, m.ROM...))
    if reply[tookAt] != took {
        check(fmt.Errorf("the driver will not run the program"))
    }
    return b
}

In order:

Calls through the table

func (b *Bus) Call(slot, fn uint32) (uint32, int64) {
    m := b.m
    entry := b.tables[slot][fn]
    if entry == nil {
        return UnknownCall, BaseCharge
    }
    field := func(at int) uint32 {
        return le.Uint32(entry[at:])
    }
    flags, access := entry[flagsAt], entry[accessAt]
    charge := int64(answeredCharge)
    if flags&deferred != 0 {
        charge = BaseCharge
    }
    args := m.X[A0 : A5+1]
    addr := args[entry[bufferAt]]
    var buffer []byte
    if flags&buffered != 0 {
        size := uint64(field(scaleAt))
        if entry[lengthAt] != none {
            size *= uint64(args[entry[lengthAt]])
        }
        if size < uint64(field(leastAt)) ||
            size > uint64(field(mostAt)) {
            return field(lengthResultAt), charge
        }
        ramOnly := access&inROM == 0 || access&writes != 0
        buffer = m.Memory(addr, uint32(size), ramOnly)
        if buffer == nil && size > 0 {
            return field(placeResultAt), charge
        }
    }
    checked := entry[checkedAt]
    if checked != none && args[checked] > field(checkedMostAt) {
        return field(placeResultAt), charge
    }

    call := words([]byte{CALL, byte(fn), 0, 0}, args...)
    call = le.AppendUint64(call, uint64(m.Budget-BaseCharge))
    if access&reads == 0 {
        call = words(call, 0)
    } else {
        call = words(call, uint32(len(buffer)))
        call = append(call, buffer...)
    }
    reply := b.request(byte(slot), call)
    if reply[flagsAt]&setsA1 != 0 {
        m.X[A1] = le.Uint32(reply[a1At:])
    }
    at := writesAt
    for range le.Uint32(reply[writeCountAt:]) {
        write := reply[at:]
        offset := uint64(le.Uint32(write) - addr)
        size := le.Uint32(write[writeLengthAt:])
        end := offset + uint64(size)
        if access&writes == 0 || end > uint64(len(buffer)) {
            check(fmt.Errorf("a write outside the buffer"))
        }
        copy(buffer[offset:], write[writeDataAt:][:size])
        at += writeDataAt + int(size)
    }
    extra := int64(le.Uint32(reply[chargeAt:]))
    return le.Uint32(reply[a0At:]), charge + extra
}

A function the table does not have is a call the machine does not have: FFFF_FFFFh, charge 4. Otherwise the charge starts at 4 for a deferred call (flag 2: its result and charge follow from its arguments) or 64 for one the driver must answer. Before anything is sent, the table's checks: the buffer's length within its range, the buffer wholly in RAM (or in ROM, for one the device only reads), and a checked argument no larger than its limit; a call that fails gets the table's failure result and goes no further. Then CALL (10h) carries a0 to a5, the budget, and the bytes of a buffer the device reads, and RESULT (90h) gives a0, maybe a1, the charge on top, and bytes to write into the call's buffer.

The …At names are offsets in an entry and in RESULT; deferred, buffered, reads, writes and inROM are the entry's flag and access bits, and none (FFh) no argument. All of them: DEVICES.md sections 1.4 and 5.

Frames

BEGIN (30h) starts each frame: the frame counter, the time (0 here), no input events, an empty replay field. The reply, INPUTS, may charge the frame and bring events; the terminal does neither, and this host reads only the charge:

func (b *Bus) Begin(frame uint32) int64 {
    begin := words([]byte{BEGIN, 0, 0, 0}, frame, 0, 0, 0)
    reply := b.request(noSlot, begin)
    return int64(le.Uint32(reply[inputsChargeAt:]))
}

END (31h) ends the frame, with no reply. STATE (40h) asks for a slot's part of the machine's state; the terminal's starts with its 2,400 cells, 4 bytes each: a character (16 bits), a foreground and a background colour. SHUTDOWN (60h) stops the driver:

func (b *Bus) End() {
    stopped := byte(flag(b.m.Stopped != Running))
    end := words([]byte{END, stopped, 0, 0}, b.m.Frame)
    b.send(noSlot, end)
}

func (b *Bus) State(slot byte) []byte {
    return b.request(slot, []byte{STATE})[sectionAt:]
}

func (b *Bus) Close() {
    b.send(noSlot, []byte{SHUTDOWN})
    b.conn.Close()
    b.driver.Wait()
    os.RemoveAll(b.dir)
}

The program

package main

import (
    "encoding/binary"
    "fmt"
    "os"
    "strconv"
    "strings"

    "host/machine"
)

func main() {
    file, err := os.ReadFile(os.Args[1])
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(2)
    }
    frames, _ := strconv.Atoi(os.Args[2])
    cpu, devices, err := machine.Load(file)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(2)
    }
    m := &machine.Machine{CPU: cpu}
    bus := machine.Start(os.Args[3], m, file, devices)
    m.Devices = bus.Call
    for m.Stopped == machine.Running && int(m.Frame) < frames {
        m.Budget -= bus.Begin(m.Frame)
        m.RunFrame()
        bus.End()
    }
    fmt.Print(screen(bus.State(machine.Terminal)))
    bus.Close()
    if m.Fault != nil {
        fmt.Fprintln(os.Stderr, m.Fault)
        os.Exit(1)
    }
    os.Exit(int(m.ExitCode))
}

const (
    columns      = 80
    rows         = 30
    cellSize     = 4
    continuation = 0xffff
)

func screen(grid []byte) string {
    code := func(cell int) rune {
        at := cellSize * cell
        return rune(binary.LittleEndian.Uint16(grid[at:]))
    }
    var text strings.Builder
    for row := range rows {
        var line []rune
        for col := range columns {
            cell := row*columns + col
            rightHalf := col > 0 && code(cell-1) != continuation
            switch {
            case code(cell) != continuation:
                line = append(line, code(cell))
            case !rightHalf:
                line = append(line, ' ')
            }
        }
        trimmed := strings.TrimRight(string(line), " ")
        text.WriteString(trimmed + "\n")
    }
    return text.String()
}

screen prints the grid as terse run --dump does: a row's 80 cells, stripped of spaces at the end. FFFFh in a cell is the right half of a wide character, skipped after the character, else a space.

Run it

From examples/host/go, after go build -o bin/ ./...:

bin/step3 ../../../programs/hello/hello.terse 30 \
    ../../../target/release/terse-dev-terminal

prints hello's screen after 30 frames, 30 lines, which begins

 Tersenet · hello

  héllo, wörld — привет, мир
  Ελληνικά · кириллица · ┌─┬─┐ · ♥ ★ ✓

and is the reference's exactly: from the top folder, terse run programs/hello/hello.terse --frames 30 --dump prints the same 30 lines.

The driver can be any program that speaks the bus. Make a device in Go writes a terminal of 257 lines that is enough for hello; give its path instead of the reference's.

What you have now

A core that shows hello through a driver: bus.go, 289 lines, and step3/main.go, 71. What it leaves out: input events and writes from drivers (the terminal has none), more than one driver, READ (a driver asking for guest memory; the content driver does), sending deferred calls in batches (only faster), and timeouts. Next: Make a host in Go, step 4: prove it exact.