Skip to content

Commit cd57d5c

Browse files
gcolvinholiman
andauthored
core/vm: EIP-2315, JUMPSUB for the EVM (#20619)
* core/vm: implement EIP 2315, subroutines for the EVM * core/vm: eip 2315 - lintfix + check jump dest validity + check ret stack size constraints logger: markdown-friendly traces, validate jumpdest, more testcase, correct opcodes * core/vm: update subroutines acc to eip: disallow walk-into * core/vm/eips: gas cost changes for subroutines * core/vm: update opcodes for EIP-2315 * core/vm: define RETURNSUB as a 'jumping' operation + review concerns Co-authored-by: Martin Holst Swende <martin@swende.se>
1 parent a35382d commit cd57d5c

15 files changed

Lines changed: 529 additions & 52 deletions

‎core/vm/contract.go‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uin
8383

8484
func (c *Contract) validJumpdest(dest *big.Int) bool {
8585
udest := dest.Uint64()
86-
// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
86+
// PC cannot go beyond len(code) and certainly can't be bigger than 63 bits.
8787
// Don't bother checking for JUMPDEST in that case.
8888
if dest.BitLen() >= 63 || udest >= uint64(len(c.Code)) {
8989
return false
@@ -92,16 +92,32 @@ func (c *Contract) validJumpdest(dest *big.Int) bool {
9292
if OpCode(c.Code[udest]) != JUMPDEST {
9393
return false
9494
}
95-
// Do we have it locally already?
96-
if c.analysis != nil {
97-
return c.analysis.codeSegment(udest)
95+
return c.isCode(udest)
96+
}
97+
98+
func (c *Contract) validJumpSubdest(udest uint64) bool {
99+
// PC cannot go beyond len(code) and certainly can't be bigger than 63 bits.
100+
// Don't bother checking for BEGINSUB in that case.
101+
if int64(udest) < 0 || udest >= uint64(len(c.Code)) {
102+
return false
103+
}
104+
// Only BEGINSUBs allowed for destinations
105+
if OpCode(c.Code[udest]) != BEGINSUB {
106+
return false
98107
}
99-
// If we have the code hash (but no analysis), we should look into the
100-
// parent analysis map and see if the analysis has been made previously
108+
return c.isCode(udest)
109+
}
110+
111+
// isCode returns true if the provided PC location is an actual opcode, as
112+
// opposed to a data-segment following a PUSHN operation.
113+
func (c *Contract) isCode(udest uint64) bool {
114+
// Do we have a contract hash already?
101115
if c.CodeHash != (common.Hash{}) {
116+
// Does parent context have the analysis?
102117
analysis, exist := c.jumpdests[c.CodeHash]
103118
if !exist {
104119
// Do the analysis and save in parent context
120+
// We do not need to store it in c.analysis
105121
analysis = codeBitmap(c.Code)
106122
c.jumpdests[c.CodeHash] = analysis
107123
}
@@ -113,7 +129,9 @@ func (c *Contract) validJumpdest(dest *big.Int) bool {
113129
// in state trie. In that case, we do an analysis, and save it locally, so
114130
// we don't have to recalculate it for every JUMP instruction in the execution
115131
// However, we don't save it within the parent context
116-
c.analysis = codeBitmap(c.Code)
132+
if c.analysis == nil {
133+
c.analysis = codeBitmap(c.Code)
134+
}
117135
return c.analysis.codeSegment(udest)
118136
}
119137

‎core/vm/eips.go‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ func EnableEIP(eipNum int, jt *JumpTable) error {
3333
enable1884(jt)
3434
case 1344:
3535
enable1344(jt)
36+
case 2315:
37+
enable2315(jt)
3638
default:
3739
return fmt.Errorf("undefined eip %d", eipNum)
3840
}
@@ -91,3 +93,34 @@ func enable2200(jt *JumpTable) {
9193
jt[SLOAD].constantGas = params.SloadGasEIP2200
9294
jt[SSTORE].dynamicGas = gasSStoreEIP2200
9395
}
96+
97+
// enable2315 applies EIP-2315 (Simple Subroutines)
98+
// - Adds opcodes that jump to and return from subroutines
99+
func enable2315(jt *JumpTable) {
100+
// New opcode
101+
jt[BEGINSUB] = operation{
102+
execute: opBeginSub,
103+
constantGas: GasQuickStep,
104+
minStack: minStack(0, 0),
105+
maxStack: maxStack(0, 0),
106+
valid: true,
107+
}
108+
// New opcode
109+
jt[JUMPSUB] = operation{
110+
execute: opJumpSub,
111+
constantGas: GasSlowStep,
112+
minStack: minStack(1, 0),
113+
maxStack: maxStack(1, 0),
114+
jumps: true,
115+
valid: true,
116+
}
117+
// New opcode
118+
jt[RETURNSUB] = operation{
119+
execute: opReturnSub,
120+
constantGas: GasFastStep,
121+
minStack: minStack(0, 0),
122+
maxStack: maxStack(0, 0),
123+
valid: true,
124+
jumps: true,
125+
}
126+
}

‎core/vm/errors.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import (
2323

2424
// List evm execution errors
2525
var (
26+
// ErrInvalidSubroutineEntry means that a BEGINSUB was reached via iteration,
27+
// as opposed to from a JUMPSUB instruction
28+
ErrInvalidSubroutineEntry = errors.New("invalid subroutine entry")
2629
ErrOutOfGas = errors.New("out of gas")
2730
ErrCodeStoreOutOfGas = errors.New("contract creation code storage out of gas")
2831
ErrDepth = errors.New("max call depth exceeded")
@@ -34,6 +37,8 @@ var (
3437
ErrWriteProtection = errors.New("write protection")
3538
ErrReturnDataOutOfBounds = errors.New("return data out of bounds")
3639
ErrGasUintOverflow = errors.New("gas uint64 overflow")
40+
ErrInvalidRetsub = errors.New("invalid retsub")
41+
ErrReturnStackExceeded = errors.New("return stack limit reached")
3742
)
3843

3944
// ErrStackUnderflow wraps an evm error when the items on the stack less

‎core/vm/gen_structlog.go‎

Lines changed: 14 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎core/vm/instructions.go‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -664,6 +664,39 @@ func opJumpdest(pc *uint64, interpreter *EVMInterpreter, callContext *callCtx) (
664664
return nil, nil
665665
}
666666

667+
func opBeginSub(pc *uint64, interpreter *EVMInterpreter, callContext *callCtx) ([]byte, error) {
668+
return nil, ErrInvalidSubroutineEntry
669+
}
670+
671+
func opJumpSub(pc *uint64, interpreter *EVMInterpreter, callContext *callCtx) ([]byte, error) {
672+
if len(callContext.rstack.data) >= 1023 {
673+
return nil, ErrReturnStackExceeded
674+
}
675+
pos := callContext.stack.pop()
676+
if !pos.IsUint64() {
677+
return nil, ErrInvalidJump
678+
}
679+
posU64 := pos.Uint64()
680+
if !callContext.contract.validJumpSubdest(posU64) {
681+
return nil, ErrInvalidJump
682+
}
683+
callContext.rstack.push(*pc)
684+
*pc = posU64 + 1
685+
interpreter.intPool.put(pos)
686+
return nil, nil
687+
}
688+
689+
func opReturnSub(pc *uint64, interpreter *EVMInterpreter, callContext *callCtx) ([]byte, error) {
690+
if len(callContext.rstack.data) == 0 {
691+
return nil, ErrInvalidRetsub
692+
}
693+
// Other than the check that the return stack is not empty, there is no
694+
// need to validate the pc from 'returns', since we only ever push valid
695+
//values onto it via jumpsub.
696+
*pc = callContext.rstack.pop() + 1
697+
return nil, nil
698+
}
699+
667700
func opPc(pc *uint64, interpreter *EVMInterpreter, callContext *callCtx) ([]byte, error) {
668701
callContext.stack.push(interpreter.intPool.get().SetUint64(*pc))
669702
return nil, nil

‎core/vm/instructions_test.go‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFu
9494
var (
9595
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
9696
stack = newstack()
97+
rstack = newReturnStack()
9798
pc = uint64(0)
9899
evmInterpreter = env.interpreter.(*EVMInterpreter)
99100
)
@@ -109,7 +110,7 @@ func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFu
109110
expected := new(big.Int).SetBytes(common.Hex2Bytes(test.Expected))
110111
stack.push(x)
111112
stack.push(y)
112-
opFn(&pc, evmInterpreter, &callCtx{nil, stack, nil})
113+
opFn(&pc, evmInterpreter, &callCtx{nil, stack, rstack, nil})
113114
actual := stack.pop()
114115

115116
if actual.Cmp(expected) != 0 {
@@ -211,10 +212,10 @@ func TestSAR(t *testing.T) {
211212
// getResult is a convenience function to generate the expected values
212213
func getResult(args []*twoOperandParams, opFn executionFunc) []TwoOperandTestcase {
213214
var (
214-
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
215-
stack = newstack()
216-
pc = uint64(0)
217-
interpreter = env.interpreter.(*EVMInterpreter)
215+
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
216+
stack, rstack = newstack(), newReturnStack()
217+
pc = uint64(0)
218+
interpreter = env.interpreter.(*EVMInterpreter)
218219
)
219220
interpreter.intPool = poolOfIntPools.get()
220221
result := make([]TwoOperandTestcase, len(args))
@@ -223,7 +224,7 @@ func getResult(args []*twoOperandParams, opFn executionFunc) []TwoOperandTestcas
223224
y := new(big.Int).SetBytes(common.Hex2Bytes(param.y))
224225
stack.push(x)
225226
stack.push(y)
226-
opFn(&pc, interpreter, &callCtx{nil, stack, nil})
227+
opFn(&pc, interpreter, &callCtx{nil, stack, rstack, nil})
227228
actual := stack.pop()
228229
result[i] = TwoOperandTestcase{param.x, param.y, fmt.Sprintf("%064x", actual)}
229230
}
@@ -263,7 +264,7 @@ func TestJsonTestcases(t *testing.T) {
263264
func opBenchmark(bench *testing.B, op executionFunc, args ...string) {
264265
var (
265266
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
266-
stack = newstack()
267+
stack, rstack = newstack(), newReturnStack()
267268
evmInterpreter = NewEVMInterpreter(env, env.vmConfig)
268269
)
269270

@@ -281,7 +282,7 @@ func opBenchmark(bench *testing.B, op executionFunc, args ...string) {
281282
a := new(big.Int).SetBytes(arg)
282283
stack.push(a)
283284
}
284-
op(&pc, evmInterpreter, &callCtx{nil, stack, nil})
285+
op(&pc, evmInterpreter, &callCtx{nil, stack, rstack, nil})
285286
stack.pop()
286287
}
287288
poolOfIntPools.put(evmInterpreter.intPool)
@@ -498,7 +499,7 @@ func BenchmarkOpIsZero(b *testing.B) {
498499
func TestOpMstore(t *testing.T) {
499500
var (
500501
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
501-
stack = newstack()
502+
stack, rstack = newstack(), newReturnStack()
502503
mem = NewMemory()
503504
evmInterpreter = NewEVMInterpreter(env, env.vmConfig)
504505
)
@@ -509,12 +510,12 @@ func TestOpMstore(t *testing.T) {
509510
pc := uint64(0)
510511
v := "abcdef00000000000000abba000000000deaf000000c0de00100000000133700"
511512
stack.pushN(new(big.Int).SetBytes(common.Hex2Bytes(v)), big.NewInt(0))
512-
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, nil})
513+
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, rstack, nil})
513514
if got := common.Bytes2Hex(mem.GetCopy(0, 32)); got != v {
514515
t.Fatalf("Mstore fail, got %v, expected %v", got, v)
515516
}
516517
stack.pushN(big.NewInt(0x1), big.NewInt(0))
517-
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, nil})
518+
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, rstack, nil})
518519
if common.Bytes2Hex(mem.GetCopy(0, 32)) != "0000000000000000000000000000000000000000000000000000000000000001" {
519520
t.Fatalf("Mstore failed to overwrite previous value")
520521
}
@@ -524,7 +525,7 @@ func TestOpMstore(t *testing.T) {
524525
func BenchmarkOpMstore(bench *testing.B) {
525526
var (
526527
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
527-
stack = newstack()
528+
stack, rstack = newstack(), newReturnStack()
528529
mem = NewMemory()
529530
evmInterpreter = NewEVMInterpreter(env, env.vmConfig)
530531
)
@@ -539,15 +540,15 @@ func BenchmarkOpMstore(bench *testing.B) {
539540
bench.ResetTimer()
540541
for i := 0; i < bench.N; i++ {
541542
stack.pushN(value, memStart)
542-
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, nil})
543+
opMstore(&pc, evmInterpreter, &callCtx{mem, stack, rstack, nil})
543544
}
544545
poolOfIntPools.put(evmInterpreter.intPool)
545546
}
546547

547548
func BenchmarkOpSHA3(bench *testing.B) {
548549
var (
549550
env = NewEVM(Context{}, nil, params.TestChainConfig, Config{})
550-
stack = newstack()
551+
stack, rstack = newstack(), newReturnStack()
551552
mem = NewMemory()
552553
evmInterpreter = NewEVMInterpreter(env, env.vmConfig)
553554
)
@@ -560,7 +561,7 @@ func BenchmarkOpSHA3(bench *testing.B) {
560561
bench.ResetTimer()
561562
for i := 0; i < bench.N; i++ {
562563
stack.pushN(big.NewInt(32), start)
563-
opSha3(&pc, evmInterpreter, &callCtx{mem, stack, nil})
564+
opSha3(&pc, evmInterpreter, &callCtx{mem, stack, rstack, nil})
564565
}
565566
poolOfIntPools.put(evmInterpreter.intPool)
566567
}

‎core/vm/interpreter.go‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ type Interpreter interface {
6767
type callCtx struct {
6868
memory *Memory
6969
stack *Stack
70+
rstack *ReturnStack
7071
contract *Contract
7172
}
7273

@@ -167,12 +168,14 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
167168
}
168169

169170
var (
170-
op OpCode // current opcode
171-
mem = NewMemory() // bound memory
172-
stack = newstack() // local stack
171+
op OpCode // current opcode
172+
mem = NewMemory() // bound memory
173+
stack = newstack() // local stack
174+
returns = newReturnStack() // local returns stack
173175
callContext = &callCtx{
174176
memory: mem,
175177
stack: stack,
178+
rstack: returns,
176179
contract: contract,
177180
}
178181
// For optimisation reason we're using uint64 as the program counter.
@@ -195,9 +198,9 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
195198
defer func() {
196199
if err != nil {
197200
if !logged {
198-
in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
201+
in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
199202
} else {
200-
in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
203+
in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
201204
}
202205
}
203206
}()
@@ -279,7 +282,7 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (
279282
}
280283

281284
if in.cfg.Debug {
282-
in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
285+
in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, returns, contract, in.evm.depth, err)
283286
logged = true
284287
}
285288

0 commit comments

Comments
 (0)