File: memfd.go

package info (click to toggle)
incus 6.0.5-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,092 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (48 lines) | stat: -rw-r--r-- 884 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package linux

import (
	"os"

	"golang.org/x/sys/unix"

	"github.com/lxc/incus/v6/shared/revert"
)

// CreateMemfd creates a new memfd for the provided byte slice.
func CreateMemfd(content []byte) (*os.File, error) {
	reverter := revert.New()
	defer reverter.Fail()

	// Create the memfd.
	fd, err := unix.MemfdCreate("memfd", unix.MFD_CLOEXEC)
	if err != nil {
		return nil, err
	}

	reverter.Add(func() { _ = unix.Close(fd) })

	// Set its size.
	err = unix.Ftruncate(fd, int64(len(content)))
	if err != nil {
		return nil, err
	}

	// Prepare the storage.
	data, err := unix.Mmap(fd, 0, len(content), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
	if err != nil {
		return nil, err
	}

	// Write the content.
	copy(data, content)

	// Cleanup.
	err = unix.Munmap(data)
	if err != nil {
		return nil, err
	}

	reverter.Success()

	return os.NewFile(uintptr(fd), "memfd"), nil
}