-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdcpu.go
371 lines (300 loc) · 9.34 KB
/
dcpu.go
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Package dcpu implements an emulator for Notch's DCPU 1.7 specification.
package dcpu
import (
"fmt"
"log"
"unicode/utf16"
)
const (
// MemorySize is the total size of the DCPU memory array.
MemorySize = 0x10000
// BasicOpcodeMask is used to extract the basic opcode.
BasicOpcodeMask = 0x001f
// BasicValueMaskA is used to extract the value of operand a.
BasicValueMaskA = 0xfc00
// BasicValueMaskB is used to extract the value of operand b.
BasicValueMaskB = 0x03e0
// BasicValueShiftA is used to extract the shifted value of operand a.
BasicValueShiftA = 0xa
// BasicValueShiftB is used to extract the shifted value of operand b.
BasicValueShiftB = 0x5
// SpecialOpcodeMask is used to extract the special opcode.
SpecialOpcodeMask = BasicValueMaskB
// SpecialOpcodeShift is used to extract the shifted special opcode.
SpecialOpcodeShift = BasicValueShiftB
// SpecialValueMaskA is used to extract the value of operand a.
SpecialValueMaskA = BasicValueMaskA
// SpecialValueShiftA is used to extract the shifted value of operand a.
SpecialValueShiftA = BasicValueShiftA
// DebugOpcodeMask is used to extract the debug opcode.
DebugOpcodeMask = BasicValueMaskA
// DebugOpcodeShift is used to extract the shifted debug opcode.
DebugOpcodeShift = BasicValueShiftA
)
// DCPU represents the state of a DCPU machine.
type DCPU struct {
RegisterA uint16
RegisterB uint16
RegisterC uint16
RegisterX uint16
RegisterY uint16
RegisterZ uint16
RegisterI uint16
RegisterJ uint16
ProgramCounter uint16
StackPointer uint16
Extra uint16
InterruptAddress uint16
InterruptQueue []uint16
QueueInterrupts bool
InstructionCount uint16
Memory [MemorySize]uint16
Hardware []Hardware
}
// Basic builds a basic instruction with operands b and a.
func Basic(opcode BasicOpcode, b OperandB, a OperandA) (instruction uint16) {
instruction = uint16(opcode) | uint16(b<<BasicValueShiftB) | uint16(a<<BasicValueShiftA)
return
}
// Special builds a special instruction with operand a.
func Special(opcode SpecialOpcode, a OperandA) (instruction uint16) {
instruction = uint16(opcode<<SpecialOpcodeShift) | uint16(a<<SpecialValueShiftA)
return
}
// Debug builds a debug instruction.
func Debug(opcode DebugOpcode) (instruction uint16) {
instruction = uint16(opcode << DebugOpcodeShift)
return
}
// Load copies a sequence of instructions (a program) into memory.
func (d *DCPU) Load(start uint16, instructions []uint16) (address uint16) {
copy(d.Memory[start:], instructions)
address = start + uint16(len(instructions))
return
}
// LoadString copies a string into memory as utf16.
func (d *DCPU) LoadString(start uint16, message string) {
encoded := utf16.Encode([]rune(message))
d.Load(start, []uint16{uint16(len(encoded))})
d.Load(start+1, encoded)
}
// Execute runs the DCPU machine and all connected hardware.
func (d *DCPU) Execute() {
for {
d.ExecuteInstruction(false)
for i := range d.Hardware {
d.Hardware[i].Execute(d)
}
}
}
// ExecuteInstructions executes multiple instructions.
func (d *DCPU) ExecuteInstructions(count int) {
for i := 0; i < count; i++ {
d.ExecuteInstruction(false)
for i := range d.Hardware {
d.Hardware[i].Execute(d)
}
}
}
func (d DCPU) String() string {
state := []interface{}{}
state = append(state,
d.RegisterA, d.RegisterB, d.RegisterC,
d.RegisterX, d.RegisterY, d.RegisterZ,
d.RegisterI, d.RegisterJ,
d.ProgramCounter, d.StackPointer, d.Extra,
d.InterruptAddress, len(d.InterruptQueue), d.QueueInterrupts,
len(d.Hardware), d.InstructionCount,
)
for _, value := range d.Memory[0x0000:0x0020] {
state = append(state, value)
}
for _, value := range d.Memory[0x1000:0x1020] {
state = append(state, value)
}
return fmt.Sprintf(`A: %#04x B: %#04x C: %#04x X: %#04x Y: %#04x Z: %#04x I: %#04x J: %#04x
PC %#04x SP %#04x EX %#04x IA %#04x IQ %#04x Q: % 6v HW %#04x IC %#04x
[0x0000:0x0008] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x0008:0x0010] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x0010:0x0018] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x0018:0x0020] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x1000:0x1008] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x1008:0x1010] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x1010:0x1018] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
[0x1018:0x1020] %#04x %#04x %#04x %#04x %#04x %#04x %#04x %#04x
`, state...)
}
// ExecuteInstruction executes a single instruction.
func (d *DCPU) ExecuteInstruction(skip bool) {
if !skip && !d.QueueInterrupts && len(d.InterruptQueue) > 0 {
d.maybeTriggerInterrupt(d.InterruptQueue[0])
d.InterruptQueue = d.InterruptQueue[1:]
}
if !skip {
d.InstructionCount++
}
stackPointerBackup := d.StackPointer
instruction := d.Memory[d.ProgramCounter]
d.ProgramCounter++
basicOpcode := BasicOpcode(instruction & BasicOpcodeMask)
specialOpcode := SpecialOpcode((instruction & SpecialOpcodeMask) >> SpecialOpcodeShift)
if basicOpcode != BasicReserved {
operandA := (instruction & BasicValueMaskA) >> BasicValueShiftA
operandB := (instruction & BasicValueMaskB) >> BasicValueShiftB
pa, a := d.getOperandAddressOrLiteral(operandA, false)
if pa != nil {
a = *pa
}
pb, b := d.getOperandAddressOrLiteral(operandB, true)
if pb != nil {
b = *pb
}
// log.Println("instruction", instruction)
// log.Println("basicOpcode", basicOpcode)
//
// log.Println("operandB", operandB)
// log.Println("pb", int(uintptr(unsafe.Pointer(pb)))-int(uintptr(unsafe.Pointer(&d.Memory))))
// log.Println("b", b)
//
// log.Println("operandA", operandA)
// log.Println("pa", int(uintptr(unsafe.Pointer(pa)))-int(uintptr(unsafe.Pointer(&d.Memory))))
// log.Println("a", a)
//
// log.Println()
if skip {
d.StackPointer = stackPointerBackup
switch basicOpcode {
case IfBitSet, IfClear, IfEqual, IfNotEqual, IfGreaterThan, IfAbove, IfLessThan, IfUnder:
d.ExecuteInstruction( /* skip */ true)
}
return
}
switch basicOpcode {
case BasicReserved:
return
case Set:
d.set(pb, a)
case Add:
d.add(pb, b, a)
case Subtract:
d.subtract(pb, b, a)
case Multiply:
d.multiply(pb, b, a)
case MultiplySigned:
d.multiplySigned(pb, b, a)
case Divide:
d.divide(pb, b, a)
case DivideSigned:
d.divideSigned(pb, b, a)
case Modulo:
d.set(pb, b%a)
// TODO(robertsdionne): case ModuloSigned:
case BinaryAnd:
d.set(pb, b&a)
case BinaryOr:
d.set(pb, b|a)
case BinaryExclusiveOr:
d.set(pb, b^a)
case ShiftRight:
d.shiftRight(pb, b, a)
// TODO(robertsdionne): case ArithmeticShiftRight:
case ShiftLeft:
d.shiftLeft(pb, b, a)
case IfBitSet:
d.skipInstructionIf((a & b) == 0)
case IfClear:
d.skipInstructionIf((a & b) != 0)
case IfEqual:
d.skipInstructionIf(b != a)
case IfNotEqual:
d.skipInstructionIf(b == a)
case IfGreaterThan:
d.skipInstructionIf(b <= a)
case IfAbove:
d.skipInstructionIf(int16(b) <= int16(a))
case IfLessThan:
d.skipInstructionIf(b >= a)
case IfUnder:
d.skipInstructionIf(int16(b) >= int16(a))
// TODO(robertsdionne): case AddWithCarry:
// TODO(robertsdionne): case SubtractWithCarry:
case SetThenIncrement:
d.setThenIncrement(pb, a)
case SetThenDecrement:
d.setThenDecrement(pb, b)
}
} else if specialOpcode != SpecialReserved {
operandA := (instruction & SpecialValueMaskA) >> SpecialValueShiftA
assignable := specialOpcode == InterruptAddressGet || specialOpcode == HardwareNumberConnected
pa, a := d.getOperandAddressOrLiteral(operandA, assignable)
if pa != nil {
a = *pa
}
if skip {
d.StackPointer = stackPointerBackup
return
}
switch specialOpcode {
case SpecialReserved:
return
case JumpSubRoutine:
d.jumpSubRoutine(a)
case InterruptTrigger:
d.Interrupt(a)
case InterruptAddressGet:
d.set(pa, d.InterruptAddress)
case InterruptAddressSet:
d.InterruptAddress = a
case ReturnFromInterrupt:
d.returnFromInterrupt()
case InterruptAddToQueue:
d.QueueInterrupts = a > 0
case HardwareNumberConnected:
d.set(pa, uint16(len(d.Hardware)))
case HardwareQuery:
d.hardwareQuery(a)
case HardwareInterrupt:
d.hardwareInterrupt(a)
}
} else {
debugOpcode := DebugOpcode((instruction & DebugOpcodeMask) >> DebugOpcodeShift)
switch debugOpcode {
case Alert:
length := d.Memory[0xf000]
switch {
case length > 0:
alert := string(utf16.Decode(d.Memory[0xf001 : 0xf001+length]))
log.Println(alert)
default:
log.Println("alert")
}
case DumpState:
log.Println(*d)
}
}
}
func (d *DCPU) skipInstructionIf(condition bool) {
if condition {
d.ExecuteInstruction( /* skip */ true)
}
}
func (d *DCPU) Interrupt(message uint16) {
switch {
case d.QueueInterrupts:
d.InterruptQueue = append(d.InterruptQueue, message)
default:
d.maybeTriggerInterrupt(message)
}
}
func (d *DCPU) maybeTriggerInterrupt(message uint16) {
if d.InterruptAddress == 0 {
return
}
d.QueueInterrupts = true
d.StackPointer--
d.Memory[d.StackPointer] = d.ProgramCounter
d.StackPointer--
d.Memory[d.StackPointer] = d.RegisterA
d.ProgramCounter = d.InterruptAddress
d.RegisterA = message
}