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, which must be of the type asked for. Anything else, an ERROR from the driver included, ends the run with status 3:

func check(err error) {
    if err != nil {
        fmt.Fprintln(os.Stderr, "bus:", err)
        os.Exit(3)
    }
}

func (b *Bus) send(slot byte, body []byte) {
    message := le.AppendUint32(nil, uint32(8+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, want byte, body []byte) []byte {
    b.send(slot, body)
    var length [4]byte
    _, err := io.ReadFull(b.conn, length[:])
    check(err)
    reply := make([]byte, le.Uint32(length[:]))
    _, err = io.ReadFull(b.conn, reply)
    check(err)
    if len(reply) < 9 || reply[8] != want {
        check(fmt.Errorf("the driver said %q", reply[8:]))
    }
    return reply[8:]
}

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 == 2 || d.Slot == 10 {
            ask = append(ask, d.Slot)
        }
    }
    hello := []byte{0x01, 1, 0, 0, 0, 0, 0, 0, byte(len(ask))}
    hello = append(hello, ask...)
    hello = le.AppendUint16(hello, uint16(len(dir)))
    hello = append(append(hello, dir...), 0, 0)
    reply := b.request(0, 0x81, hello)
    at := 10 + int(le.Uint16(reply[4:]))
    versions := map[byte]byte{}
    for range reply[at] {
        slot, version := reply[at+1], reply[at+2]
        at += 4 + 2*int(reply[at+3])
        table := map[uint32][]byte{}
        for range reply[at] {
            table[uint32(reply[at+1])] = reply[at+1 : at+65]
            at += 64
        }
        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{0x03, 0, 0, 0}, id[:]...)
    open = le.AppendUint32(open, uint32(len(m.ROM)))
    open = le.AppendUint32(open, uint32(len(m.RAM)))
    open = append(open, 0, 0, byte(len(has)/2))
    open = append(append(open, has...), 0)
    reply = b.request(0, 0x83, append(open, m.ROM...))
    if reply[1] != 1 {
        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 0xffffffff, 4
    }
    charge := int64(64)
    if entry[1]&2 != 0 {
        charge = 4
    }
    args, access := m.X[10:16], entry[16]
    addr := args[entry[2]]
    var buffer []byte
    if entry[1]&4 != 0 {
        size := uint64(le.Uint32(entry[4:]))
        if entry[3] != 0xff {
            size *= uint64(args[entry[3]])
        }
        if size < uint64(le.Uint32(entry[8:])) ||
            size > uint64(le.Uint32(entry[12:])) {
            return le.Uint32(entry[24:]), charge
        }
        ramOnly := access&4 == 0 || access&2 != 0
        buffer = m.Memory(addr, uint32(size), ramOnly)
        if buffer == nil && size > 0 {
            return le.Uint32(entry[28:]), charge
        }
    }
    checked, most := entry[17], le.Uint32(entry[20:])
    if checked != 0xff && args[checked] > most {
        return le.Uint32(entry[28:]), charge
    }

    call := []byte{0x10, byte(fn), 0, 0}
    for _, a := range args {
        call = le.AppendUint32(call, a)
    }
    call = le.AppendUint64(call, uint64(m.Budget-4))
    if access&1 == 0 {
        call = le.AppendUint32(call, 0)
    } else {
        call = le.AppendUint32(call, uint32(len(buffer)))
        call = append(call, buffer...)
    }
    reply := b.request(byte(slot), 0x90, call)
    if reply[1]&1 != 0 {
        m.X[11] = le.Uint32(reply[8:])
    }
    at := 20
    for range le.Uint32(reply[16:]) {
        offset := uint64(le.Uint32(reply[at:]) - addr)
        size := uint64(le.Uint32(reply[at+4:]))
        if access&2 == 0 || offset+size > uint64(len(buffer)) {
            check(fmt.Errorf("a write outside the buffer"))
        }
        copy(buffer[offset:], reply[at+8:at+8+int(size)])
        at += 8 + int(size)
    }
    extra := int64(le.Uint32(reply[12:]))
    return le.Uint32(reply[4:]), 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.

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 := le.AppendUint32([]byte{0x30, 0, 0, 0}, frame)
    begin = append(begin, make([]byte, 12)...)
    return int64(le.Uint32(b.request(0, 0xb0, begin)[4:]))
}

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 := []byte{0x31, stopped, 0, 0}
    b.send(0, le.AppendUint32(end, b.m.Frame))
}

func (b *Bus) State(slot byte) []byte {
    return b.request(slot, 0xc0, []byte{0x40})[8:]
}

func (b *Bus) Close() {
    b.send(0, []byte{0x60})
    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(2)))
    bus.Close()
    if m.Fault != nil {
        fmt.Fprintln(os.Stderr, m.Fault)
        os.Exit(1)
    }
    os.Exit(int(m.ExitCode))
}

func screen(grid []byte) string {
    code := func(cell int) rune {
        return rune(binary.LittleEndian.Uint16(grid[4*cell:]))
    }
    var text strings.Builder
    for row := range 30 {
        var line []rune
        for col := range 80 {
            cell := row*80 + col
            rightHalf := col > 0 && code(cell-1) != 0xffff
            switch {
            case code(cell) != 0xffff:
                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, 202 lines, and step3/main.go, 63. 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.