-
Notifications
You must be signed in to change notification settings - Fork 506
/
state.go
443 lines (340 loc) · 7.12 KB
/
state.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
package evm
import (
"errors"
"math/big"
"strings"
"sync"
"github.com/0xPolygon/polygon-edge/chain"
"github.com/0xPolygon/polygon-edge/helper/common"
"github.com/0xPolygon/polygon-edge/helper/hex"
"github.com/0xPolygon/polygon-edge/state/runtime"
"github.com/0xPolygon/polygon-edge/types"
)
var statePool = sync.Pool{
New: func() interface{} {
return new(state)
},
}
func acquireState() *state {
aquiredState, ok := statePool.Get().(*state)
if !ok {
return nil
}
return aquiredState
}
func releaseState(s *state) {
s.reset()
statePool.Put(s)
}
const stackSize = 1024
var (
errOutOfGas = runtime.ErrOutOfGas
errStackUnderflow = runtime.ErrStackUnderflow
errStackOverflow = runtime.ErrStackOverflow
errRevert = runtime.ErrExecutionReverted
errGasUintOverflow = errors.New("gas uint64 overflow")
errWriteProtection = errors.New("write protection")
errInvalidJump = errors.New("invalid jump destination")
errOpCodeNotFound = errors.New("opcode not found")
errReturnDataOutOfBounds = errors.New("return data out of bounds")
)
// Instructions is the code of instructions
type state struct {
ip int
code []byte
tmp []byte
host runtime.Host
msg *runtime.Contract // change with msg
config *chain.ForksInTime
// memory
memory []byte
lastGasCost uint64
// stack
stack []*big.Int
sp int
// remove later
evm *EVM
err error
stop bool
gas uint64
currentConsumedGas uint64
// bitvec bitvec
bitmap bitmap
returnData []byte
ret []byte
}
func (c *state) reset() {
c.sp = 0
c.ip = 0
c.gas = 0
c.currentConsumedGas = 0
c.lastGasCost = 0
c.stop = false
c.err = nil
// reset bitmap
c.bitmap.reset()
// reset memory
for i := range c.memory {
c.memory[i] = 0
}
c.stack = c.stack[:0]
c.tmp = c.tmp[:0]
c.ret = c.ret[:0]
c.code = c.code[:0]
// c.returnData = c.returnData[:0]
c.memory = c.memory[:0]
}
func (c *state) validJumpdest(dest *big.Int) bool {
udest := dest.Uint64()
if dest.BitLen() >= 63 || udest >= uint64(len(c.code)) {
return false
}
return c.bitmap.isSet(udest)
}
func (c *state) Halt() {
c.stop = true
}
func (c *state) exit(err error) {
if err == nil {
panic("cannot stop with none")
}
c.stop = true
c.err = err
}
func (c *state) push(val *big.Int) {
c.push1().Set(val)
}
func (c *state) push1() *big.Int {
if len(c.stack) > c.sp {
c.sp++
return c.stack[c.sp-1]
}
v := big.NewInt(0)
c.stack = append(c.stack, v)
c.sp++
return v
}
func (c *state) stackAtLeast(n int) bool {
return c.sp >= n
}
func (c *state) popHash() types.Hash {
return types.BytesToHash(c.pop().Bytes())
}
func (c *state) popAddr() (types.Address, bool) {
b := c.pop()
if b == nil {
return types.Address{}, false
}
return types.BytesToAddress(b.Bytes()), true
}
func (c *state) stackSize() int {
return c.sp
}
func (c *state) top() *big.Int {
if c.sp == 0 {
return nil
}
return c.stack[c.sp-1]
}
func (c *state) pop() *big.Int {
if c.sp == 0 {
return nil
}
o := c.stack[c.sp-1]
c.sp--
return o
}
func (c *state) peekAt(n int) *big.Int {
return c.stack[c.sp-n]
}
func (c *state) swap(n int) {
c.stack[c.sp-1], c.stack[c.sp-n-1] = c.stack[c.sp-n-1], c.stack[c.sp-1]
}
func (c *state) consumeGas(gas uint64) bool {
c.currentConsumedGas += gas
if c.gas < gas {
c.exit(errOutOfGas)
return false
}
c.gas -= gas
return true
}
func (c *state) resetReturnData() {
c.returnData = c.returnData[:0]
}
// Run executes the virtual machine
func (c *state) Run() ([]byte, error) {
var (
vmerr error
op OpCode
ok bool
)
for !c.stop {
op, ok = c.CurrentOpCode()
gasCopy, ipCopy := c.gas, uint64(c.ip)
c.captureState(int(op))
if !ok {
c.Halt()
break
}
inst := dispatchTable[op]
if inst.inst == nil {
c.exit(errOpCodeNotFound)
c.captureExecutionError(op.String(), c.ip, gasCopy, 0)
break
}
// check if the depth of the stack is enough for the instruction
if c.sp < inst.stack {
c.exit(errStackUnderflow)
c.captureExecutionError(op.String(), c.ip, gasCopy, inst.gas)
break
}
// consume the gas of the instruction
if !c.consumeGas(inst.gas) {
c.exit(errOutOfGas)
c.captureExecutionError(op.String(), c.ip, gasCopy, inst.gas)
break
}
// execute the instruction
inst.inst(c)
c.captureSuccessfulExecution(op.String(), ipCopy, gasCopy, gasCopy-c.gas)
// check if stack size exceeds the max size
if c.sp > stackSize {
c.exit(errStackOverflow)
break
}
c.ip++
}
if err := c.err; err != nil {
vmerr = err
}
return c.ret, vmerr
}
func (c *state) inStaticCall() bool {
return c.msg.Static
}
func bigToHash(b *big.Int) types.Hash {
return types.BytesToHash(b.Bytes())
}
func (c *state) Len() int {
return len(c.memory)
}
// allocateMemory allocates memory to enable accessing in the range of [offset, offset+size]
// throws error if the given offset and size are negative
// consumes gas if memory needs to be expanded
func (c *state) allocateMemory(offset, size *big.Int) bool {
if !offset.IsUint64() || !size.IsUint64() {
c.exit(errReturnDataOutOfBounds)
return false
}
if size.Sign() == 0 {
return true
}
o := offset.Uint64()
s := size.Uint64()
if o > 0xffffffffe0 || s > 0xffffffffe0 {
c.exit(errReturnDataOutOfBounds)
return false
}
if newSize, currentSize := o+s, uint64(len(c.memory)); currentSize < newSize {
w := (newSize + 31) / 32
newCost := 3*w + w*w/512
cost := newCost - c.lastGasCost
c.lastGasCost = newCost
if !c.consumeGas(cost) {
c.exit(errOutOfGas)
return false
}
// resize the memory
c.memory = common.ExtendByteSlice(c.memory, int(w*32))
}
return true
}
func (c *state) get2(dst []byte, offset, length *big.Int) ([]byte, bool) {
if length.Sign() == 0 {
return nil, true
}
if !c.allocateMemory(offset, length) {
return nil, false
}
o := offset.Uint64()
l := length.Uint64()
dst = append(dst, c.memory[o:o+l]...)
return dst, true
}
func (c *state) Show() string {
str := []string{}
for i := 0; i < len(c.memory); i += 16 {
j := i + 16
if j > len(c.memory) {
j = len(c.memory)
}
str = append(str, hex.EncodeToHex(c.memory[i:j]))
}
return strings.Join(str, "\n")
}
func (c *state) CurrentOpCode() (OpCode, bool) {
if codeSize := len(c.code); c.ip >= codeSize {
return STOP, false
}
return OpCode(c.code[c.ip]), true
}
func (c *state) captureState(opCode int) {
tracer := c.host.GetTracer()
if tracer == nil {
return
}
tracer.CaptureState(
c.memory,
c.stack,
opCode,
c.msg.Address,
c.sp,
c.host,
c,
)
}
func (c *state) captureSuccessfulExecution(
opCode string,
ip uint64,
gas uint64,
consumedGas uint64,
) {
tracer := c.host.GetTracer()
if tracer == nil {
return
}
tracer.ExecuteState(
c.msg.Address,
ip,
opCode,
gas,
consumedGas,
c.returnData,
c.msg.Depth,
c.err,
c.host,
)
}
func (c *state) captureExecutionError(
opCode string,
ip int,
gas uint64,
consumedGas uint64,
) {
tracer := c.host.GetTracer()
if tracer == nil {
return
}
tracer.ExecuteState(
c.msg.Address,
uint64(ip),
opCode,
gas,
consumedGas,
c.returnData,
c.msg.Depth,
c.err,
c.host,
)
}