commit 55903be438b4b852330c075af6e51bda98a7c3eb
parent 554d531820eb7cf3d2f6d7a3cc209291996a9083
Author: Gabriel G. de Brito <gabrielgbrito@icloud.com>
Date: Mon, 18 Dec 2023 19:11:02 -0300
Added full RISC-V assembler parser. Needs testing and assembling ;)
Diffstat:
7 files changed, 400 insertions(+), 1 deletion(-)
diff --git a/assembler/assembler.go b/assembler/assembler.go
@@ -0,0 +1,219 @@
+// Package egg/assembler implements a set of usefull functions and structs for
+// creating assemblers.
+package assembler
+
+import (
+ "fmt"
+ "errors"
+ "strings"
+)
+
+const (
+ TOKEN_LABEL = iota
+ TOKEN_INSTRUCTION
+ TOKEN_ARG
+ TOKEN_LITERAL
+)
+
+// Can be label, instruction, arg or literal.
+type Token struct {
+ Type uint8
+ Value string
+}
+
+// Can be instruction or literal. Only instructions have Args.
+type ResolvedToken struct {
+ Type uint8
+ Size uint64
+ Value string
+ Args []uint64
+}
+
+// Only instructions.
+type DebuggerToken struct {
+ Instruction string
+ Args string
+ Address uint64
+ Label string
+}
+
+func CreateDebugTokensFixedSize(tokens []Token, size uint64) []DebuggerToken {
+ var dt []DebuggerToken
+ addr := uint64(0)
+ var last_label string
+
+ for _, t := range tokens {
+ switch t.Type {
+
+ // I'm pretty sure the tokenizer cannot create an argument
+ // before an instruction so we just ignore it and let have an
+ // undefined behaviour if that happens.
+ case TOKEN_INSTRUCTION:
+ dt = append(dt, DebuggerToken{
+ Instruction: t.Value,
+ Address: addr,
+ Label: last_label,
+ })
+ addr += size
+ last_label = ""
+ case TOKEN_LABEL:
+ last_label = t.Value
+ case TOKEN_LITERAL:
+ addr += uint64(len(t.Value))
+ last_label = ""
+ }
+ }
+
+ return dt
+}
+
+// Function to pass to ResolveTokensFixedSize.
+type ArgTranslateFunction func(string) (uint64, error)
+
+// Resolves labels and arguments for fixed-size instructions with size bytes.
+// ArgTranslateFunction translates arguments into numbers.
+func ResolveTokensFixedSize(tokens []Token, size uint64, arg ArgTranslateFunction) ([]ResolvedToken, error) {
+ var labels map[string]uint64
+ addr := uint64(0)
+ for _, t := range tokens {
+ switch (t.Type) {
+ case TOKEN_INSTRUCTION:
+ addr += size
+ case TOKEN_LITERAL:
+ addr += uint64(len(t.Value))
+ case TOKEN_LABEL:
+ labels[t.Value] = addr
+ }
+ }
+
+ var rt []ResolvedToken
+ i := 0
+
+ // I'm pretty sure the tokenizer cannot create an argument before an
+ // instruction so we just ignore it and let have an undefined behaviour
+ // if that happens.
+ for _, t := range tokens {
+ switch t.Type {
+ case TOKEN_INSTRUCTION:
+ rt = append(rt, ResolvedToken{
+ Type: TOKEN_INSTRUCTION,
+ Size: size,
+ Value: t.Value,
+ })
+ i++
+ case TOKEN_LITERAL:
+ rt = append(rt, ResolvedToken{
+ Type: TOKEN_LITERAL,
+ Size: uint64(len(t.Value)),
+ Value: t.Value,
+ })
+ i++
+ case TOKEN_ARG:
+ av, islabel := labels[t.Value]
+ if !islabel {
+ var err error
+ av, err = arg(t.Value)
+ if err != nil {
+ return nil, errors.New(fmt.Sprintf("Cannot resolve argument: %v", err))
+ }
+ }
+
+ rt[i - 1].Args = append(rt[i - 1].Args, av)
+ }
+ }
+
+ return rt, nil
+}
+
+func getHexNumber(r rune) (uint8, error) {
+ if 0x30 <= r && r <= 0x39 {
+ return uint8(r - 0x30), nil
+ } else if 0x41 <= r && r <= 0x46 {
+ return uint8(r - 0x37), nil
+ } else if 0x61 <= r && r <= 0x66 {
+ return uint8(r - 0x57), nil
+ } else {
+ return 0, errors.New("Malformed hex number")
+ }
+}
+
+// Parses everything cleanly excepts that any % followed by a two-digit hex
+// number (e.g., %FA) in substituted by it's own value. Use %% for a literal %.
+func ParseLiteral(lit string) string {
+ var b strings.Builder
+ i := 0
+ for i < len(lit) {
+ if lit[i] == '%' {
+ if i + 1 < len(lit) && lit[i + 1] == '%' {
+ b.WriteRune('%')
+ } else if i + 2 < len(lit) {
+ b2, err := getHexNumber(rune(lit[i + 1]))
+ if err != nil {
+ b.WriteRune('%')
+ i++
+ continue
+ }
+ b1, err := getHexNumber(rune(lit[i + 2]))
+ if err != nil {
+ b.WriteRune('%')
+ i++
+ continue
+ }
+ b.WriteRune(rune(b1 | (b2 << 4)))
+ i += 3
+ }
+ } else {
+ b.WriteRune(rune(lit[i]))
+ i++
+ }
+ }
+ return b.String()
+}
+
+// Tokenize uses a very standard Assembly syntax to create a token array:
+// - Define labels with :
+// - Arguments are separated by ,
+// - Comments start with ; and go to the end of the line
+// - Literals must be placed in lines beggining with # and are parsed by ParseLiteral
+func Tokenize(asm string) []Token {
+ var tokens []Token
+ // This handles trailing newlines and carriage returns ;).
+ for _, line := range strings.Split(strings.TrimRight(asm, "\n"), "\n") {
+ if len(line) == 0 {
+ continue
+ }
+ if line[0] == '#' {
+ tokens = append(tokens, Token{Type: TOKEN_LITERAL, Value: ParseLiteral(line[1:])})
+ continue
+ }
+ uncommented, _, _ := strings.Cut(line, ";")
+ uncommented = strings.TrimSpace(uncommented)
+ if len(uncommented) == 0 {
+ continue
+ }
+
+ label, ins, has_label := strings.Cut(uncommented, ":")
+ if !has_label {
+ ins = label
+ } else {
+ tokens = append(tokens, Token{Type: TOKEN_LABEL, Value: label})
+ }
+
+ ins = strings.TrimSpace(ins)
+ if len(ins) == 0 {
+ continue
+ }
+
+ mne, args, has_mne := strings.Cut(ins, " ")
+ // We already trimmed it so there's no way mne == "".
+ tokens = append(tokens, Token{Type: TOKEN_INSTRUCTION, Value: mne})
+ if has_mne {
+ for _, arg := range strings.Split(args, ",") {
+ arg = strings.TrimSpace(arg)
+ tokens = append(tokens, Token{Type: TOKEN_ARG, Value: arg})
+ }
+ }
+ }
+
+ return tokens
+}
diff --git a/assembler/assembler_test.go b/assembler/assembler_test.go
@@ -0,0 +1,47 @@
+package assembler
+
+import (
+ "testing"
+ "reflect"
+)
+
+func TestTokenizer(t *testing.T) {
+ asm := `
+;; Test assembly string for the tokenizer test
+_start:
+ addi t1, zero, 1
+ beq t1, zero, prob ;; Looks like your machine has some problem!
+ ebreak
+prob: addi a0, zero, msg ;; Let's fixed it!
+ ecall
+
+msg:
+#Your %6dachine is broken%0A
+`
+ tokens := Tokenize(asm)
+
+ expectedTokens := []Token{
+ Token{Type: TOKEN_LABEL, Value: "_start"},
+ Token{Type: TOKEN_INSTRUCTION, Value: "addi"},
+ Token{Type: TOKEN_ARG, Value: "t1"},
+ Token{Type: TOKEN_ARG, Value: "zero"},
+ Token{Type: TOKEN_ARG, Value: "1"},
+ Token{Type: TOKEN_INSTRUCTION, Value: "beq"},
+ Token{Type: TOKEN_ARG, Value: "t1"},
+ Token{Type: TOKEN_ARG, Value: "zero"},
+ Token{Type: TOKEN_ARG, Value: "prob"},
+ Token{Type: TOKEN_INSTRUCTION, Value: "ebreak"},
+ Token{Type: TOKEN_LABEL, Value: "prob"},
+ Token{Type: TOKEN_INSTRUCTION, Value: "addi"},
+ Token{Type: TOKEN_ARG, Value: "a0"},
+ Token{Type: TOKEN_ARG, Value: "zero"},
+ Token{Type: TOKEN_ARG, Value: "msg"},
+ Token{Type: TOKEN_INSTRUCTION, Value: "ecall"},
+ Token{Type: TOKEN_LABEL, Value: "msg"},
+ Token{Type: TOKEN_LITERAL, Value: "Your machine is broken\n"},
+ }
+
+ if !reflect.DeepEqual(tokens, expectedTokens) {
+ t.Fatalf("Tokenizer doesnt work: %v", tokens)
+ }
+}
diff --git a/debugger.go b/debugger.go
@@ -0,0 +1,12 @@
+package main
+
+import (
+ //"fmt"
+
+ "github.com/gboncoffee/egg/machine"
+ "github.com/gboncoffee/egg/assembler"
+)
+
+func debugMachine(m machine.Machine, sym []assembler.DebuggerToken) {
+ panic("not yet implemented")
+}
diff --git a/machine/machine.go b/machine/machine.go
@@ -1,6 +1,8 @@
// Package egg/machine has the interface and syscall struct used by EGG backends.
package machine
+import "github.com/gboncoffee/egg/assembler"
+
// Interface that machine structs are required to implement to work with EGG.
//
// It always use uint64 because if we used variable-lengh []bytes, they would
@@ -17,6 +19,8 @@ type Machine interface {
GetRegister(uint64) (uint64, error)
// Address than content.
SetRegister(uint64, uint64) error
+ //GetRegisterNumber(string) uint64
+ Assemble(string) ([]uint8, []assembler.DebuggerToken, error)
}
// Syscalls numbers. ISAs with specific calls for BREAK should send a BREAK on them.
diff --git a/main.go b/main.go
@@ -52,6 +52,15 @@ func runMachine(m machine.Machine) {
}
}
+func readToString(filename string) (string, error) {
+ data, err := os.ReadFile(filename)
+ if err != nil {
+ return "", err
+ }
+
+ return string(data), nil
+}
+
func main() {
var architeture string
var debug bool
@@ -100,9 +109,27 @@ func main() {
os.Exit(1)
}
+ asm, err := readToString(file)
+ if err != nil {
+ log.Println(fmt.Sprintf("Could not read supplied file %v", file))
+ os.Exit(1)
+ }
+
+ code, sym, err := m.Assemble(asm)
+ if err != nil {
+ log.Println("Error assembling file %v: %v", file, err)
+ os.Exit(1)
+ }
+
+ err = m.LoadProgram(code)
+ if err != nil {
+ log.Println("Error loading assembled program: %v", err)
+ os.Exit(1)
+ }
+
if debug {
// Hello fellow Acme user. Plumb this: debugger.go:/debugMachine
- debugMachine(m)
+ debugMachine(m, sym)
} else {
runMachine(m)
}
diff --git a/riscv/riscv.go b/riscv/riscv.go
@@ -5,8 +5,10 @@ import (
"errors"
"fmt"
"math"
+ "strconv"
"github.com/gboncoffee/egg/machine"
+ "github.com/gboncoffee/egg/assembler"
)
// The RiscV struct implements the machine interface needed by the EGG emulator.
@@ -454,3 +456,78 @@ func (m *RiscV) SetRegister(reg uint64, content uint64) error {
return nil
}
+
+func assemble(t []assembler.ResolvedToken) ([]uint8, error) {
+ return nil, errors.New("not implemented")
+}
+
+func parseRegisterArg(arg string) (uint64, error) {
+ n, err := strconv.Atoi(arg[1:])
+ if err != nil {
+ return 0, errors.New(fmt.Sprintf("No such register: %v", arg))
+ }
+
+ switch arg[0] {
+ case 't':
+ if n < 3 {
+ return uint64(n + 5), nil
+ }
+ return uint64(n + 25), nil
+ case 's':
+ switch n {
+ case 0:
+ return 8, nil
+ case 1:
+ return 9, nil
+ }
+ return uint64(n + 16), nil
+ case 'a':
+ return uint64(n + 10), nil
+ }
+
+ return 0, errors.New(fmt.Sprintf("No such register: %v", arg))
+}
+
+func translateArgs(arg string) (uint64, error) {
+ if len(arg) < 1 {
+ return 0, errors.New("Empty argument")
+ }
+
+ if 0x30 <= arg[0] && arg[0] <= 0x39 {
+ n, err := strconv.ParseInt(arg, 0, 64)
+ return uint64(n), err
+ }
+
+ switch arg {
+ case "zero":
+ return 0, nil
+ case "ra":
+ return 1, nil
+ case "sp":
+ return 2, nil
+ case "gp":
+ return 3, nil
+ case "tp":
+ return 4, nil
+ case "fp":
+ return 8, nil
+ }
+
+ return parseRegisterArg(arg)
+}
+
+func (m *RiscV) Assemble(asm string) ([]uint8, []assembler.DebuggerToken, error) {
+ tokens := assembler.Tokenize(asm)
+ rt, err := assembler.ResolveTokensFixedSize(tokens, 4, translateArgs)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ symbs := assembler.CreateDebugTokensFixedSize(tokens, 4)
+ code, err := assemble(rt)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return code, symbs, nil
+}
diff --git a/riscv/test.asm b/riscv/test.asm
@@ -0,0 +1,13 @@
+;;
+;; Test source file for RISC-V IM 32 bits implementation at EGG.
+;;
+
+_start:
+ addi t1, zero, 5
+ addi t2, zero, 1
+
+test: ;; This is a loop.
+ sub t1, t1, t2
+ bne t1, zero, test ;; Go out of the loop when tq = 0.
+
+ ebreak