github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/memutil/memutil_unsafe.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 memutil provides utilities for working with shared memory files. 16 package memutil 17 18 import ( 19 "reflect" 20 "unsafe" 21 22 "golang.org/x/sys/unix" 23 ) 24 25 // MapSlice is like MapFile, but returns a slice instead of a uintptr. 26 func MapSlice(addr, size, prot, flags, fd, offset uintptr) ([]byte, error) { 27 addr, err := MapFile(addr, size, prot, flags, fd, offset) 28 if err != nil { 29 return nil, err 30 } 31 var slice []byte 32 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&slice)) 33 hdr.Data = addr 34 hdr.Len = int(size) 35 hdr.Cap = int(size) 36 return slice, nil 37 } 38 39 // UnmapSlice unmaps a mapping returned by MapSlice. 40 func UnmapSlice(slice []byte) error { 41 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&slice)) 42 _, _, err := unix.RawSyscall6(unix.SYS_MUNMAP, uintptr(unsafe.Pointer(hdr.Data)), uintptr(hdr.Cap), 0, 0, 0, 0) 43 return err 44 }