asm.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. "fmt"
  19. "math/big"
  20. "github.com/ethereum/go-ethereum/common"
  21. )
  22. // Disassemble disassembles the byte code and returns the string
  23. // representation (human readable opcodes).
  24. func Disassemble(script []byte) (asm []string) {
  25. pc := new(big.Int)
  26. for {
  27. if pc.Cmp(big.NewInt(int64(len(script)))) >= 0 {
  28. return
  29. }
  30. // Get the memory location of pc
  31. val := script[pc.Int64()]
  32. // Get the opcode (it must be an opcode!)
  33. op := OpCode(val)
  34. asm = append(asm, fmt.Sprintf("%v", op))
  35. switch op {
  36. 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:
  37. pc.Add(pc, common.Big1)
  38. a := int64(op) - int64(PUSH1) + 1
  39. if int(pc.Int64()+a) > len(script) {
  40. return nil
  41. }
  42. data := script[pc.Int64() : pc.Int64()+a]
  43. if len(data) == 0 {
  44. data = []byte{0}
  45. }
  46. asm = append(asm, fmt.Sprintf("0x%x", data))
  47. pc.Add(pc, big.NewInt(a-1))
  48. }
  49. pc.Add(pc, common.Big1)
  50. }
  51. }