Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
101 lines (86 loc) · 2.23 KB
/
Copy pathmain.go
File metadata and controls
101 lines (86 loc) · 2.23 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//go:build !wasm
// +build !wasm
package main
import (
"fmt"
"backend/checker"
"backend/emulator"
"backend/genhex"
)
func main() {
cpu := emulator.NewCPU()
fmt.Printf("Completed cpu initialization\n")
fmt.Printf("RAX=%d, RBX=%d, RCX=%d, RDX=%d\n\n",
cpu.GetRegister(emulator.RAX),
cpu.GetRegister(emulator.RBX),
cpu.GetRegister(emulator.RCX),
cpu.GetRegister(emulator.RDX),
)
debugMode := true
if debugMode {
for i := 1; i < 5; i++ {
fmt.Printf("=== Level %d ===\n", i)
if err := genAndRunLevel(cpu, i); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("======================\n")
}
} else {
var hexInput string
fmt.Print("Enter machine code (hex): ")
fmt.Scanln(&hexInput)
if err := runHex(cpu, hexInput); err != nil {
fmt.Printf("Error: %v\n", err)
return
}
}
}
func assertEqualInt(expected, actual int) error {
if expected != actual {
return fmt.Errorf("assert equal failed: expected=%d, actual=%d", expected, actual)
}
return nil
}
func runHex(cpu *emulator.CPU, hex string) error {
code, err := emulator.ParseHexString(hex)
if err != nil {
return fmt.Errorf("parse hex: %w", err)
}
decoder := emulator.NewDecoder(code)
for decoder.HasMore() {
inst, err := decoder.DecodeNext()
if err != nil {
return fmt.Errorf("decode: %w", err)
}
if err := cpu.Execute(inst); err != nil {
return fmt.Errorf("execute: %w", err)
}
}
fmt.Printf("\n=== Execution Result ===\n")
fmt.Printf("RAX=%d, RBX=%d, RCX=%d, RDX=%d\n",
cpu.GetRegister(emulator.RAX),
cpu.GetRegister(emulator.RBX),
cpu.GetRegister(emulator.RCX),
cpu.GetRegister(emulator.RDX),
)
fmt.Printf("Final result (int32): %d\n", cpu.GetResult())
fmt.Printf("Final result (int32): %x\n", int32(cpu.GetResult()))
return nil
}
func genAndRunLevel(cpu *emulator.CPU, level int) error {
spaceHex, noSpaceHex, err := genhex.GenerateHex(level)
if err != nil {
return fmt.Errorf("GenerateHex: %w", err)
}
fmt.Println("Generated hex: " + spaceHex)
check, err := checker.CheckLevel(noSpaceHex)
if err != nil {
return fmt.Errorf("CheckLevel: %w", err)
}
fmt.Printf("Checker returned: %d\n", check)
if err := assertEqualInt(level, check); err != nil {
return err
}
return runHex(cpu, noSpaceHex)
}