| 1 |
package testmain |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"os" |
| 7 |
"runtime" |
| 8 |
"sync" |
| 9 |
"sync/atomic" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 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 |
|
| 22 |
|
| 23 |
var fds *sync.Map |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
func TraceFD(raw int, skip int) { |
| 29 |
if fds == nil { |
| 30 |
return |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 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 |
|
| 43 |
func ForgetFD(raw int) { |
| 44 |
if fds != nil { |
| 45 |
fds.Delete(raw) |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
func LeakFD(raw int) { |
| 54 |
if fds == nil { |
| 55 |
return |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
f, ok := fds.LoadAndDelete(raw) |
| 62 |
if ok { |
| 63 |
onLeakFD(f.(*runtime.Frames)) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 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 |
|
| 84 |
i := runtime.Callers(skip+2, c) |
| 85 |
if i == 0 { |
| 86 |
return nil |
| 87 |
} |
| 88 |
|
| 89 |
return runtime.CallersFrames(c) |
| 90 |
} |
| 91 |
|
| 92 |
|
| 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 |
} |