all repos — xyw @ 4f11cb9c874e5baa2c1adf150c2949688a6edbe6

A minimal virtual machine and assembler for terminals.

devices/system.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "../xyw.h"

#define SYSTEM_STATE 0x00
#define SYSTEM_ERROR 0x01
#define SYSTEM_PAGE 0x02
#define SYSTEM_RANDOM 0x03
#define SYSTEM_IMAGE_EXEC 0x06
#define SYSTEM_IMAGE_EXEC_TRIGGER 0x08

#define SYSTEM_IMAGE_EXEC_DIRECTION 0x01 // 0 = exec child, 1 = return to parent
#define SYSTEM_IMAGE_EXEC_PRESERVE  0x02 // EXEC only: snapshot self to be able to return to previous image

void system_setup(xyw_byte *data)
{
    (void)data;
    // Initialize random generator seed
    srand(time(NULL));
}

xyw_byte system_input(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    if (addr == SYSTEM_RANDOM)
    {
        return (xyw_byte)(rand() & 0xFF);
    }
    (void)error;
    return data[addr];
}

void system_output(xyw_byte *data, xyw_byte addr, xyw_byte *error)
{
    (void)error;
    if (addr == SYSTEM_IMAGE_EXEC_TRIGGER && data[SYSTEM_IMAGE_EXEC_TRIGGER] != 0)
    {
        xyw_byte trig = data[SYSTEM_IMAGE_EXEC_TRIGGER];
        data[SYSTEM_IMAGE_EXEC_TRIGGER] = 0;
        if (trig & SYSTEM_IMAGE_EXEC_DIRECTION)
        {
            xyw_request_return();
        }
        else
        {
            xyw_word target = XYW_PEEKW(&data[SYSTEM_IMAGE_EXEC]);
            if (target != 0) {
                xyw_request_exec(target, trig & SYSTEM_IMAGE_EXEC_PRESERVE);
            }
        }
    }
}