analysis.go 1.9 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
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,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
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/>.
F
Felix Lange 已提交
16

O
obscuren 已提交
17 18
package vm

O
obscuren 已提交
19 20
import (
	"math/big"
O
obscuren 已提交
21

F
Felix Lange 已提交
22
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
23 24
)

F
Felix Lange 已提交
25 26 27
// destinations stores one map per contract (keyed by hash of code).
// The maps contain an entry for each location of a JUMPDEST
// instruction.
28
type destinations map[common.Hash][]byte
O
obscuren 已提交
29

F
Felix Lange 已提交
30 31
// has checks whether code has a JUMPDEST at dest.
func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {
32
	// PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
F
Felix Lange 已提交
33
	// Don't bother checking for JUMPDEST in that case.
34 35
	udest := dest.Uint64()
	if dest.BitLen() >= 63 || udest >= uint64(len(code)) {
F
Felix Lange 已提交
36 37
		return false
	}
38

F
Felix Lange 已提交
39 40 41 42 43
	m, analysed := d[codehash]
	if !analysed {
		m = jumpdests(code)
		d[codehash] = m
	}
44
	return (m[udest/8] & (1 << (udest % 8))) != 0
O
obscuren 已提交
45 46
}

F
Felix Lange 已提交
47 48
// jumpdests creates a map that contains an entry for each
// PC location that is a JUMPDEST instruction.
49 50
func jumpdests(code []byte) []byte {
	m := make([]byte, len(code)/8+1)
51
	for pc := uint64(0); pc < uint64(len(code)); pc++ {
52 53 54 55
		op := OpCode(code[pc])
		if op == JUMPDEST {
			m[pc/8] |= 1 << (pc % 8)
		} else if op >= PUSH1 && op <= PUSH32 {
56
			a := uint64(op) - uint64(PUSH1) + 1
O
obscuren 已提交
57 58 59
			pc += a
		}
	}
F
Felix Lange 已提交
60
	return m
O
obscuren 已提交
61
}