-
Notifications
You must be signed in to change notification settings - Fork 7
/
zmachine.go
1495 lines (1210 loc) · 36 KB
/
zmachine.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
type ZHeader struct {
version uint8
hiMemBase uint16
ip uint16
dictAddress uint32
objTableAddress uint32
globalVarAddress uint32
staticMemAddress uint32
abbreviationTable uint32
}
const (
OPERAND_LARGE = 0x0
OPERAND_SMALL = 0x1
OPERAND_VARIABLE = 0x2
OPERAND_OMITTED = 0x3
FORM_SHORT = 0x0
FORM_LONG = 0x1
FORM_VARIABLE = 0x2
MAX_STACK = 1024
MAX_OBJECT = 256
OBJECT_ENTRY_SIZE = 9
OBJECT_PARENT_INDEX = 4
OBJECT_SIBLING_INDEX = 5
OBJECT_CHILD_INDEX = 6
NULL_OBJECT_INDEX = 0
DICT_NOT_FOUND = 0
)
type ZStack struct {
stack []uint16
top int
localFrame int
}
func NewStack() *ZStack {
s := new(ZStack)
s.stack = make([]uint16, MAX_STACK)
s.top = MAX_STACK
s.localFrame = s.top
return s
}
type ZMachine struct {
ip uint32
header ZHeader
buf []uint8
stack *ZStack
localFrame uint16
done bool
}
type ZFunction func(*ZMachine, []uint16, uint16)
type ZFunction1Op func(*ZMachine, uint16)
type ZFunction0Op func(*ZMachine)
func DebugPrintf(format string, v ...interface{}) {
//fmt.Printf(format, v...)
}
var alphabets = []string{ "abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
" \n0123456789.,!?_#'\"/\\-:()" }
func (s *ZStack) Push(value uint16) {
if s.top == 0 {
panic("Stack overflow")
}
s.top--
s.stack[s.top] = value
}
func (s *ZStack) Pop() uint16 {
if s.top == MAX_STACK {
panic("Trying to pop from empty stack")
}
retValue := s.stack[s.top]
s.top++
return retValue
}
func (s *ZStack) Reset(newTop int) {
if newTop > MAX_STACK || newTop < 0 {
panic("Invalid stack top value")
}
s.top = newTop
}
func (s *ZStack) GetTopItem() uint16 {
return s.stack[s.top]
}
func (s *ZStack) SaveFrame() {
s.Push(uint16(s.localFrame))
s.localFrame = s.top
}
// Returns caller address (where to return to)
func (s *ZStack) RestoreFrame() uint32 {
// Discard local frame
s.top = s.localFrame
// Restore previous frame
s.localFrame = int(s.Pop())
retLo := s.Pop()
retHi := s.Pop()
return (uint32(retHi) << 16) | uint32(retLo)
}
func (s *ZStack) ValidateLocalVarIndex(localVarIndex int) {
if (localVarIndex > 0xF) {
panic("Local var index out of bounds")
}
if (s.localFrame < localVarIndex) {
panic("Stack underflow")
}
}
func (s *ZStack) GetLocalVar(localVarIndex int) uint16 {
s.ValidateLocalVarIndex(localVarIndex)
stackIndex := (s.localFrame - localVarIndex) - 1
r := s.stack[stackIndex]
return r
}
func (s *ZStack) SetLocalVar(localVarIndex int, value uint16) {
s.ValidateLocalVarIndex(localVarIndex)
stackIndex := (s.localFrame - localVarIndex) - 1
s.stack[stackIndex] = value
}
func (s *ZStack) Dump() {
DebugPrintf("Top = %d, local frame = %d\n", s.top, s.localFrame)
for i := MAX_STACK - 1; i >= s.top; i-- {
if i == s.localFrame {
DebugPrintf("0x%X: 0x%X <------ local frame\n", i, s.stack[i])
} else {
DebugPrintf("0x%X: 0x%X\n", i, s.stack[i])
}
}
}
func GetUint16(buf []byte, offset uint32) uint16 {
return (uint16(buf[offset]) << 8) | (uint16)(buf[offset + 1])
}
func GetUint32(buf []byte, offset uint32) uint32 {
return (uint32(buf[offset]) << 24) | (uint32(buf[offset + 1]) << 16) | (uint32(buf[offset + 2]) << 8) | uint32(buf[offset + 3])
}
func (h *ZHeader) read(buf []byte) {
h.version = buf[0]
h.hiMemBase = GetUint16(buf, 4)
h.ip = GetUint16(buf, 6)
h.dictAddress = uint32(GetUint16(buf, 0x8))
h.objTableAddress = uint32(GetUint16(buf, 0xA))
h.globalVarAddress = uint32(GetUint16(buf, 0xC))
h.staticMemAddress = uint32(GetUint16(buf, 0xE))
h.abbreviationTable = uint32(GetUint16(buf, 0x18))
DebugPrintf("End of dyn mem: 0x%X\n", h.staticMemAddress)
DebugPrintf("Global vars: 0x%X\n", h.globalVarAddress)
}
// Doesn't modify IP
func (zm *ZMachine) PeekByte() uint8 {
return zm.buf[zm.ip]
}
// Reads & moves to the next one (advances IP)
func (zm *ZMachine) ReadByte() uint8 {
zm.ip++
return zm.buf[zm.ip - 1]
}
// Reads 2 bytes and advances IP
func (zm *ZMachine) ReadUint16() uint16 {
retVal := zm.GetUint16(zm.ip)
zm.ip += 2
return retVal
}
// We can only write to dynamic memory
func (zm *ZMachine) IsSafeToWrite(address uint32) bool {
return address < zm.header.staticMemAddress
}
func (zm *ZMachine) GetUint16(offset uint32) uint16 {
return (uint16(zm.buf[offset]) << 8) | (uint16)(zm.buf[offset + 1])
}
func (zm *ZMachine) SetUint16(offset uint32, v uint16) {
zm.buf[offset] = uint8(v >> 8)
zm.buf[offset + 1] = uint8(v & 0xFF)
}
// " Given a packed address P, the formula to obtain the corresponding byte address B is:
// 2P Versions 1, 2 and 3"
func PackedAddress(a uint32) uint32 {
return a * 2
}
func (zm *ZMachine) ReadGlobal(x uint8) uint16 {
if x < 0x10 {
panic("Invalid global variable")
}
addr := PackedAddress(uint32(x) - 0x10)
ret := zm.GetUint16(zm.header.globalVarAddress + addr)
return ret
}
func (zm *ZMachine) SetGlobal(x uint16, v uint16) {
if x < 0x10 {
panic("Invalid global variable")
}
addr := PackedAddress(uint32(x) - 0x10)
zm.SetUint16(zm.header.globalVarAddress + addr, v)
}
func (zm *ZMachine) GetObjectEntryAddress(objectIndex uint16) uint32 {
if objectIndex > MAX_OBJECT || objectIndex == 0 {
fmt.Printf("Index: %d\n", objectIndex)
panic("Invalid object index")
}
// Convert from 1-based (0 = NULL = no object) to 0-based
objectIndex--
// Skip default props
objectEntryAddress := zm.header.objTableAddress + (31 * 2) + uint32(objectIndex * OBJECT_ENTRY_SIZE)
return uint32(objectEntryAddress)
}
func (zm *ZMachine) SetObjectProperty(objectIndex uint16, propertyId uint16, value uint16) {
objectEntryAddress := uint32(zm.GetObjectEntryAddress(objectIndex))
propertiesAddress := GetUint16(zm.buf, objectEntryAddress + 7)
nameLength := uint16(zm.buf[propertiesAddress]) * 2 // in 2-byte words
// Find property
found := false
propData := uint32(propertiesAddress + nameLength + 1)
for !found {
propSize := zm.buf[propData]
if propSize == 0 {
break
}
propData++
propNo := uint16(propSize & 0x1F)
// Props are sorted
if propNo < propertyId {
break
}
numBytes := (propSize >> 5) + 1
if propNo == propertyId {
found = true
if numBytes == 1 {
zm.buf[propData] = uint8(value & 0xFF)
} else if numBytes == 2 {
zm.SetUint16(propData, value)
} else {
panic("SetObjectProperty only supports 1/2 byte properties")
}
}
propData += uint32(numBytes)
}
if !found {
panic("Property not found!")
}
}
func (zm *ZMachine) GetFirstPropertyAddress(objectIndex uint16) uint16 {
objectEntryAddress := uint32(zm.GetObjectEntryAddress(objectIndex))
propertiesAddress := GetUint16(zm.buf, objectEntryAddress + 7)
nameLength := uint16(zm.buf[propertiesAddress]) * 2 // in 2-byte words
propData := propertiesAddress + nameLength + 1
return propData
}
// Returns prop data address, number of property bytes
// (0 if not found)
func (zm *ZMachine) GetObjectPropertyInfo(objectIndex uint16, propertyId uint16) (uint16, uint16) {
propData := zm.GetFirstPropertyAddress(objectIndex)
// Find property
found := false
for !found {
propSize := zm.buf[propData]
if propSize == 0 {
break
}
propData++
propNo := uint16(propSize & 0x1F)
// Props are sorted
if propNo < propertyId {
break
}
numBytes := uint16(propSize >> 5) + 1
if propNo == propertyId {
return propData, numBytes
}
propData += uint16(numBytes)
}
return uint16(0), uint16(0)
}
func (zm *ZMachine) GetObjectPropertyAddress(objectIndex uint16, propertyId uint16) uint16 {
address, _ := zm.GetObjectPropertyInfo(objectIndex, propertyId)
return address
}
func (zm *ZMachine) GetNextObjectProperty(objectIndex uint16, propertyId uint16) uint16 {
nextPropSize := uint8(0)
// " if called with zero, it gives the first property number present."
if propertyId == 0 {
propData := zm.GetFirstPropertyAddress(objectIndex)
nextPropSize = zm.buf[propData]
} else {
propData, numBytes := zm.GetObjectPropertyInfo(objectIndex, propertyId)
if propData == 0 {
panic("GetNextObjectProperty - non existent property")
}
nextPropSize = zm.buf[propData + numBytes]
}
// "zero, indicating the end of the property list"
if nextPropSize == 0 {
return 0
} else {
return uint16(nextPropSize & 0x1F)
}
}
func (zm *ZMachine) GetObjectProperty(objectIndex uint16, propertyId uint16) uint16 {
propData, numBytes := zm.GetObjectPropertyInfo(objectIndex, propertyId)
result := uint16(0)
if propData == 0 {
// Get a default one
result = zm.GetPropertyDefault(propertyId)
DebugPrintf("Default prop %d = 0x%X\n", propertyId, result)
} else {
if numBytes == 1 {
result = uint16(zm.buf[propData])
} else if numBytes == 2 {
result = GetUint16(zm.buf, uint32(propData))
} else {
panic("GetObjectProperty only supports 1/2 byte properties")
}
}
return result
}
// True if set
func (zm *ZMachine) TestObjectAttr(objectIndex uint16, attribute uint16) bool {
if attribute > 31 {
panic("Attribute out of bounds")
}
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
attribs := GetUint32(zm.buf, objectEntryAddress)
// 0: top bit
// 31: bottom bit
mask := uint32(1 << (31 - attribute))
return (attribs & mask) != 0
}
func (zm *ZMachine) SetObjectAttr(objectIndex uint16, attribute uint16) {
if attribute > 31 {
panic("Attribute out of bounds")
}
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
byteIndex := uint32(attribute >> 3)
shift := 7 - (attribute & 0x7)
zm.buf[objectEntryAddress + byteIndex] |= (1 << shift)
}
func (zm *ZMachine) ClearObjectAttr(objectIndex uint16, attribute uint16) {
if attribute > 31 {
panic("Attribute out of bounds")
}
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
byteIndex := uint32(attribute >> 3)
shift := 7 - (attribute & 0x7)
zm.buf[objectEntryAddress + byteIndex] &= ^(1 << shift)
}
func (zm *ZMachine) IsDirectParent(childIndex uint16, parentIndex uint16) bool {
return zm.GetParentObject(childIndex) == parentIndex
}
func (zm *ZMachine) GetParentObject(objectIndex uint16) uint16 {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
return uint16(zm.buf[objectEntryAddress + OBJECT_PARENT_INDEX])
}
// Unlink object from its parent
func (zm *ZMachine) UnlinkObject(objectIndex uint16) {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
currentParentIndex := uint16(zm.buf[objectEntryAddress + OBJECT_PARENT_INDEX])
// Unlink from current parent first
if currentParentIndex != NULL_OBJECT_INDEX {
curParentAddress := zm.GetObjectEntryAddress(currentParentIndex)
// If we're the first child -> move to sibling
if uint16(zm.buf[curParentAddress + OBJECT_CHILD_INDEX]) == objectIndex {
zm.buf[curParentAddress + OBJECT_CHILD_INDEX] = zm.buf[objectEntryAddress + OBJECT_SIBLING_INDEX]
} else {
childIter := uint16(zm.buf[curParentAddress + OBJECT_CHILD_INDEX])
prevChild := uint16(NULL_OBJECT_INDEX)
for childIter != objectIndex && childIter != NULL_OBJECT_INDEX {
prevChild = childIter
childIter = zm.GetSibling(childIter)
}
// Sanity checks
if childIter == NULL_OBJECT_INDEX {
panic("Object not found on parent children list")
}
if prevChild == NULL_OBJECT_INDEX {
panic("Corrupted data")
}
prevSiblingAddress := zm.GetObjectEntryAddress(prevChild)
sibling := zm.buf[objectEntryAddress + OBJECT_SIBLING_INDEX]
zm.buf[prevSiblingAddress + OBJECT_SIBLING_INDEX] = sibling
}
zm.buf[objectEntryAddress + OBJECT_PARENT_INDEX] = NULL_OBJECT_INDEX;
}
}
func (zm *ZMachine) ReparentObject(objectIndex uint16, newParentIndex uint16) {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
currentParentIndex := uint16(zm.buf[objectEntryAddress + OBJECT_PARENT_INDEX])
if currentParentIndex == newParentIndex {
return
}
zm.UnlinkObject(objectIndex)
// Make the first child of our new parent
newParentAddress := zm.GetObjectEntryAddress(newParentIndex)
zm.buf[objectEntryAddress + OBJECT_SIBLING_INDEX] = zm.buf[newParentAddress + OBJECT_CHILD_INDEX]
zm.buf[newParentAddress + OBJECT_CHILD_INDEX] = uint8(objectIndex)
zm.buf[objectEntryAddress + OBJECT_PARENT_INDEX] = uint8(newParentIndex)
}
func (zm *ZMachine) GetFirstChild(objectIndex uint16) uint16 {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
return uint16(zm.buf[objectEntryAddress + OBJECT_CHILD_INDEX])
}
func (zm *ZMachine) GetSibling(objectIndex uint16) uint16 {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
return uint16(zm.buf[objectEntryAddress + OBJECT_SIBLING_INDEX])
}
func (zm *ZMachine) PrintObjectName(objectIndex uint16) {
objectEntryAddress := zm.GetObjectEntryAddress(objectIndex)
propertiesAddress := uint32(GetUint16(zm.buf, objectEntryAddress + 7))
zm.DecodeZString(propertiesAddress + 1)
}
func ZCall(zm *ZMachine, args []uint16, numArgs uint16) {
if numArgs == 0 {
panic("Data corruption, call instruction requires at least 1 argument")
}
// Save return address
zm.stack.Push(uint16(zm.ip >> 16) & 0xFFFF)
zm.stack.Push(uint16(zm.ip & 0xFFFF))
functionAddress := PackedAddress(uint32(args[0]))
DebugPrintf("Jumping to 0x%X [0x%X]\n", functionAddress, args[0])
zm.ip = functionAddress
// Save local frame (think EBP)
zm.stack.SaveFrame()
if zm.ip == 0 {
ZReturnFalse(zm)
return
}
// Local function variables on the stack
numLocals := zm.ReadByte()
// "When a routine is called, its local variables are created with initial values taken from the routine header.
// Next, the arguments are written into the local variables (argument 1 into local 1 and so on)."
numArgs-- // first argument is function address
for i := 0; i < int(numLocals); i++ {
localVar := zm.ReadUint16()
if numArgs > 0 {
localVar = args[i + 1]
numArgs--
}
zm.stack.Push(localVar)
}
}
// storew array word-index value
func ZStoreW(zm *ZMachine, args []uint16, numArgs uint16) {
address := uint32(args[0] + args[1] * 2)
if !zm.IsSafeToWrite(address) {
panic("Access violation")
}
zm.SetUint16(address, args[2])
}
func ZStoreB(zm *ZMachine, args []uint16, numArgs uint16) {
address := uint32(args[0] + args[1])
if !zm.IsSafeToWrite(address) {
panic("Access violation")
}
zm.buf[address] = uint8(args[2])
}
func ZPutProp(zm *ZMachine, args []uint16, numArgs uint16) {
zm.SetObjectProperty(args[0], args[1], args[2])
}
func ZRead(zm *ZMachine, args []uint16, numArgs uint16) {
textAddress := args[0]
maxChars := uint16(zm.buf[textAddress])
if maxChars == 0 {
panic("Invalid max chars")
}
maxChars--
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.ToLower(input)
input = strings.Trim(input, "\r\n")
copy(zm.buf[textAddress + 1:textAddress + maxChars], input)
zm.buf[textAddress + uint16(len(input)) + 1] = 0
var words []string
var wordStarts []uint16
var stringBuffer bytes.Buffer
prevWordStart := uint16(1)
for i := uint16(1); zm.buf[textAddress + i] != 0; i++ {
ch := zm.buf[textAddress + i]
if ch == ' ' {
if prevWordStart < 0xFFFF {
words = append(words, stringBuffer.String())
wordStarts = append(wordStarts, prevWordStart)
stringBuffer.Truncate(0)
}
prevWordStart = 0xFFFF
} else {
stringBuffer.WriteByte(ch)
if prevWordStart == 0xFFFF {
prevWordStart = i
}
}
}
// Last word
if prevWordStart < 0xFFFF {
words = append(words, stringBuffer.String())
wordStarts = append(wordStarts, prevWordStart)
}
// TODO: include other separators, not only spaces
parseAddress := uint32(args[1])
maxTokens := zm.buf[parseAddress]
//DebugPrintf("Max tokens: %d\n", maxTokens)
parseAddress++
numTokens := uint8(len(words))
if numTokens > maxTokens {
numTokens = maxTokens
}
zm.buf[parseAddress] = numTokens
parseAddress++
// "Each block consists of the byte address of the word in the dictionary, if it is in the dictionary, or 0 if it isn't;
// followed by a byte giving the number of letters in the word; and finally a byte giving the position in the text-buffer
// of the first letter of the word.
for i, w := range(words) {
if uint8(i) >= maxTokens {
break
}
DebugPrintf("w = %s, %d\n", w, wordStarts[i])
dictionaryAddress := zm.FindInDictionary(w)
DebugPrintf("Dictionary address: 0x%X\n", dictionaryAddress)
zm.SetUint16(parseAddress, dictionaryAddress)
zm.buf[parseAddress + 2] = uint8(len(w))
zm.buf[parseAddress + 3] = uint8(wordStarts[i])
parseAddress += 4
}
}
func ZPrintChar(zm *ZMachine, args []uint16, numArgs uint16) {
ch := args[0]
PrintZChar(ch)
}
func ZPrintNum(zm *ZMachine, args []uint16, numArgs uint16) {
fmt.Printf("%d", int16(args[0]))
}
// If range is positive, returns a uniformly random number between 1 and range.
// If range is negative, the random number generator is seeded to that value and the return value is 0.
// Most interpreters consider giving 0 as range illegal (because they attempt a division with remainder by the range),
/// but correct behaviour is to reseed the generator in as random a way as the interpreter can (e.g. by using the time
// in milliseconds).
func ZRandom(zm *ZMachine, args []uint16, numArgs uint16) {
randRange := int16(args[0])
if randRange > 0 {
r := rand.Int31n(int32(randRange)) // [0, n]
zm.StoreResult(uint16(r + 1))
} else if randRange < 0 {
rand.Seed(int64(randRange * -1))
zm.StoreResult(0)
} else {
rand.Seed(time.Now().Unix())
zm.StoreResult(0)
}
}
func ZPush(zm *ZMachine, args []uint16, numArgs uint16) {
zm.stack.Push(args[0])
}
func ZPull(zm *ZMachine, args []uint16, numArgs uint16) {
r := zm.stack.Pop()
DebugPrintf("Popped %d 0x%X %d %d\n", r, zm.ip, numArgs, args[0])
zm.StoreAtLocation(args[0], r)
}
func ZNOP_VAR(zm *ZMachine, args []uint16, numArgs uint16) {
fmt.Printf("IP=0x%X\n", zm.ip)
panic("NOP VAR")
}
func ZNOP(zm *ZMachine, args []uint16) {
fmt.Printf("IP=0x%X\n", zm.ip)
panic("NOP 2OP")
}
func GenericBranch(zm *ZMachine, conditionSatisfied bool) {
branchInfo := zm.ReadByte()
// "If bit 7 of the first byte is 0, a branch occurs when the condition was false; if 1, then branch is on true"
branchOnFalse := (branchInfo >> 7) == 0
var jumpAddress int32
var branchOffset int32
// 0 = return false, 1 = return true, 2 = standard jump
returnFromCurrent := int32(2)
// "If bit 6 is set, then the branch occupies 1 byte only, and the "offset" is in the range 0 to 63, given in the bottom 6 bits"
if (branchInfo & (1 << 6)) != 0 {
branchOffset = int32(branchInfo & 0x3F)
// "An offset of 0 means "return false from the current routine", and 1 means "return true from the current routine".
if branchOffset <= 1 {
returnFromCurrent = branchOffset
}
} else {
// If bit 6 is clear, then the offset is a signed 14-bit number given in bits 0 to 5 of the first
// byte followed by all 8 of the second.
secondPart := zm.ReadByte()
firstPart := uint16(branchInfo & 0x3F)
// Propagate sign bit (2 complement)
if (firstPart & 0x20) != 0 {
firstPart |= (1 << 6) | (1 << 7)
}
branchOffset16 := int16(firstPart << 8) | int16(secondPart)
branchOffset = int32(branchOffset16)
DebugPrintf("Offset: 0x%X [%d]\n", branchOffset, branchOffset)
}
ip := int32(zm.ip)
// "Otherwise, a branch moves execution to the instruction at address
// Address after branch data + Offset - 2."
jumpAddress = ip + int32(branchOffset) - 2
DebugPrintf("Jump address = 0x%X\n", jumpAddress)
doJump := (conditionSatisfied != branchOnFalse)
DebugPrintf("Do jump: %t\n", doJump)
if doJump {
if returnFromCurrent != 2 {
ZRet(zm, uint16(returnFromCurrent))
} else {
zm.ip = uint32(jumpAddress)
}
}
}
func ZJumpEqual(zm *ZMachine, args []uint16, numArgs uint16) {
conditionSatisfied := (args[0] == args[1] ||
(numArgs > 2 && args[0] == args[2]) || (numArgs > 3 && args[0] == args[3]))
GenericBranch(zm, conditionSatisfied)
}
func ZJumpLess(zm *ZMachine, args []uint16, numArgs uint16) {
conditionSatisfied := int16(args[0]) < int16(args[1])
GenericBranch(zm, conditionSatisfied)
}
func ZJumpGreater(zm *ZMachine, args []uint16, numArgs uint16) {
conditionSatisfied := int16(args[0]) > int16(args[1])
GenericBranch(zm, conditionSatisfied)
}
func ZAdd(zm *ZMachine, args []uint16, numArgs uint16) {
r := int16(args[0]) + int16(args[1])
zm.StoreResult(uint16(r))
}
func ZSub(zm *ZMachine, args[] uint16, numArgs uint16) {
r := int16(args[0]) - int16(args[1])
zm.StoreResult(uint16(r))
}
func ZMul(zm *ZMachine, args[] uint16, numArgs uint16) {
r := int16(args[0]) * int16(args[1])
zm.StoreResult(uint16(r))
}
func ZDiv(zm *ZMachine, args[] uint16, numArgs uint16) {
if args[1] == 0 {
panic("Division by zero")
}
r := int16(args[0]) / int16(args[1])
zm.StoreResult(uint16(r))
}
func ZMod(zm *ZMachine, args[] uint16, numArgs uint16) {
if args[1] == 0 {
panic("Division by zero (mod)")
}
r := int16(args[0]) % int16(args[1])
zm.StoreResult(uint16(r))
}
func ZStore(zm *ZMachine, args[] uint16, numArgs uint16) {
DebugPrintf("%d - 0x%X\n", args[0], args[1])
zm.StoreAtLocation(args[0], args[1])
}
func ZTestAttr(zm *ZMachine, args[] uint16, numArgs uint16) {
GenericBranch(zm, zm.TestObjectAttr(args[0], args[1]))
}
func ZOr(zm *ZMachine, args[] uint16, numArgs uint16) {
zm.StoreResult(args[0] | args[1])
}
func ZAnd(zm *ZMachine, args[] uint16, numArgs uint16) {
zm.StoreResult(args[0] & args[1])
}
func ZSetAttr(zm *ZMachine, args[] uint16, numArgs uint16) {
zm.SetObjectAttr(args[0], args[1])
}
func ZClearAttr(zm *ZMachine, args[] uint16, numArgs uint16) {
zm.ClearObjectAttr(args[0], args[1])
}
func ZLoadB(zm *ZMachine, args[] uint16, numArgs uint16) {
address := args[0] + args[1]
value := zm.buf[address]
zm.StoreResult(uint16(value))
}
func ZGetProp(zm *ZMachine, args[] uint16, numArgs uint16) {
prop := zm.GetObjectProperty(args[0], args[1])
zm.StoreResult(prop)
}
func ZGetPropAddr(zm *ZMachine, args[] uint16, numArgs uint16) {
addr := zm.GetObjectPropertyAddress(args[0], args[1])
zm.StoreResult(addr)
}
func ZGetNextProp(zm *ZMachine, args[] uint16, numArgs uint16) {
addr := zm.GetNextObjectProperty(args[0], args[1])
zm.StoreResult(addr)
}
// array word-index -> (result)
func ZLoadW(zm *ZMachine, args[] uint16, numArgs uint16) {
address := uint32(args[0] + (args[1] * 2))
value := GetUint16(zm.buf, address)
zm.StoreResult(value)
}
// Returns new value.
func (zm *ZMachine) AddToVar(varType uint16, value int16) uint16 {
retValue := uint16(0)
if varType == 0 {
zm.stack.stack[zm.stack.top] += uint16(value)
retValue = zm.stack.GetTopItem()
} else if varType < 0x10 {
retValue = zm.stack.GetLocalVar((int)(varType - 1))
retValue += uint16(value)
zm.stack.SetLocalVar(int(varType - 1), retValue)
} else {
retValue = zm.ReadGlobal(uint8(varType))
retValue += uint16(value)
zm.SetGlobal(varType, retValue)
}
return retValue
}
// dec_chk (variable) value ?(label)
// Decrement variable, and branch if it is now less than the given value.
func ZDecChk(zm *ZMachine, args[] uint16, numArgs uint16) {
newValue := zm.AddToVar(args[0], -1)
GenericBranch(zm, int16(newValue) < int16(args[1]))
}
// inc_chk (variable) value ?(label)
// Increment variable, and branch if now greater than value.
func ZIncChk(zm *ZMachine, args[] uint16, numArgs uint16) {
newValue := zm.AddToVar(args[0], 1)
GenericBranch(zm, int16(newValue) > int16(args[1]))
}
// test bitmap flags ?(label)
// Jump if all of the flags in bitmap are set (i.e. if bitmap & flags == flags).
func ZTest(zm *ZMachine, args[] uint16, numArgs uint16) {
bitmap := args[0]
flags := args[1]
GenericBranch(zm, (bitmap & flags) == flags)
}
// jin obj1 obj2 ?(label)
// Jump if object a is a direct child of b, i.e., if parent of a is b.
func ZJin(zm *ZMachine, args[] uint16, numArgs uint16) {
GenericBranch(zm, zm.IsDirectParent(args[0], args[1]))
}
func ZInsertObj(zm *ZMachine, args[] uint16, numArgs uint16) {
zm.ReparentObject(args[0], args[1])
}
func ZJumpZero(zm *ZMachine, arg uint16) {
GenericBranch(zm, arg == 0)
}
// get_sibling object -> (result) ?(label)
// Get next object in tree, branching if this exists, i.e. is not 0.
func ZGetSibling(zm *ZMachine, arg uint16) {
sibling := zm.GetSibling(arg)
zm.StoreResult(sibling)
GenericBranch(zm, sibling != NULL_OBJECT_INDEX)
}
// get_child object -> (result) ?(label)
// Get first object contained in given object, branching if this exists, i.e. is not nothing (i.e., is not 0).
func ZGetChild(zm *ZMachine, arg uint16) {
childIndex := zm.GetFirstChild(arg)
zm.StoreResult(childIndex)
GenericBranch(zm, childIndex != NULL_OBJECT_INDEX)
}
func ZGetParent(zm *ZMachine, arg uint16) {
parent := zm.GetParentObject(arg)
zm.StoreResult(parent)
}
func ZGetPropLen(zm *ZMachine, arg uint16) {
if arg == 0 {
zm.StoreResult(0)
} else {
// Arg = direct address of the property block
// To get size, we need to go 1 byte back
propSize := zm.buf[arg - 1]
numBytes := (propSize >> 5) + 1
zm.StoreResult(uint16(numBytes))
}
}
// print_paddr packed-address-of-string
func ZPrintPAddr(zm *ZMachine, arg uint16) {
zm.DecodeZString(uint32(arg) * 2)
}
func ZLoad(zm *ZMachine, arg uint16) {
zm.StoreResult(arg)
}
func ZInc(zm *ZMachine, arg uint16) {
zm.AddToVar(arg, 1)
}
func ZDec(zm *ZMachine, arg uint16) {
zm.AddToVar(arg, -1)
}
func ZPrintAddr(zm *ZMachine, arg uint16) {
zm.DecodeZString(uint32(arg))
}
func ZRemoveObj(zm *ZMachine, arg uint16) {
zm.UnlinkObject(arg)
}
func ZPrintObj(zm *ZMachine, arg uint16) {
zm.PrintObjectName(arg)
}
func ZRet(zm *ZMachine, arg uint16) {
returnAddress := zm.stack.RestoreFrame()
zm.ip = returnAddress
DebugPrintf("Returning to 0x%X\n", zm.ip)
zm.StoreResult(arg)
}
// Unconditional jump
func ZJump(zm *ZMachine, arg uint16) {
jumpOffset := int16(arg)
jumpAddress := int32(zm.ip) + int32(jumpOffset) - 2
DebugPrintf("Jump address: 0x%X\n", jumpAddress)
zm.ip = uint32(jumpAddress)
}
func ZNOP1(zm *ZMachine, arg uint16) {
fmt.Printf("IP=0x%X\n", zm.ip)