analysis.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // bitvec is a bit vector which maps bytes in a program.
  18. // An unset bit means the byte is an opcode, a set bit means
  19. // it's data (i.e. argument of PUSHxx).
  20. type bitvec []byte
  21. func (bits *bitvec) set(pos uint64) {
  22. (*bits)[pos/8] |= 0x80 >> (pos % 8)
  23. }
  24. func (bits *bitvec) set8(pos uint64) {
  25. (*bits)[pos/8] |= 0xFF >> (pos % 8)
  26. (*bits)[pos/8+1] |= ^(0xFF >> (pos % 8))
  27. }
  28. // codeSegment checks if the position is in a code segment.
  29. func (bits *bitvec) codeSegment(pos uint64) bool {
  30. return ((*bits)[pos/8] & (0x80 >> (pos % 8))) == 0
  31. }
  32. // codeBitmap collects data locations in code.
  33. func codeBitmap(code []byte) bitvec {
  34. // The bitmap is 4 bytes longer than necessary, in case the code
  35. // ends with a PUSH32, the algorithm will push zeroes onto the
  36. // bitvector outside the bounds of the actual code.
  37. bits := make(bitvec, len(code)/8+1+4)
  38. for pc := uint64(0); pc < uint64(len(code)); {
  39. op := OpCode(code[pc])
  40. if op >= PUSH1 && op <= PUSH32 {
  41. numbits := op - PUSH1 + 1
  42. pc++
  43. for ; numbits >= 8; numbits -= 8 {
  44. bits.set8(pc) // 8
  45. pc += 8
  46. }
  47. for ; numbits > 0; numbits-- {
  48. bits.set(pc)
  49. pc++
  50. }
  51. } else {
  52. pc++
  53. }
  54. }
  55. return bits
  56. }