github.com/ontio/ontology@v1.14.4/vm/evm/common.go (about) 1 // Copyright (C) 2021 The Ontology Authors 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 18 package evm 19 20 import ( 21 "math" 22 23 "github.com/ethereum/go-ethereum/common" 24 "github.com/holiman/uint256" 25 ) 26 27 // calcMemSize64 calculates the required memory size, and returns 28 // the size and whether the result overflowed uint64 29 func calcMemSize64(off, l *uint256.Int) (uint64, bool) { 30 if !l.IsUint64() { 31 return 0, true 32 } 33 return calcMemSize64WithUint(off, l.Uint64()) 34 } 35 36 // calcMemSize64WithUint calculates the required memory size, and returns 37 // the size and whether the result overflowed uint64 38 // Identical to calcMemSize64, but length is a uint64 39 func calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) { 40 // if length is zero, memsize is always zero, regardless of offset 41 if length64 == 0 { 42 return 0, false 43 } 44 // Check that offset doesn't overflow 45 offset64, overflow := off.Uint64WithOverflow() 46 if overflow { 47 return 0, true 48 } 49 val := offset64 + length64 50 // if value < either of it's parts, then it overflowed 51 return val, val < offset64 52 } 53 54 // getData returns a slice from the data based on the start and size and pads 55 // up to size with zero's. This function is overflow safe. 56 func getData(data []byte, start uint64, size uint64) []byte { 57 length := uint64(len(data)) 58 if start > length { 59 start = length 60 } 61 end := start + size 62 if end > length { 63 end = length 64 } 65 return common.RightPadBytes(data[start:end], int(size)) 66 } 67 68 // toWordSize returns the ceiled word size required for memory expansion. 69 func toWordSize(size uint64) uint64 { 70 if size > math.MaxUint64-31 { 71 return math.MaxUint64/32 + 1 72 } 73 74 return (size + 31) / 32 75 } 76 77 func allZero(b []byte) bool { 78 for _, byte := range b { 79 if byte != 0 { 80 return false 81 } 82 } 83 return true 84 }