github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/core/vm/analysis.go (about)

     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  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     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  // GNU Lesser General Public License for more details.
    13  //
    14  // 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  
    17  package vm
    18  
    19  import (
    20  	"math/big"
    21  
    22  	"github.com/ethereumproject/go-ethereum/common"
    23  )
    24  
    25  // destinations stores one map per contract (keyed by hash of code).
    26  // The maps contain an entry for each location of a JUMPDEST
    27  // instruction.
    28  type destinations map[common.Hash][]byte
    29  
    30  // has checks whether code has a JUMPDEST at dest.
    31  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.
    33  	// Don't bother checking for JUMPDEST in that case.
    34  	udest := dest.Uint64()
    35  	if dest.BitLen() >= 63 || udest >= uint64(len(code)) {
    36  		return false
    37  	}
    38  
    39  	m, analysed := d[codehash]
    40  	if !analysed {
    41  		m = jumpdests(code)
    42  		d[codehash] = m
    43  	}
    44  	return (m[udest/8] & (1 << (udest % 8))) != 0
    45  }
    46  
    47  // jumpdests creates a map that contains an entry for each
    48  // PC location that is a JUMPDEST instruction.
    49  func jumpdests(code []byte) []byte {
    50  	m := make([]byte, len(code)/8+1)
    51  	for pc := uint64(0); pc < uint64(len(code)); pc++ {
    52  		op := OpCode(code[pc])
    53  		if op == JUMPDEST {
    54  			m[pc/8] |= 1 << (pc % 8)
    55  		} else if op >= PUSH1 && op <= PUSH32 {
    56  			a := uint64(op) - uint64(PUSH1) + 1
    57  			pc += a
    58  		}
    59  	}
    60  	return m
    61  }