-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathExecutionEngine.cs
More file actions
323 lines (291 loc) · 10.4 KB
/
ExecutionEngine.cs
File metadata and controls
323 lines (291 loc) · 10.4 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
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
// Copyright (C) 2015-2026 The Neo Project.
//
// ExecutionEngine.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Neo.VM;
/// <summary>
/// Represents the VM used to execute the script.
/// </summary>
public class ExecutionEngine : IDisposable
{
private VMState _state = VMState.BREAK;
internal bool isJumping = false;
public JumpTable JumpTable { get; }
/// <summary>
/// Restrictions on the VM.
/// </summary>
public ExecutionEngineLimits Limits { get; }
/// <summary>
/// Used for reference counting of objects in the VM.
/// </summary>
public IReferenceCounter ReferenceCounter { get; }
/// <summary>
/// The invocation stack of the VM.
/// </summary>
public Stack<ExecutionContext> InvocationStack { get; } = new();
/// <summary>
/// The top frame of the invocation stack.
/// </summary>
public ExecutionContext? CurrentContext { get; private set; }
/// <summary>
/// The bottom frame of the invocation stack.
/// </summary>
public ExecutionContext? EntryContext { get; private set; }
/// <summary>
/// The stack to store the return values.
/// </summary>
public EvaluationStack ResultStack { get; }
/// <summary>
/// The VM object representing the uncaught exception.
/// </summary>
public StackItem? UncaughtException { get; internal set; }
/// <summary>
/// The current state of the VM.
/// </summary>
public VMState State
{
get
{
return _state;
}
protected internal set
{
if (_state != value)
{
_state = value;
OnStateChanged();
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionEngine"/> class.
/// </summary>
/// <param name="jumpTable">The jump table to be used.</param>
public ExecutionEngine(JumpTable? jumpTable = null)
: this(jumpTable, new ReferenceCounter(), ExecutionEngineLimits.Default) { }
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionEngine"/> class
/// with the specified <see cref="VM.IReferenceCounter"/> and <see cref="ExecutionEngineLimits"/>.
/// </summary>
/// <param name="jumpTable">The jump table to be used.</param>
/// <param name="referenceCounter">The reference counter to be used.</param>
/// <param name="limits">Restrictions on the VM.</param>
protected ExecutionEngine(JumpTable? jumpTable, IReferenceCounter referenceCounter, ExecutionEngineLimits limits)
{
JumpTable = jumpTable ?? JumpTable.Default;
Limits = limits;
ReferenceCounter = referenceCounter;
ResultStack = new(referenceCounter);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
InvocationStack.Clear();
}
}
/// <summary>
/// Start execution of the VM.
/// </summary>
/// <returns></returns>
public virtual VMState Execute()
{
if (State == VMState.BREAK)
State = VMState.NONE;
while (State != VMState.HALT && State != VMState.FAULT)
ExecuteNext();
return State;
}
/// <summary>
/// Execute the next instruction.
/// </summary>
protected internal void ExecuteNext()
{
if (InvocationStack.Count == 0)
{
State = VMState.HALT;
}
else
{
try
{
ExecutionContext context = CurrentContext!;
Instruction? currentInstruction = context.CurrentInstruction;
Instruction instruction = currentInstruction ?? Instruction.RET;
PreExecuteInstruction(instruction);
#if VMPERF
Console.WriteLine("op:["
+ this.CurrentContext.InstructionPointer.ToString("X04")
+ "]"
+ this.CurrentContext.CurrentInstruction?.OpCode
+ " "
+ this.CurrentContext.EvaluationStack);
#endif
try
{
JumpTable[instruction.OpCode](this, instruction);
}
catch (CatchableException ex) when (Limits.CatchEngineExceptions)
{
JumpTable.ExecuteThrow(this, ex.Message);
}
PostExecuteInstruction(instruction);
if (!isJumping && currentInstruction != null)
context.InstructionPointer += instruction.Size;
isJumping = false;
}
catch (Exception e)
{
OnFault(e);
}
}
}
/// <summary>
/// Loads the specified context into the invocation stack.
/// </summary>
/// <param name="context">The context to load.</param>
public virtual void LoadContext(ExecutionContext context)
{
if (InvocationStack.Count >= Limits.MaxInvocationStackSize)
throw new InvalidOperationException($"MaxInvocationStackSize exceed: {InvocationStack.Count}");
InvocationStack.Push(context);
EntryContext ??= context;
CurrentContext = context;
}
/// <summary>
/// Called when a context is unloaded.
/// </summary>
/// <param name="context">The context being unloaded.</param>
internal protected virtual void ContextUnloaded(ExecutionContext context)
{
if (InvocationStack.Count == 0)
{
CurrentContext = null;
EntryContext = null;
}
else
{
CurrentContext = InvocationStack.Peek();
}
if (context.StaticFields != null && context.StaticFields != CurrentContext?.StaticFields)
{
context.StaticFields.ClearReferences();
}
context.LocalVariables?.ClearReferences();
context.Arguments?.ClearReferences();
}
/// <summary>
/// Create a new context with the specified script without loading.
/// </summary>
/// <param name="script">The script used to create the context.</param>
/// <param name="rvcount">The number of values that the context should return when it is unloaded.</param>
/// <param name="initialPosition">The pointer indicating the current instruction.</param>
/// <returns>The created context.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected ExecutionContext CreateContext(Script script, int rvcount, int initialPosition)
{
return new ExecutionContext(script, rvcount, ReferenceCounter)
{
InstructionPointer = initialPosition
};
}
/// <summary>
/// Create a new context with the specified script and load it.
/// </summary>
/// <param name="script">The script used to create the context.</param>
/// <param name="rvcount">The number of values that the context should return when it is unloaded.</param>
/// <param name="initialPosition">The pointer indicating the current instruction.</param>
/// <returns>The created context.</returns>
public ExecutionContext LoadScript(Script script, int rvcount = -1, int initialPosition = 0)
{
var context = CreateContext(script, rvcount, initialPosition);
LoadContext(context);
return context;
}
/// <summary>
/// Called when an exception that cannot be caught by the VM is thrown.
/// </summary>
/// <param name="ex">The exception that caused the <see cref="VMState.FAULT"/> state.</param>
protected virtual void OnFault(Exception ex)
{
State = VMState.FAULT;
#if VMPERF
if (ex != null)
{
Console.Error.WriteLine(ex);
}
#endif
}
/// <summary>
/// Called when the state of the VM changed.
/// </summary>
protected virtual void OnStateChanged()
{
}
/// <summary>
/// Returns the item at the specified index from the top of the current stack without removing it.
/// </summary>
/// <param name="index">The index of the object from the top of the stack.</param>
/// <returns>The item at the specified index.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public StackItem Peek(int index = 0)
{
return CurrentContext!.EvaluationStack.Peek(index);
}
/// <summary>
/// Removes and returns the item at the top of the current stack.
/// </summary>
/// <returns>The item removed from the top of the stack.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public StackItem Pop()
{
return CurrentContext!.EvaluationStack.Pop();
}
/// <summary>
/// Removes and returns the item at the top of the current stack and convert it to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <returns>The item removed from the top of the stack.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Pop<T>() where T : StackItem
{
return CurrentContext!.EvaluationStack.Pop<T>();
}
/// <summary>
/// Called after an instruction is executed.
/// </summary>
protected virtual void PostExecuteInstruction(Instruction instruction)
{
if (ReferenceCounter.Count < Limits.MaxStackSize) return;
if (ReferenceCounter.CheckZeroReferred() > Limits.MaxStackSize)
throw new InvalidOperationException($"MaxStackSize exceed: {ReferenceCounter.Count}/{Limits.MaxStackSize}");
}
/// <summary>
/// Called before an instruction is executed.
/// </summary>
protected virtual void PreExecuteInstruction(Instruction instruction) { }
/// <summary>
/// Pushes an item onto the top of the current stack.
/// </summary>
/// <param name="item">The item to be pushed.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Push(StackItem item)
{
CurrentContext!.EvaluationStack.Push(item);
}
}