forked from joebobmiles/SUBLEQ-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubleq.cpp
121 lines (95 loc) · 2.61 KB
/
subleq.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* @file subleq.cpp
* @author Joseph Miles <josephmiles2015@gmail.com>
* @date 2019-06-10
*
* This file contains the main entry point for subleq.exe, the SUBLEQ emulator.
*/
// C standard libraries.
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <fstream>
#define IsStdout(OFFSET) (OFFSET == -1)
enum status {
NORMAL,
NO_INPUT,
NO_SUCH_FILE,
INVALID_BINARY,
OFFSET_OUT_OF_BOUNDS,
UNKNOWN
};
static
bool InBounds(int Offset, long Extent)
{
if (IsStdout(Offset))
return true;
else if (0 <= Offset && Offset < Extent)
return true;
else
return false;
}
int main(int argc, char** argv)
{
if (argc == 1)
{
printf("No input binary given, exiting.\n");
return NO_INPUT;
}
std::ifstream BinaryFile (argv[1],
std::ifstream::out | std::ifstream::binary);
if (!BinaryFile)
{
printf("Failed to open binary \"%s\", exiting.\n", argv[1]);
return NO_SUCH_FILE;
}
// Discover binary size.
BinaryFile.seekg(0, BinaryFile.end);
long ProgramLength = BinaryFile.tellg();
BinaryFile.seekg(0, BinaryFile.beg);
if (ProgramLength %3 != 0)
{
printf("Input file size (%ldb) is not a multiple of three.\n"
"Input file is not a valid SUBLEQ binary, exiting.\n",
ProgramLength);
return INVALID_BINARY;
}
int *Program = new int[ProgramLength];
// TODO[joe] Abort if we haven't read the bytes we are looking for?
BinaryFile.read((char *)Program, ProgramLength);
int ProgramCounter, A, B, C = 0;
do
{
A = Program[ProgramCounter++];
B = Program[ProgramCounter++];
C = Program[ProgramCounter++];
if (!InBounds(A, ProgramLength) ||
!InBounds(B, ProgramLength) ||
!InBounds(C, ProgramLength))
{
break;
}
// The SUBLEQ operation.
if ((Program[B] = Program[A] - Program[B]) <= 0)
ProgramCounter = C;
printf("%d\n", Program[B]);
}
while (InBounds(ProgramCounter, ProgramLength) &&
!IsStdout(ProgramCounter));
if (!InBounds(ProgramCounter, ProgramLength))
{
printf("Program counter is out-of-bounds, exiting.\n");
return OFFSET_OUT_OF_BOUNDS;
}
else if (!InBounds(A, ProgramLength) ||
!InBounds(B, ProgramLength) ||
!InBounds(C, ProgramLength))
{
printf("Attempted to access an out-of-bounds offset, exiting.\n");
return OFFSET_OUT_OF_BOUNDS;
}
else
{
return NORMAL;
}
}