analysis.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. package vm
  17. import (
  18. "math/big"
  19. "github.com/ethereum/go-ethereum/common"
  20. )
  21. // destinations stores one map per contract (keyed by hash of code).
  22. // The maps contain an entry for each location of a JUMPDEST
  23. // instruction.
  24. type destinations map[common.Hash][]byte
  25. // has checks whether code has a JUMPDEST at dest.
  26. func (d destinations) has(codehash common.Hash, code []byte, dest *big.Int) bool {
  27. // PC cannot go beyond len(code) and certainly can't be bigger than 63bits.
  28. // Don't bother checking for JUMPDEST in that case.
  29. udest := dest.Uint64()
  30. if dest.BitLen() >= 63 || udest >= uint64(len(code)) {
  31. return false
  32. }
  33. m, analysed := d[codehash]
  34. if !analysed {
  35. m = jumpdests(code)
  36. d[codehash] = m
  37. }
  38. return (m[udest/8] & (1 << (udest % 8))) != 0
  39. }
  40. // jumpdests creates a map that contains an entry for each
  41. // PC location that is a JUMPDEST instruction.
  42. func jumpdests(code []byte) []byte {
  43. m := make([]byte, len(code)/8+1)
  44. for pc := uint64(0); pc < uint64(len(code)); pc++ {
  45. op := OpCode(code[pc])
  46. if op == JUMPDEST {
  47. m[pc/8] |= 1 << (pc % 8)
  48. } else if op >= PUSH1 && op <= PUSH32 {
  49. a := uint64(op) - uint64(PUSH1) + 1
  50. pc += a
  51. }
  52. }
  53. return m
  54. }