github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/fs/offset.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package fs 16 17 import ( 18 "math" 19 20 "github.com/SagerNet/gvisor/pkg/hostarch" 21 ) 22 23 // OffsetPageEnd returns the file offset rounded up to the nearest 24 // page boundary. OffsetPageEnd panics if rounding up causes overflow, 25 // which shouldn't be possible given that offset is an int64. 26 func OffsetPageEnd(offset int64) uint64 { 27 end, ok := hostarch.Addr(offset).RoundUp() 28 if !ok { 29 panic("impossible overflow") 30 } 31 return uint64(end) 32 } 33 34 // ReadEndOffset returns an exclusive end offset for a read operation 35 // so that the read does not overflow an int64 nor size. 36 // 37 // Parameters: 38 // - offset: the starting offset of the read. 39 // - length: the number of bytes to read. 40 // - size: the size of the file. 41 // 42 // Postconditions: The returned offset is >= offset. 43 func ReadEndOffset(offset int64, length int64, size int64) int64 { 44 if offset >= size { 45 return offset 46 } 47 end := offset + length 48 // Don't overflow. 49 if end < offset || end > size { 50 end = size 51 } 52 return end 53 } 54 55 // WriteEndOffset returns an exclusive end offset for a write operation 56 // so that the write does not overflow an int64. 57 // 58 // Parameters: 59 // - offset: the starting offset of the write. 60 // - length: the number of bytes to write. 61 // 62 // Postconditions: The returned offset is >= offset. 63 func WriteEndOffset(offset int64, length int64) int64 { 64 return ReadEndOffset(offset, length, math.MaxInt64) 65 }