analysis.go 2.17 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16

obscuren's avatar
obscuren committed
17 18
package vm

obscuren's avatar
obscuren committed
19 20
import (
	"math/big"
obscuren's avatar
obscuren committed
21

22
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
23 24
)

25
var bigMaxUint64 = new(big.Int).SetUint64(^uint64(0))
obscuren's avatar
obscuren committed
26

27 28 29 30
// destinations stores one map per contract (keyed by hash of code).
// The maps contain an entry for each location of a JUMPDEST
// instruction.
type destinations map[common.Hash]map[uint64]struct{}
obscuren's avatar
obscuren committed
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45
// has checks whether code has a JUMPDEST at dest.
func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {
	// PC cannot go beyond len(code) and certainly can't be bigger than 64bits.
	// Don't bother checking for JUMPDEST in that case.
	if dest.Cmp(bigMaxUint64) > 0 {
		return false
	}
	m, analysed := d[codehash]
	if !analysed {
		m = jumpdests(code)
		d[codehash] = m
	}
	_, ok := m[dest.Uint64()]
	return ok
obscuren's avatar
obscuren committed
46 47
}

48 49 50 51
// jumpdests creates a map that contains an entry for each
// PC location that is a JUMPDEST instruction.
func jumpdests(code []byte) map[uint64]struct{} {
	m := make(map[uint64]struct{})
52
	for pc := uint64(0); pc < uint64(len(code)); pc++ {
obscuren's avatar
obscuren committed
53 54 55
		var op OpCode = OpCode(code[pc])
		switch op {
		case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
56
			a := uint64(op) - uint64(PUSH1) + 1
obscuren's avatar
obscuren committed
57
			pc += a
obscuren's avatar
obscuren committed
58
		case JUMPDEST:
59
			m[pc] = struct{}{}
obscuren's avatar
obscuren committed
60 61
		}
	}
62
	return m
obscuren's avatar
obscuren committed
63
}