| 1 |
package sys |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"os" |
| 6 |
"syscall" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"github.com/go-quicktest/qt" |
| 10 |
|
| 11 |
"github.com/cilium/ebpf/internal/unix" |
| 12 |
) |
| 13 |
|
| 14 |
func init() { |
| 15 |
|
| 16 |
stdin, err := unix.FcntlInt(os.Stdin.Fd(), unix.F_DUPFD_CLOEXEC, 1) |
| 17 |
if err != nil { |
| 18 |
panic(err) |
| 19 |
} |
| 20 |
|
| 21 |
old := os.Stdin |
| 22 |
os.Stdin = os.NewFile(uintptr(stdin), "stdin") |
| 23 |
old.Close() |
| 24 |
|
| 25 |
reserveFdZero() |
| 26 |
} |
| 27 |
|
| 28 |
func reserveFdZero() { |
| 29 |
fd, err := unix.Open(os.DevNull, syscall.O_RDONLY, 0) |
| 30 |
if err != nil { |
| 31 |
panic(err) |
| 32 |
} |
| 33 |
if fd != 0 { |
| 34 |
panic(errors.New("zero fd already taken")) |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
func TestFD(t *testing.T) { |
| 39 |
_, err := NewFD(-1) |
| 40 |
qt.Assert(t, qt.IsNotNil(err), qt.Commentf("invalid fd should be rejected")) |
| 41 |
|
| 42 |
fd, err := NewFD(0) |
| 43 |
qt.Assert(t, qt.IsNil(err)) |
| 44 |
qt.Assert(t, qt.Not(qt.Equals(fd.Int(), 0)), qt.Commentf("fd value should not be zero")) |
| 45 |
qt.Assert(t, qt.IsNil(fd.Close())) |
| 46 |
|
| 47 |
var stat unix.Stat_t |
| 48 |
err = unix.Fstat(0, &stat) |
| 49 |
qt.Assert(t, qt.ErrorIs(err, unix.EBADF), qt.Commentf("zero fd should be closed")) |
| 50 |
|
| 51 |
reserveFdZero() |
| 52 |
} |
| 53 |
|
| 54 |
func TestFDFile(t *testing.T) { |
| 55 |
fd := newFD(openFd(t)) |
| 56 |
file, err := fd.File("test") |
| 57 |
qt.Assert(t, qt.IsNil(err)) |
| 58 |
qt.Assert(t, qt.IsNotNil(file)) |
| 59 |
|
| 60 |
qt.Assert(t, qt.IsNil(file.Close())) |
| 61 |
|
| 62 |
_, err = fd.File("closed") |
| 63 |
qt.Assert(t, qt.ErrorIs(err, ErrClosedFd)) |
| 64 |
|
| 65 |
_, err = fd.Dup() |
| 66 |
qt.Assert(t, qt.ErrorIs(err, ErrClosedFd)) |
| 67 |
} |
| 68 |
|
| 69 |
func openFd(tb testing.TB) int { |
| 70 |
fd, err := unix.Open(os.DevNull, syscall.O_RDONLY, 0) |
| 71 |
qt.Assert(tb, qt.IsNil(err)) |
| 72 |
return fd |
| 73 |
} |