-
Notifications
You must be signed in to change notification settings - Fork 451
/
debug.go
319 lines (276 loc) · 7.59 KB
/
debug.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package checked
import (
"bytes"
"fmt"
"runtime"
"sync"
"time"
"github.com/m3db/m3/src/x/resource"
)
const (
defaultTraceback = false
defaultTracebackCycles = 3
defaultTracebackMaxDepth = 64
defaultLeakDetection = false
)
var (
traceback = defaultTraceback
tracebackCycles = defaultTracebackCycles
tracebackMaxDepth = defaultTracebackMaxDepth
panicFn = defaultPanic
leakDetectionFlag = defaultLeakDetection
)
var tracebackCallersPool = sync.Pool{New: func() interface{} {
// Pools should generally only return pointer types, since a pointer
// can be put into the return interface value without an allocation.
// However, since this package is used just for debugging, we make the
// tradeoff of greater code clarity by putting slices directly into the
// pool at the cost of an additional allocation of the three words which
// comprise the slice on each put.
return make([]uintptr, tracebackMaxDepth)
}}
var tracebackEntryPool = sync.Pool{New: func() interface{} {
return &debuggerEntry{}
}}
var leaks struct {
sync.RWMutex
m map[string]uint64
}
// PanicFn is a panic function to call on invalid checked state
type PanicFn func(e error)
// SetPanicFn sets the panic function
func SetPanicFn(fn PanicFn) {
panicFn = fn
}
// Panic will execute the currently set panic function
func Panic(e error) {
panicFn(e)
}
// ResetPanicFn resets the panic function to the default runtime panic
func ResetPanicFn() {
panicFn = defaultPanic
}
// EnableTracebacks turns traceback collection for events on
func EnableTracebacks() {
traceback = true
}
// DisableTracebacks turns traceback collection for events off
func DisableTracebacks() {
traceback = false
}
// SetTracebackCycles sets the count of traceback cycles to keep if enabled
func SetTracebackCycles(value int) {
tracebackCycles = value
}
// SetTracebackMaxDepth sets the max amount of frames to capture for traceback
func SetTracebackMaxDepth(frames int) {
tracebackMaxDepth = frames
}
// EnableLeakDetection turns leak detection on.
func EnableLeakDetection() {
leakDetectionFlag = true
}
// DisableLeakDetection turns leak detection off.
func DisableLeakDetection() {
leakDetectionFlag = false
}
func leakDetectionEnabled() bool {
return leakDetectionFlag
}
// DumpLeaks returns all detected leaks so far.
func DumpLeaks() []string {
var r []string
leaks.RLock()
for k, v := range leaks.m {
r = append(r, fmt.Sprintf("leaked %d bytes, origin:\n%s", v, k))
}
leaks.RUnlock()
return r
}
func defaultPanic(e error) {
panic(e)
}
func panicRef(c *RefCount, err error) {
if traceback {
trace := getDebuggerRef(c).String()
err = fmt.Errorf("%v, traceback:\n\n%s", err, trace)
}
panicFn(err)
}
type debuggerEvent int
const (
incRefEvent debuggerEvent = iota
decRefEvent
moveRefEvent
finalizeEvent
incReadsEvent
decReadsEvent
incWritesEvent
decWritesEvent
)
func (d debuggerEvent) String() string {
switch d {
case incRefEvent:
return "IncRef"
case decRefEvent:
return "DecRef"
case moveRefEvent:
return "MoveRef"
case finalizeEvent:
return "Finalize"
case incReadsEvent:
return "IncReads"
case decReadsEvent:
return "DecReads"
case incWritesEvent:
return "IncWrites"
case decWritesEvent:
return "DecWrites"
}
return "Unknown"
}
type debugger struct {
sync.Mutex
entries [][]*debuggerEntry
}
func (d *debugger) append(event debuggerEvent, ref int, pc []uintptr) {
d.Lock()
if len(d.entries) == 0 {
d.entries = make([][]*debuggerEntry, 1, tracebackCycles)
}
idx := len(d.entries) - 1
entry := tracebackEntryPool.Get().(*debuggerEntry)
entry.event = event
entry.ref = ref
entry.pc = pc
entry.t = time.Now()
d.entries[idx] = append(d.entries[idx], entry)
if event == finalizeEvent {
if len(d.entries) == tracebackCycles {
// Shift all tracebacks back one if at end of traceback cycles
slice := d.entries[0]
for i, entry := range slice {
tracebackCallersPool.Put(entry.pc) // nolint: megacheck
entry.pc = nil
tracebackEntryPool.Put(entry)
slice[i] = nil
}
for i := 1; i < len(d.entries); i++ {
d.entries[i-1] = d.entries[i]
}
d.entries[idx] = slice[:0]
} else {
// Begin writing new events to the next cycle
d.entries = d.entries[:len(d.entries)+1]
}
}
d.Unlock()
}
func (d *debugger) String() string {
buffer := bytes.NewBuffer(nil)
d.Lock()
// Reverse the entries for time descending
for i := len(d.entries) - 1; i >= 0; i-- {
for j := len(d.entries[i]) - 1; j >= 0; j-- {
buffer.WriteString(d.entries[i][j].String())
}
}
d.Unlock()
return buffer.String()
}
type debuggerRef struct {
debugger
finalizer resource.Finalizer
}
func (d *debuggerRef) Finalize() {
if d.finalizer != nil {
d.finalizer.Finalize()
}
}
type debuggerEntry struct {
event debuggerEvent
ref int
pc []uintptr
t time.Time
}
func (e *debuggerEntry) String() string {
buf := bytes.NewBuffer(nil)
frames := runtime.CallersFrames(e.pc)
for {
frame, more := frames.Next()
buf.WriteString(frame.Function)
buf.WriteString("(...)")
buf.WriteString("\n")
buf.WriteString("\t")
buf.WriteString(frame.File)
buf.WriteString(":")
buf.WriteString(fmt.Sprintf("%d", frame.Line))
buf.WriteString(fmt.Sprintf(" +%x", frame.Entry))
buf.WriteString("\n")
if !more {
break
}
}
return fmt.Sprintf("%s, ref=%d, unixnanos=%d:\n%s\n",
e.event.String(), e.ref, e.t.UnixNano(), buf.String())
}
func getDebuggerRef(c *RefCount) *debuggerRef {
// Note: because finalizer is an atomic pointer not using
// CompareAndSwapPointer makes this code is racy, however
// it is safe due to using atomic load and stores.
// This is used primarily for debugging and the races will
// show up when inspecting the tracebacks.
finalizer := c.Finalizer()
if finalizer == nil {
debugger := &debuggerRef{}
c.SetFinalizer(debugger)
return debugger
}
debugger, ok := finalizer.(*debuggerRef)
if !ok {
// Wrap the existing finalizer in a debuggerRef
debugger := &debuggerRef{finalizer: finalizer}
c.SetFinalizer(debugger)
return debugger
}
return debugger
}
func tracebackEvent(c *RefCount, ref int, e debuggerEvent) {
if !traceback {
return
}
d := getDebuggerRef(c)
depth := tracebackMaxDepth
pc := tracebackCallersPool.Get().([]uintptr)
if capacity := cap(pc); capacity < depth {
// Defensive programming here in case someone changes
// the max depth during runtime
pc = make([]uintptr, depth)
}
pc = pc[:depth]
skipEntry := 2
n := runtime.Callers(skipEntry, pc)
d.append(e, ref, pc[:n])
}
func init() {
leaks.m = make(map[string]uint64)
}