Debian Codegraph @

internal/testutils/testmain/fd_trace.go

raw symbols SCIP
1 package testmain
2
3 import (
4 "bytes"
5 "fmt"
6 "os"
7 "runtime"
8 "sync"
9 "sync/atomic"
10 )
11
12 // foundLeak is atomic since the GC may collect objects in parallel.
13 var foundLeak atomic.Bool
14
15 func onLeakFD(fs *runtime.Frames) {
16 foundLeak.Store(true)
17 fmt.Fprintln(os.Stderr, "leaked fd created at:")
18 fmt.Fprintln(os.Stderr, formatFrames(fs))
19 }
20
21 // fds is a registry of all file descriptors wrapped into sys.fds that were
22 // created while an fd tracer was active.
23 var fds *sync.Map // map[int]*runtime.Frames
24
25 // TraceFD associates raw with the current execution stack.
26 //
27 // skip controls how many entries of the stack the function should skip.
28 func TraceFD(raw int, skip int) {
29 if fds == nil {
30 return
31 }
32
33 // Attempt to store the caller's stack for the given fd value.
34 // Panic if fds contains an existing stack for the fd.
35 old, exist := fds.LoadOrStore(raw, callersFrames(skip))
36 if exist {
37 f := old.(*runtime.Frames)
38 panic(fmt.Sprintf("found existing stack for fd %d:\n%s", raw, formatFrames(f)))
39 }
40 }
41
42 // ForgetFD removes any existing association for raw.
43 func ForgetFD(raw int) {
44 if fds != nil {
45 fds.Delete(raw)
46 }
47 }
48
49 // LeakFD indicates that raw was leaked.
50 //
51 // Calling the function with a value that was not passed to [TraceFD] before
52 // is undefined.
53 func LeakFD(raw int) {
54 if fds == nil {
55 return
56 }
57
58 // Invoke the fd leak callback. Calls LoadAndDelete to guarantee the callback
59 // is invoked at most once for one sys.FD allocation, runtime.Frames can only
60 // be unwound once.
61 f, ok := fds.LoadAndDelete(raw)
62 if ok {
63 onLeakFD(f.(*runtime.Frames))
64 }
65 }
66
67 // flushFrames removes all elements from fds and returns them as a slice. This
68 // deals with the fact that a runtime.Frames can only be unwound once using
69 // Next().
70 func flushFrames() []*runtime.Frames {
71 var frames []*runtime.Frames
72 fds.Range(func(key, value any) bool {
73 frames = append(frames, value.(*runtime.Frames))
74 fds.Delete(key)
75 return true
76 })
77 return frames
78 }
79
80 func callersFrames(skip int) *runtime.Frames {
81 c := make([]uintptr, 32)
82
83 // Skip runtime.Callers and this function.
84 i := runtime.Callers(skip+2, c)
85 if i == 0 {
86 return nil
87 }
88
89 return runtime.CallersFrames(c)
90 }
91
92 // formatFrames formats a runtime.Frames as a human-readable string.
93 func formatFrames(fs *runtime.Frames) string {
94 var b bytes.Buffer
95 for {
96 f, more := fs.Next()
97 b.WriteString(fmt.Sprintf("\t%s+%#x\n\t\t%s:%d\n", f.Function, f.PC-f.Entry, f.File, f.Line))
98 if !more {
99 break
100 }
101 }
102 return b.String()
103 }