Debian Codegraph @

internal/sys/fd.go

raw symbols SCIP
1 package sys
2
3 import (
4 "math"
5 "runtime"
6 "strconv"
7
8 "github.com/cilium/ebpf/internal/testutils/testmain"
9 "github.com/cilium/ebpf/internal/unix"
10 )
11
12 var ErrClosedFd = unix.EBADF
13
14 // A value for an invalid fd.
15 //
16 // Luckily this is consistent across Linux and Windows.
17 //
18 // See https://github.com/microsoft/ebpf-for-windows/blob/54632eb360c560ebef2f173be1a4a4625d540744/include/ebpf_api.h#L25
19 const invalidFd = -1
20
21 func newFD(value int) *FD {
22 testmain.TraceFD(value, 1)
23
24 fd := &FD{raw: value}
25 fd.cleanup = runtime.AddCleanup(fd, func(raw int) {
26 testmain.LeakFD(raw)
27 _ = unix.Close(raw)
28 }, fd.raw)
29 return fd
30 }
31
32 func (fd *FD) String() string {
33 return strconv.FormatInt(int64(fd.raw), 10)
34 }
35
36 func (fd *FD) Int() int {
37 return int(fd.raw)
38 }
39
40 func (fd *FD) Uint() uint32 {
41 if fd.raw == invalidFd {
42 // Best effort: this is the number most likely to be an invalid file
43 // descriptor. It is equal to -1 (on two's complement arches).
44 return math.MaxUint32
45 }
46 return uint32(fd.raw)
47 }
48
49 // Disown destroys the FD and returns its raw file descriptor without closing
50 // it. After this call, the underlying fd is no longer tied to the FD's
51 // lifecycle.
52 func (fd *FD) Disown() int {
53 value := fd.raw
54 testmain.ForgetFD(value)
55 fd.raw = invalidFd
56
57 fd.cleanup.Stop()
58 return value
59 }