-
Notifications
You must be signed in to change notification settings - Fork 10
/
Engine.cs
1584 lines (1387 loc) · 55.9 KB
/
Engine.cs
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
/*
* Copyright © 2008, Textfyre, Inc. - All Rights Reserved
* Please read the accompanying COPYRIGHT file for licensing resstrictions.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.Serialization;
namespace FyreVM
{
/// <summary>
/// Provides data for an input line request event.
/// </summary>
public class LineWantedEventArgs : EventArgs
{
private string line;
/// <summary>
/// Gets or sets the line of input that was read, or <b>null</b> to cancel.
/// </summary>
public string Line
{
get { return line; }
set { line = value; }
}
}
/// <summary>
/// A delegate that handles the <see cref="Engine.LineWanted"/> event.
/// </summary>
/// <param name="sender">The <see cref="Engine"/> raising the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void LineWantedEventHandler(object sender, LineWantedEventArgs e);
/// <summary>
/// Provides data for an input character request event.
/// </summary>
public class KeyWantedEventArgs : EventArgs
{
private char ch;
/// <summary>
/// Gets or sets the character that was read, or '\0' to cancel.
/// </summary>
public char Char
{
get { return ch; }
set { ch = value; }
}
}
/// <summary>
/// A delegate that handles the <see cref="Engine.KeyWanted"/> event.
/// </summary>
/// <param name="sender">The <see cref="Engine"/> raising the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void KeyWantedEventHandler(object sender, KeyWantedEventArgs e);
/// <summary>
/// Provides data for an output event.
/// </summary>
public class OutputReadyEventArgs : EventArgs
{
private IDictionary<string, string> package;
/// <summary>
/// Gets or sets a dictionary containing the text that has been
/// captured on each output channel since the last output delivery.
/// </summary>
public IDictionary<string, string> Package
{
get { return package; }
set { package = value; }
}
}
/// <summary>
/// A delegate that handles the <see cref="Engine.OutputReady"/> event.
/// </summary>
/// <param name="sender">The <see cref="Engine"/> raising the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void OutputReadyEventHandler(object sender, OutputReadyEventArgs e);
/// <summary>
/// Provides data for a save or restore event.
/// </summary>
public class SaveRestoreEventArgs : EventArgs
{
private Stream stream;
/// <summary>
/// Gets or sets the stream to use for saving or restoring the game
/// state. This stream will be closed by the interpreter after the
/// save or load process finishes. (A value of <see langword="null"/>
/// indicates that the save/load process was aborted.)
/// </summary>
public Stream Stream
{
get { return stream; }
set { stream = value; }
}
}
/// <summary>
/// A delegate that handles the <see cref="Engine.SaveRequested"/> or
/// <see cref="Engine.LoadRequested"/> event.
/// </summary>
/// <param name="sender">The <see cref="Engine"/> raising the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void SaveRestoreEventHandler(object sender, SaveRestoreEventArgs e);
public class TransitionEventArgs : EventArgs
{
private string message;
public string Message { get { return message; } set { message = value; } }
}
public delegate void TransitionRequestedEventHandler(object sender, TransitionEventArgs e);
/// <summary>
/// Describes the type of Glk support offered by the interpreter.
/// </summary>
public enum GlkMode
{
/// <summary>
/// No Glk support.
/// </summary>
None,
/// <summary>
/// A minimal Glk implementation, with I/O functions mapped to the channel system.
/// </summary>
Wrapper,
}
/// <summary>
/// The main FyreVM class, which implements a modified Glulx interpreter.
/// </summary>
public partial class Engine
{
public enum VMRequestType
{
StartGame,
EnterCommand
}
/// <summary>
/// Describes the task that the interpreter is currently performing.
/// </summary>
private enum ExecutionMode
{
/// <summary>
/// We are running function code. PC points to the next instruction.
/// </summary>
Code,
/// <summary>
/// We are printing a null-terminated string (E0). PC points to the
/// next character.
/// </summary>
CString,
/// <summary>
/// We are printing a compressed string (E1). PC points to the next
/// compressed byte, and printingDigit is the bit position (0-7).
/// </summary>
CompressedString,
/// <summary>
/// We are printing a Unicode string (E2). PC points to the next
/// character.
/// </summary>
UnicodeString,
/// <summary>
/// We are printing a decimal number. PC contains the number, and
/// printingDigit is the next digit, starting at 0 (for the first
/// digit or minus sign).
/// </summary>
Number,
/// <summary>
/// We are returning control to <see cref="Engine.NestedCall"/>
/// after engine code has called a Glulx function.
/// </summary>
Return,
}
/// <summary>
/// Represents a Glulx call stub, which describes the VM's state at
/// the time of a function call or string printing task.
/// </summary>
private struct CallStub
{
/// <summary>
/// The type of storage location (for function calls) or the
/// previous task (for string printing).
/// </summary>
public uint DestType;
/// <summary>
/// The storage address (for function calls) or the digit
/// being examined (for string printing).
/// </summary>
public uint DestAddr;
/// <summary>
/// The address of the opcode or character at which to resume.
/// </summary>
public uint PC;
/// <summary>
/// The stack frame in which the function call or string printing
/// was performed.
/// </summary>
public uint FramePtr;
/// <summary>
/// Initializes a new call stub.
/// </summary>
/// <param name="destType">The stub type.</param>
/// <param name="destAddr">The storage address or printing digit.</param>
/// <param name="pc">The address of the opcode or character at which to resume.</param>
/// <param name="framePtr">The stack frame pointer.</param>
public CallStub(uint destType, uint destAddr, uint pc, uint framePtr)
{
this.DestType = destType;
this.DestAddr = destAddr;
this.PC = pc;
this.FramePtr = framePtr;
}
}
#region Glulx constants
// Header size and field offsets
public const int GLULX_HDR_SIZE = 36;
public const int GLULX_HDR_MAGIC_OFFSET = 0;
public const int GLULX_HDR_VERSION_OFFSET = 4;
public const int GLULX_HDR_RAMSTART_OFFSET = 8;
public const int GLULX_HDR_EXTSTART_OFFSET = 12;
public const int GLULX_HDR_ENDMEM_OFFSET = 16;
public const int GLULX_HDR_STACKSIZE_OFFSET = 20;
public const int GLULX_HDR_STARTFUNC_OFFSET = 24;
public const int GLULX_HDR_DECODINGTBL_OFFSET = 28;
public const int GLULX_HDR_CHECKSUM_OFFSET = 32;
// Call stub: DestType values for function calls
public const int GLULX_STUB_STORE_NULL = 0;
public const int GLULX_STUB_STORE_MEM = 1;
public const int GLULX_STUB_STORE_LOCAL = 2;
public const int GLULX_STUB_STORE_STACK = 3;
// Call stub: DestType values for string printing
public const int GLULX_STUB_RESUME_HUFFSTR = 10;
public const int GLULX_STUB_RESUME_FUNC = 11;
public const int GLULX_STUB_RESUME_NUMBER = 12;
public const int GLULX_STUB_RESUME_CSTR = 13;
public const int GLULX_STUB_RESUME_UNISTR = 14;
// FyreVM addition: DestType value for nested calls
public const int FYREVM_STUB_RESUME_NATIVE = 99;
// String decoding table: header field offsets
public const int GLULX_HUFF_TABLESIZE_OFFSET = 0;
public const int GLULX_HUFF_NODECOUNT_OFFSET = 4;
public const int GLULX_HUFF_ROOTNODE_OFFSET = 8;
// String decoding table: node types
public const int GLULX_HUFF_NODE_BRANCH = 0;
public const int GLULX_HUFF_NODE_END = 1;
public const int GLULX_HUFF_NODE_CHAR = 2;
public const int GLULX_HUFF_NODE_CSTR = 3;
public const int GLULX_HUFF_NODE_UNICHAR = 4;
public const int GLULX_HUFF_NODE_UNISTR = 5;
public const int GLULX_HUFF_NODE_INDIRECT = 8;
public const int GLULX_HUFF_NODE_DBLINDIRECT = 9;
public const int GLULX_HUFF_NODE_INDIRECT_ARGS = 10;
public const int GLULX_HUFF_NODE_DBLINDIRECT_ARGS = 11;
#endregion
private const string LATIN1_CODEPAGE = "latin1";//28591;
#region Dictionary of opcodes
private readonly Dictionary<uint, Opcode> opcodeDict = new Dictionary<uint, Opcode>();
private readonly Opcode[] quickOpcodes = new Opcode[0x80];
private void InitOpcodeDict()
{
MethodInfo[] methods = typeof(Engine).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MethodInfo mi in methods)
{
object[] attrs = mi.GetCustomAttributes(typeof(OpcodeAttribute), false);
if (attrs.Length > 0)
{
OpcodeAttribute attr = (OpcodeAttribute)(attrs[0]);
Delegate handler = Delegate.CreateDelegate(typeof(OpcodeHandler), this, mi);
opcodeDict.Add(attr.Number, new Opcode(attr, (OpcodeHandler)handler));
}
}
}
#endregion
private const uint FIRST_MAJOR_VERSION = 2;
private const uint FIRST_MINOR_VERSION = 0;
private const uint LAST_MAJOR_VERSION = 3;
private const uint LAST_MINOR_VERSION = 1;
private const int MAX_UNDO_LEVEL = 3;
// persistent machine state (written to save file)
private UlxImage image;
private byte[] stack;
private uint pc, sp, fp; // program counter, stack ptr, call-frame ptr
private HeapAllocator heap;
// transient state
private uint frameLen, localsPos; // updated along with FP
private IOSystem outputSystem;
private GlkMode glkMode = GlkMode.None;
private OutputBuffer outputBuffer;
private uint filterAddress;
private uint decodingTable;
private StrNode nativeDecodingTable;
private ExecutionMode execMode;
private byte printingDigit; // bit number for compressed strings, digit for numbers
private Random randomGenerator = new Random();
private List<MemoryStream> undoBuffers = new List<MemoryStream>();
private uint protectionStart, protectionLength; // relative to start of RAM!
private bool running;
private uint nestedResult;
private int nestingLevel;
private Veneer veneer = new Veneer();
private uint maxHeapSize;
/// <summary>
/// Initializes a new instance of the VM from a game file.
/// </summary>
/// <param name="gameFile">A stream containing the ROM and
/// initial RAM.</param>
public Engine(Stream gameFile)
{
image = new UlxImage(gameFile);
outputBuffer = new OutputBuffer();
uint version = (uint)image.ReadInt32(GLULX_HDR_VERSION_OFFSET);
uint major = version >> 16;
uint minor = (version >> 8) & 0xFF;
if (major < FIRST_MAJOR_VERSION ||
(major == FIRST_MAJOR_VERSION && minor < FIRST_MINOR_VERSION) ||
major > LAST_MAJOR_VERSION ||
(major == LAST_MAJOR_VERSION && minor > LAST_MINOR_VERSION))
throw new ArgumentException("Game version is out of the supported range");
uint stacksize = (uint)image.ReadInt32(GLULX_HDR_STACKSIZE_OFFSET);
stack = new byte[stacksize];
InitOpcodeDict();
}
/// <summary>
/// Initializes a new instance of the VM from a saved state and the
/// associated game file.
/// </summary>
/// <param name="gameFile">A stream containing the ROM and
/// initial RAM.</param>
/// <param name="saveFile">A stream containing a <see cref="Quetzal"/>
/// state that was saved by the specified game file.</param>
public Engine(Stream gameFile, Stream saveFile)
: this(gameFile)
{
LoadFromStream(saveFile);
}
/// <summary>
/// Raised when the VM wants to read a line of input. The handler may
/// return a string or indicate that input was canceled.
/// </summary>
public event LineWantedEventHandler LineWanted;
/// <summary>
/// Raised when the VM wants to read a single character of input.
/// The handler may return a character or indicate that input was
/// canceled.
/// </summary>
public event KeyWantedEventHandler KeyWanted;
/// <summary>
/// Raised when queued output is being delivered, i.e. before
/// requesting input or terminating.
/// </summary>
public event OutputReadyEventHandler OutputReady;
/// <summary>
/// Raised when the VM needs a stream to use for saving the current
/// state.
/// </summary>
public event SaveRestoreEventHandler SaveRequested;
/// <summary>
/// Raised when the VM needs a stream to use for restoring a previous
/// state.
/// </summary>
public event SaveRestoreEventHandler LoadRequested;
/// <summary>
/// Raised when the game requests a physical device transition. The host device can handle in a native manner.
/// This happens instead of fusging for a keypress.
/// </summary>
public event TransitionRequestedEventHandler TransitionRequested;
/// <summary>
/// Gets or sets a value limiting the maximum size of the Glulx heap,
/// in bytes, or zero to indicate an unlimited heap size.
/// </summary>
public uint MaxHeapSize
{
get { return maxHeapSize; }
set { maxHeapSize = value; if (heap != null) heap.MaxSize = value; }
}
/// <summary>
/// Gets or sets a value indicating what type of Glk support will be offered.
/// </summary>
public GlkMode GlkMode
{
get { return glkMode; }
set { glkMode = value; }
}
private void Push(uint value)
{
BigEndian.WriteInt32(stack, sp, value);
sp += 4;
}
private void WriteToStack(uint position, uint value)
{
BigEndian.WriteInt32(stack, position, value);
}
private uint Pop()
{
sp -= 4;
return BigEndian.ReadInt32(stack, sp);
}
private uint ReadFromStack(uint position)
{
return BigEndian.ReadInt32(stack, position);
}
private void PushCallStub(CallStub stub)
{
Push(stub.DestType);
Push(stub.DestAddr);
Push(stub.PC);
Push(stub.FramePtr);
}
private CallStub PopCallStub()
{
CallStub stub;
stub.FramePtr = Pop();
stub.PC = Pop();
stub.DestAddr = Pop();
stub.DestType = Pop();
return stub;
}
private static StringBuilder debugBuffer = new StringBuilder();
[Conditional("TRACEOPS")]
private static void WriteTrace(string str)
{
lock (debugBuffer)
{
debugBuffer.Append(str);
if (str.Contains("\n"))
{
string x = debugBuffer.ToString();
do
{
int pos = x.IndexOf('\n');
string line = x.Substring(0, pos).TrimEnd();
Debug.WriteLine(line);
if (pos == x.Length - 1)
x = "";
else
x = x.Substring(pos + 1);
} while (x.Contains("\n"));
//Debug.WriteLine(debugBuffer.ToString());
debugBuffer.Length = 0;
debugBuffer.Append(x);
}
}
}
/// <summary>
/// Clears the stack and initializes VM registers from values found in RAM.
/// </summary>
private void Bootstrap()
{
uint mainfunc = image.ReadInt32(GLULX_HDR_STARTFUNC_OFFSET);
decodingTable = image.ReadInt32(GLULX_HDR_DECODINGTBL_OFFSET);
sp = fp = frameLen = localsPos = 0;
outputSystem = IOSystem.Null;
execMode = ExecutionMode.Code;
EnterFunction(mainfunc);
}
/// <summary>
/// Starts the interpreter.
/// </summary>
/// <remarks>
/// This method does not return until the game finishes, either by
/// returning from the main function or with the quit opcode.
/// </remarks>
///
public Boolean _IsCurrentRestore = false;
public void Run()
{
running = true;
#if PROFILING
cycles = 0;
#endif
// initialize registers and stack
Bootstrap();
CacheDecodingTable();
// run the game
if (_IsCurrentRestore == false)
{
InterpreterLoop();
}
// send any output that may be left
DeliverOutput();
}
public void Continue()
{
running = true;
#if PROFILING
cycles = 0;
#endif
// run the game
InterpreterLoop();
// send any output that may be left
DeliverOutput();
}
private uint NestedCall(uint address)
{
return NestedCall(address, null);
}
private uint NestedCall(uint address, uint arg0)
{
funcargs1[0] = arg0;
return NestedCall(address, funcargs1);
}
private uint NestedCall(uint address, uint arg0, uint arg1)
{
funcargs2[0] = arg0;
funcargs2[1] = arg1;
return NestedCall(address, funcargs2);
}
private uint NestedCall(uint address, uint arg0, uint arg1, uint arg2)
{
funcargs3[0] = arg0;
funcargs3[1] = arg1;
funcargs3[2] = arg2;
return NestedCall(address, funcargs3);
}
/// <summary>
/// Executes a Glulx function and returns its result.
/// </summary>
/// <param name="address">The address of the function.</param>
/// <param name="args">The list of arguments, or <see langword="null"/>
/// if no arguments need to be passed in.</param>
/// <returns>The function's return value.</returns>
private uint NestedCall(uint address, params uint[] args)
{
ExecutionMode oldMode = execMode;
byte oldDigit = printingDigit;
PerformCall(address, args, FYREVM_STUB_RESUME_NATIVE, 0);
nestingLevel++;
try
{
InterpreterLoop();
}
finally
{
nestingLevel--;
execMode = oldMode;
printingDigit = oldDigit;
}
return nestedResult;
}
/// <summary>
/// Runs the main interpreter loop.
/// </summary>
private void InterpreterLoop()
{
try
{
const int MAX_OPERANDS = 8;
uint[] operands = new uint[MAX_OPERANDS];
uint[] resultAddrs = new uint[MAX_OPERANDS];
byte[] resultTypes = new byte[MAX_OPERANDS];
while (running)
{
switch (execMode)
{
case ExecutionMode.Code:
// decode opcode number
uint opnum = image.ReadByte(pc);
if (opnum >= 0xC0)
{
opnum = image.ReadInt32(pc) - 0xC0000000;
pc += 4;
}
else if (opnum >= 0x80)
{
opnum = (uint)(image.ReadInt16(pc) - 0x8000);
pc += 2;
}
else
{
pc++;
}
// look up opcode info
Opcode opcode;
try
{
opcode = opcodeDict[opnum];
WriteTrace("[" + opcode.ToString());
}
catch (KeyNotFoundException)
{
throw new VMException(string.Format("Unrecognized opcode {0:X}h", opnum));
}
// decode load-operands
uint opcount = (uint)(opcode.Attr.LoadArgs + opcode.Attr.StoreArgs);
if (opcode.Attr.Rule == OpcodeRule.DelayedStore)
opcount++;
else if (opcode.Attr.Rule == OpcodeRule.Catch)
opcount += 2;
uint operandPos = pc + (opcount + 1) / 2;
for (int i = 0; i < opcode.Attr.LoadArgs; i++)
{
byte type;
if (i % 2 == 0)
{
type = (byte)(image.ReadByte(pc) & 0xF);
}
else
{
type = (byte)((image.ReadByte(pc) >> 4) & 0xF);
pc++;
}
WriteTrace(" ");
operands[i] = DecodeLoadOperand(opcode, type, ref operandPos);
}
uint storePos = pc;
// decode store-operands
for (int i = 0; i < opcode.Attr.StoreArgs; i++)
{
byte type;
if ((opcode.Attr.LoadArgs + i) % 2 == 0)
{
type = (byte)(image.ReadByte(pc) & 0xF);
}
else
{
type = (byte)((image.ReadByte(pc) >> 4) & 0xF);
pc++;
}
resultTypes[i] = type;
WriteTrace(" -> ");
resultAddrs[i] = DecodeStoreOperand(opcode, type, ref operandPos);
}
if (opcode.Attr.Rule == OpcodeRule.DelayedStore ||
opcode.Attr.Rule == OpcodeRule.Catch)
{
// decode delayed store operand
byte type;
if ((opcode.Attr.LoadArgs + opcode.Attr.StoreArgs) % 2 == 0)
{
type = (byte)(image.ReadByte(pc) & 0xF);
}
else
{
type = (byte)((image.ReadByte(pc) >> 4) & 0xF);
pc++;
}
WriteTrace(" -> ");
DecodeDelayedStoreOperand(type, ref operandPos,
operands, opcode.Attr.LoadArgs + opcode.Attr.StoreArgs);
}
if (opcode.Attr.Rule == OpcodeRule.Catch)
{
// decode final load operand for @catch
byte type;
if ((opcode.Attr.LoadArgs + opcode.Attr.StoreArgs + 1) % 2 == 0)
{
type = (byte)(image.ReadByte(pc) & 0xF);
}
else
{
type = (byte)((image.ReadByte(pc) >> 4) & 0xF);
pc++;
}
WriteTrace(" ?");
operands[opcode.Attr.LoadArgs + opcode.Attr.StoreArgs + 2] =
DecodeLoadOperand(opcode, type, ref operandPos);
}
WriteTrace("]\r\n");
// call opcode implementation
pc = operandPos; // after the last operand
opcode.Handler(operands);
// store results
for (int i = 0; i < opcode.Attr.StoreArgs; i++)
StoreResult(opcode.Attr.Rule, resultTypes[i], resultAddrs[i],
operands[opcode.Attr.LoadArgs + i]);
break;
case ExecutionMode.CString:
NextCStringChar();
break;
case ExecutionMode.UnicodeString:
NextUniStringChar();
break;
case ExecutionMode.Number:
NextDigit();
break;
case ExecutionMode.CompressedString:
if (nativeDecodingTable != null)
nativeDecodingTable.HandleNextChar(this);
else
NextCompressedChar();
break;
case ExecutionMode.Return:
return;
}
#if PROFILING
cycles++;
#endif
}
}
catch (Exception ex)
{
string s = ex.Message;
throw;
}
}
private uint DecodeLoadOperand(Opcode opcode, byte type, ref uint operandPos)
{
uint address, value;
switch (type)
{
case 0:
WriteTrace("zero");
return 0;
case 1:
value = (uint)(sbyte)image.ReadByte(operandPos++);
WriteTrace("byte_" + value.ToString());
return value;
case 2:
operandPos += 2;
value = (uint)(short)image.ReadInt16(operandPos - 2);
WriteTrace("short_" + value.ToString());
return value;
case 3:
operandPos += 4;
value = image.ReadInt32(operandPos - 4);
WriteTrace("int_" + value.ToString());
return value;
// case 4: unused
case 5:
address = image.ReadByte(operandPos++);
WriteTrace("ptr");
goto LoadIndirect;
case 6:
address = image.ReadInt16(operandPos);
operandPos += 2;
WriteTrace("ptr");
goto LoadIndirect;
case 7:
address = image.ReadInt32(operandPos);
operandPos += 4;
WriteTrace("ptr");
LoadIndirect:
WriteTrace("_" + address.ToString() + "(");
switch (opcode.Attr.Rule)
{
case OpcodeRule.Indirect8Bit:
value = image.ReadByte(address);
break;
case OpcodeRule.Indirect16Bit:
value = image.ReadInt16(address);
break;
default:
value = image.ReadInt32(address);
break;
}
WriteTrace(value.ToString() + ")");
return value;
case 8:
if (sp <= fp + frameLen)
throw new VMException("Stack underflow");
value = Pop();
WriteTrace("sp(" + value.ToString() + ")");
return value;
case 9:
address = image.ReadByte(operandPos++);
goto LoadLocal;
case 10:
address = image.ReadInt16(operandPos);
operandPos += 2;
goto LoadLocal;
case 11:
address = image.ReadInt32(operandPos);
operandPos += 4;
LoadLocal:
WriteTrace("local_" + address.ToString() + "(");
address += fp + localsPos;
switch (opcode.Attr.Rule)
{
case OpcodeRule.Indirect8Bit:
if (address >= fp + frameLen)
throw new VMException("Reading outside local storage bounds");
else
value = stack[address];
break;
case OpcodeRule.Indirect16Bit:
if (address + 1 >= fp + frameLen)
throw new VMException("Reading outside local storage bounds");
else
value = BigEndian.ReadInt16(stack, address);
break;
default:
if (address + 3 >= fp + frameLen)
throw new VMException("Reading outside local storage bounds");
else
value = ReadFromStack(address);
break;
}
WriteTrace(value.ToString() + ")");
return value;
// case 12: unused
case 13:
address = image.RamStart + image.ReadByte(operandPos++);
WriteTrace("ram");
goto LoadIndirect;
case 14:
address = image.RamStart + image.ReadInt16(operandPos);
operandPos += 2;
WriteTrace("ram");
goto LoadIndirect;
case 15:
address = image.RamStart + image.ReadInt32(operandPos);
operandPos += 4;
WriteTrace("ram");
goto LoadIndirect;
default:
throw new ArgumentException("Invalid operand type");
}
}
private uint DecodeStoreOperand(Opcode opcode, byte type, ref uint operandPos)
{
uint address;
switch (type)
{
case 0:
// discard result
WriteTrace("discard");
return 0;
// case 1..4: unused
case 5:
address = image.ReadByte(operandPos++);
WriteTrace("ptr_" + address.ToString());
break;
case 6:
address = image.ReadInt16(operandPos);
operandPos += 2;
WriteTrace("ptr_" + address.ToString());
break;
case 7:
address = image.ReadInt32(operandPos);
operandPos += 4;
WriteTrace("ptr_" + address.ToString());
break;
// case 8: push onto stack
case 8:
// push onto stack
WriteTrace("sp");
return 0;
case 9:
address = image.ReadByte(operandPos++);
WriteTrace("local_" + address.ToString());
break;
case 10:
address = image.ReadInt16(operandPos);
operandPos += 2;
WriteTrace("local_" + address.ToString());
break;
case 11:
address = image.ReadInt32(operandPos);
operandPos += 4;
WriteTrace("local_" + address.ToString());
break;
// case 12: unused
case 13:
address = image.RamStart + image.ReadByte(operandPos++);
WriteTrace("ram_" + (address - image.RamStart).ToString());
break;
case 14:
address = image.RamStart + image.ReadInt16(operandPos);
operandPos += 2;
WriteTrace("ram_" + (address - image.RamStart).ToString());
break;
case 15:
address = image.RamStart + image.ReadInt32(operandPos);
operandPos += 4;
WriteTrace("ram_" + (address - image.RamStart).ToString());
break;
default:
throw new ArgumentException("Invalid operand type");
}
return address;
}
private void StoreResult(OpcodeRule rule, byte type, uint address, uint value)
{
switch (type)