Debian Codegraph @

internal/sys/fd_other.go

raw symbols SCIP
1 //go:build !windows
2
3 package sys
4
5 import (
6 "fmt"
7 "os"
8 "runtime"
9
10 "github.com/cilium/ebpf/internal/unix"
11 )
12
13 type FD struct {
14 raw int
15 cleanup runtime.Cleanup
16 }
17
18 // NewFD wraps a raw fd with a finalizer.
19 //
20 // You must not use the raw fd after calling this function, since the underlying
21 // file descriptor number may change. This is because the BPF UAPI assumes that
22 // zero is not a valid fd value.
23 func NewFD(value int) (*FD, error) {
24 if value < 0 {
25 return nil, fmt.Errorf("invalid fd %d", value)
26 }
27
28 fd := newFD(value)
29 if value != 0 {
30 return fd, nil
31 }
32
33 dup, err := fd.Dup()
34 _ = fd.Close()
35 return dup, err
36 }
37
38 func (fd *FD) Close() error {
39 if fd.raw < 0 {
40 return nil
41 }
42
43 return unix.Close(fd.Disown())
44 }
45
46 func (fd *FD) Dup() (*FD, error) {
47 if fd.raw < 0 {
48 return nil, ErrClosedFd
49 }
50
51 // Always require the fd to be larger than zero: the BPF API treats the value
52 // as "no argument provided".
53 dup, err := unix.FcntlInt(uintptr(fd.raw), unix.F_DUPFD_CLOEXEC, 1)
54 if err != nil {
55 return nil, fmt.Errorf("can't dup fd: %v", err)
56 }
57
58 return newFD(dup), nil
59 }
60
61 // File takes ownership of FD and turns it into an [*os.File].
62 //
63 // You must not use the FD after the call returns.
64 //
65 // Returns [ErrClosedFd] if the fd is not valid.
66 func (fd *FD) File(name string) (*os.File, error) {
67 if fd.raw == invalidFd {
68 return nil, ErrClosedFd
69 }
70
71 return os.NewFile(uintptr(fd.Disown()), name), nil
72 }