File: fd_test.go

package info (click to toggle)
golang-github-cilium-ebpf 0.17.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,684 kB
  • sloc: ansic: 1,259; makefile: 127; python: 113; awk: 29; sh: 24
file content (69 lines) | stat: -rw-r--r-- 1,411 bytes parent folder | download
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package sys

import (
	"errors"
	"os"
	"syscall"
	"testing"

	"github.com/go-quicktest/qt"

	"github.com/cilium/ebpf/internal/unix"
)

func init() {
	// Free up fd 0 for TestFD.
	stdin, err := unix.FcntlInt(os.Stdin.Fd(), unix.F_DUPFD_CLOEXEC, 1)
	if err != nil {
		panic(err)
	}

	old := os.Stdin
	os.Stdin = os.NewFile(uintptr(stdin), "stdin")
	old.Close()

	reserveFdZero()
}

func reserveFdZero() {
	fd, err := unix.Open(os.DevNull, syscall.O_RDONLY, 0)
	if err != nil {
		panic(err)
	}
	if fd != 0 {
		panic(errors.New("zero fd already taken"))
	}
}

func TestFD(t *testing.T) {
	_, err := NewFD(-1)
	qt.Assert(t, qt.IsNotNil(err), qt.Commentf("negative fd should be rejected"))

	fd, err := NewFD(0)
	qt.Assert(t, qt.IsNil(err))
	qt.Assert(t, qt.Not(qt.Equals(fd.Int(), 0)), qt.Commentf("fd value should not be zero"))
	qt.Assert(t, qt.IsNil(fd.Close()))

	var stat unix.Stat_t
	err = unix.Fstat(0, &stat)
	qt.Assert(t, qt.ErrorIs(err, unix.EBADF), qt.Commentf("zero fd should be closed"))

	reserveFdZero()
}

func TestFDFile(t *testing.T) {
	fd := newFD(openFd(t))
	file := fd.File("test")
	qt.Assert(t, qt.IsNotNil(file))
	qt.Assert(t, qt.IsNil(file.Close()))
	qt.Assert(t, qt.IsNil(fd.File("closed")))

	_, err := fd.Dup()
	qt.Assert(t, qt.ErrorIs(err, ErrClosedFd))
}

func openFd(tb testing.TB) int {
	fd, err := unix.Open(os.DevNull, syscall.O_RDONLY, 0)
	qt.Assert(tb, qt.IsNil(err))
	return fd
}