mremap_size.go raw
1 //go:build linux && !arm64 && !arm && !js
2 // +build linux,!arm64,!arm,!js
3
4 /*
5 * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 package z
10
11 import (
12 "fmt"
13 "reflect"
14 "unsafe"
15
16 "golang.org/x/sys/unix"
17 )
18
19 // mremap is a Linux-specific system call to remap pages in memory. This can be used in place of munmap + mmap.
20 func mremap(data []byte, size int) ([]byte, error) {
21 //nolint:lll
22 // taken from <https://github.com/torvalds/linux/blob/f8394f232b1eab649ce2df5c5f15b0e528c92091/include/uapi/linux/mman.h#L8>
23 const MREMAP_MAYMOVE = 0x1
24
25 header := (*reflect.SliceHeader)(unsafe.Pointer(&data))
26 mmapAddr, mmapSize, errno := unix.Syscall6(
27 unix.SYS_MREMAP,
28 header.Data,
29 uintptr(header.Len),
30 uintptr(size),
31 uintptr(MREMAP_MAYMOVE),
32 0,
33 0,
34 )
35 if errno != 0 {
36 return nil, errno
37 }
38 if mmapSize != uintptr(size) {
39 return nil, fmt.Errorf("mremap size mismatch: requested: %d got: %d", size, mmapSize)
40 }
41
42 header.Data = mmapAddr
43 header.Cap = size
44 header.Len = size
45 return data, nil
46 }
47