blob: 9f34e37ea4ec2939e1ae06f9392cf75d5dee15bc [file] [log] [blame]
Russ Coxfa2af442014-09-02 15:12:53 -04001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package runtime
6
7import "unsafe"
8
9// The code in this file implements stack trace walking for all architectures.
10// The most important fact about a given architecture is whether it uses a link register.
11// On systems with link registers, the prologue for a non-leaf function stores the
12// incoming value of LR at the bottom of the newly allocated stack frame.
13// On systems without link registers, the architecture pushes a return PC during
14// the call instruction, so the return PC ends up above the stack frame.
15// In this file, the return PC is always called LR, no matter how it was found.
16//
17// To date, the opposite of a link register architecture is an x86 architecture.
18// This code may need to change if some other kind of non-link-register
19// architecture comes along.
20//
21// The other important fact is the size of a pointer: on 32-bit systems the LR
22// takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes.
23// Typically this is ptrSize.
24//
25// As an exception, amd64p32 has ptrSize == 4 but the CALL instruction still
26// stores an 8-byte return PC onto the stack. To accommodate this, we use regSize
27// as the size of the architecture-pushed return PC.
28//
29// usesLR is defined below. ptrSize and regSize are defined in stubs.go.
30
31const usesLR = GOARCH != "amd64" && GOARCH != "amd64p32" && GOARCH != "386"
32
Russ Cox97f83862014-09-03 13:02:48 -040033var (
Keith Randall70b2da92014-09-29 21:21:36 -070034 // initialized in tracebackinit
Russ Cox656be312014-11-12 14:54:31 -050035 goexitPC uintptr
36 jmpdeferPC uintptr
37 mcallPC uintptr
38 morestackPC uintptr
39 mstartPC uintptr
Russ Cox656be312014-11-12 14:54:31 -050040 rt0_goPC uintptr
41 sigpanicPC uintptr
Dmitry Vyukov59495e82015-02-07 15:31:18 +030042 runfinqPC uintptr
43 backgroundgcPC uintptr
44 bgsweepPC uintptr
45 forcegchelperPC uintptr
46 timerprocPC uintptr
Austin Clements8d03acc2015-03-23 21:07:33 -040047 gcBgMarkWorkerPC uintptr
Russ Cox656be312014-11-12 14:54:31 -050048 systemstack_switchPC uintptr
Russ Cox97f83862014-09-03 13:02:48 -040049
50 externalthreadhandlerp uintptr // initialized elsewhere
51)
Russ Coxfa2af442014-09-02 15:12:53 -040052
Keith Randall70b2da92014-09-29 21:21:36 -070053func tracebackinit() {
54 // Go variable initialization happens late during runtime startup.
55 // Instead of initializing the variables above in the declarations,
56 // schedinit calls this function so that the variables are
57 // initialized and available earlier in the startup sequence.
Keith Randall70b2da92014-09-29 21:21:36 -070058 goexitPC = funcPC(goexit)
59 jmpdeferPC = funcPC(jmpdefer)
60 mcallPC = funcPC(mcall)
61 morestackPC = funcPC(morestack)
62 mstartPC = funcPC(mstart)
Keith Randall70b2da92014-09-29 21:21:36 -070063 rt0_goPC = funcPC(rt0_go)
64 sigpanicPC = funcPC(sigpanic)
Dmitry Vyukov59495e82015-02-07 15:31:18 +030065 runfinqPC = funcPC(runfinq)
66 backgroundgcPC = funcPC(backgroundgc)
67 bgsweepPC = funcPC(bgsweep)
68 forcegchelperPC = funcPC(forcegchelper)
69 timerprocPC = funcPC(timerproc)
Austin Clements8d03acc2015-03-23 21:07:33 -040070 gcBgMarkWorkerPC = funcPC(gcBgMarkWorker)
Russ Cox656be312014-11-12 14:54:31 -050071 systemstack_switchPC = funcPC(systemstack_switch)
Keith Randall70b2da92014-09-29 21:21:36 -070072}
73
Russ Coxf95beae2014-09-16 10:36:38 -040074// Traceback over the deferred function calls.
75// Report them like calls that have been invoked but not started executing yet.
76func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
77 var frame stkframe
78 for d := gp._defer; d != nil; d = d.link {
79 fn := d.fn
80 if fn == nil {
81 // Defer of nil function. Args don't matter.
82 frame.pc = 0
83 frame.fn = nil
84 frame.argp = 0
85 frame.arglen = 0
86 frame.argmap = nil
87 } else {
88 frame.pc = uintptr(fn.fn)
89 f := findfunc(frame.pc)
90 if f == nil {
91 print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -080092 throw("unknown pc")
Russ Coxf95beae2014-09-16 10:36:38 -040093 }
94 frame.fn = f
95 frame.argp = uintptr(deferArgs(d))
96 setArgInfo(&frame, f, true)
97 }
98 frame.continpc = frame.pc
99 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
100 return
101 }
102 }
103}
Russ Coxfa2af442014-09-02 15:12:53 -0400104
105// Generic traceback. Handles runtime stack prints (pcbuf == nil),
106// the runtime.Callers function (pcbuf != nil), as well as the garbage
107// collector (callback != nil). A little clunky to merge these, but avoids
108// duplicating the code and all its subtlety.
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900109func gentraceback(pc0, sp0, lr0 uintptr, gp *g, skip int, pcbuf *uintptr, max int, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer, flags uint) int {
Keith Randall70b2da92014-09-29 21:21:36 -0700110 if goexitPC == 0 {
Keith Randallb2a950b2014-12-27 20:58:00 -0800111 throw("gentraceback before goexitPC initialization")
Keith Randall70b2da92014-09-29 21:21:36 -0700112 }
Russ Coxfa2af442014-09-02 15:12:53 -0400113 g := getg()
Russ Cox39bcbb32014-11-05 23:01:48 -0500114 if g == gp && g == g.m.curg {
115 // The starting sp has been passed in as a uintptr, and the caller may
116 // have other uintptr-typed stack references as well.
117 // If during one of the calls that got us here or during one of the
118 // callbacks below the stack must be grown, all these uintptr references
119 // to the stack will not be updated, and gentraceback will continue
120 // to inspect the old stack memory, which may no longer be valid.
121 // Even if all the variables were updated correctly, it is not clear that
122 // we want to expose a traceback that begins on one stack and ends
123 // on another stack. That could confuse callers quite a bit.
124 // Instead, we require that gentraceback and any other function that
125 // accepts an sp for the current goroutine (typically obtained by
126 // calling getcallersp) must not run on that goroutine's stack but
127 // instead on the g0 stack.
Keith Randallb2a950b2014-12-27 20:58:00 -0800128 throw("gentraceback cannot trace user goroutine on its own stack")
Russ Cox39bcbb32014-11-05 23:01:48 -0500129 }
Russ Coxfa2af442014-09-02 15:12:53 -0400130 gotraceback := gotraceback(nil)
131 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
Russ Cox15b76ad2014-09-09 13:39:57 -0400132 if gp.syscallsp != 0 {
Russ Coxfa2af442014-09-02 15:12:53 -0400133 pc0 = gp.syscallpc
134 sp0 = gp.syscallsp
135 if usesLR {
136 lr0 = 0
137 }
138 } else {
139 pc0 = gp.sched.pc
140 sp0 = gp.sched.sp
141 if usesLR {
142 lr0 = gp.sched.lr
143 }
144 }
145 }
146
147 nprint := 0
148 var frame stkframe
149 frame.pc = pc0
150 frame.sp = sp0
151 if usesLR {
152 frame.lr = lr0
153 }
154 waspanic := false
Russ Coxfa2af442014-09-02 15:12:53 -0400155 printing := pcbuf == nil && callback == nil
Russ Coxfa2af442014-09-02 15:12:53 -0400156 _defer := gp._defer
157
Keith Randall53c52262014-12-08 14:18:58 -0800158 for _defer != nil && uintptr(_defer.sp) == _NoArgs {
Russ Coxfa2af442014-09-02 15:12:53 -0400159 _defer = _defer.link
160 }
Russ Coxfa2af442014-09-02 15:12:53 -0400161
162 // If the PC is zero, it's likely a nil function call.
163 // Start in the caller's frame.
164 if frame.pc == 0 {
165 if usesLR {
166 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
167 frame.lr = 0
168 } else {
169 frame.pc = uintptr(*(*uintreg)(unsafe.Pointer(frame.sp)))
170 frame.sp += regSize
171 }
172 }
173
174 f := findfunc(frame.pc)
175 if f == nil {
176 if callback != nil {
177 print("runtime: unknown pc ", hex(frame.pc), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800178 throw("unknown pc")
Russ Coxfa2af442014-09-02 15:12:53 -0400179 }
180 return 0
181 }
182 frame.fn = f
183
184 n := 0
Russ Coxfa2af442014-09-02 15:12:53 -0400185 for n < max {
186 // Typically:
187 // pc is the PC of the running function.
188 // sp is the stack pointer at that program counter.
189 // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
190 // stk is the stack containing sp.
191 // The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
Russ Coxfa2af442014-09-02 15:12:53 -0400192 f = frame.fn
193
Russ Coxfa2af442014-09-02 15:12:53 -0400194 // Found an actual function.
195 // Derive frame pointer and link register.
196 if frame.fp == 0 {
197 frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc))
198 if !usesLR {
199 // On x86, call instruction pushes return PC before entering new function.
200 frame.fp += regSize
201 }
202 }
203 var flr *_func
204 if topofstack(f) {
205 frame.lr = 0
206 flr = nil
207 } else if usesLR && f.entry == jmpdeferPC {
208 // jmpdefer modifies SP/LR/PC non-atomically.
209 // If a profiling interrupt arrives during jmpdefer,
210 // the stack unwind may see a mismatched register set
211 // and get confused. Stop if we see PC within jmpdefer
212 // to avoid that confusion.
213 // See golang.org/issue/8153.
214 if callback != nil {
Keith Randallb2a950b2014-12-27 20:58:00 -0800215 throw("traceback_arm: found jmpdefer when tracing with callback")
Russ Coxfa2af442014-09-02 15:12:53 -0400216 }
217 frame.lr = 0
218 } else {
219 if usesLR {
220 if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
221 frame.lr = *(*uintptr)(unsafe.Pointer(frame.sp))
222 }
223 } else {
224 if frame.lr == 0 {
225 frame.lr = uintptr(*(*uintreg)(unsafe.Pointer(frame.fp - regSize)))
226 }
227 }
228 flr = findfunc(frame.lr)
229 if flr == nil {
230 // This happens if you get a profiling interrupt at just the wrong time.
231 // In that context it is okay to stop early.
232 // But if callback is set, we're doing a garbage collection and must
233 // get everything, so crash loudly.
234 if callback != nil {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800235 print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800236 throw("unknown caller pc")
Russ Coxfa2af442014-09-02 15:12:53 -0400237 }
238 }
239 }
240
241 frame.varp = frame.fp
242 if !usesLR {
243 // On x86, call instruction pushes return PC before entering new function.
244 frame.varp -= regSize
245 }
246
Austin Clements3c0fee12015-01-14 11:09:50 -0500247 // If framepointer_enabled and there's a frame, then
248 // there's a saved bp here.
Austin Clementsfc5baec2015-02-03 09:18:15 -0500249 if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp {
Austin Clements67a03fd2015-02-03 09:09:56 -0500250 frame.varp -= regSize
Austin Clements3c0fee12015-01-14 11:09:50 -0500251 }
252
Russ Coxfa2af442014-09-02 15:12:53 -0400253 // Derive size of arguments.
254 // Most functions have a fixed-size argument block,
255 // so we can use metadata about the function f.
256 // Not all, though: there are some variadic functions
257 // in package runtime and reflect, and for those we use call-specific
258 // metadata recorded by f's caller.
259 if callback != nil || printing {
260 frame.argp = frame.fp
261 if usesLR {
262 frame.argp += ptrSize
263 }
Russ Coxf95beae2014-09-16 10:36:38 -0400264 setArgInfo(&frame, f, callback != nil)
Russ Coxfa2af442014-09-02 15:12:53 -0400265 }
266
Russ Coxfa2af442014-09-02 15:12:53 -0400267 // Determine frame's 'continuation PC', where it can continue.
268 // Normally this is the return address on the stack, but if sigpanic
269 // is immediately below this function on the stack, then the frame
270 // stopped executing due to a trap, and frame.pc is probably not
271 // a safe point for looking up liveness information. In this panicking case,
272 // the function either doesn't return at all (if it has no defers or if the
273 // defers do not recover) or it returns from one of the calls to
274 // deferproc a second time (if the corresponding deferred func recovers).
275 // It suffices to assume that the most recent deferproc is the one that
276 // returns; everything live at earlier deferprocs is still live at that one.
277 frame.continpc = frame.pc
278 if waspanic {
Keith Randall53c52262014-12-08 14:18:58 -0800279 if _defer != nil && _defer.sp == frame.sp {
Russ Coxfa2af442014-09-02 15:12:53 -0400280 frame.continpc = _defer.pc
281 } else {
282 frame.continpc = 0
283 }
284 }
285
Russ Coxf95beae2014-09-16 10:36:38 -0400286 // Unwind our local defer stack past this frame.
Keith Randall53c52262014-12-08 14:18:58 -0800287 for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) {
Russ Coxfa2af442014-09-02 15:12:53 -0400288 _defer = _defer.link
289 }
290
291 if skip > 0 {
292 skip--
293 goto skipped
294 }
295
296 if pcbuf != nil {
297 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
298 }
299 if callback != nil {
300 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
301 return n
302 }
303 }
304 if printing {
Russ Coxa22c11b2014-10-29 15:14:24 -0400305 if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp) {
Russ Coxfa2af442014-09-02 15:12:53 -0400306 // Print during crash.
307 // main(0x1, 0x2, 0x3)
308 // /home/rsc/go/src/runtime/x.go:23 +0xf
309 //
310 tracepc := frame.pc // back up to CALL instruction for funcline.
Russ Coxa22c11b2014-10-29 15:14:24 -0400311 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
Russ Coxfa2af442014-09-02 15:12:53 -0400312 tracepc--
313 }
Keith Randall0bb8fc62014-12-28 23:16:32 -0800314 print(funcname(f), "(")
Russ Coxfa2af442014-09-02 15:12:53 -0400315 argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
316 for i := uintptr(0); i < frame.arglen/ptrSize; i++ {
317 if i >= 10 {
318 print(", ...")
319 break
320 }
321 if i != 0 {
322 print(", ")
323 }
324 print(hex(argp[i]))
325 }
326 print(")\n")
Russ Cox656be312014-11-12 14:54:31 -0500327 file, line := funcline(f, tracepc)
Russ Coxfa2af442014-09-02 15:12:53 -0400328 print("\t", file, ":", line)
329 if frame.pc > f.entry {
330 print(" +", hex(frame.pc-f.entry))
331 }
332 if g.m.throwing > 0 && gp == g.m.curg || gotraceback >= 2 {
333 print(" fp=", hex(frame.fp), " sp=", hex(frame.sp))
334 }
335 print("\n")
336 nprint++
337 }
338 }
339 n++
340
341 skipped:
Russ Cox97f83862014-09-03 13:02:48 -0400342 waspanic = f.entry == sigpanicPC
Russ Coxfa2af442014-09-02 15:12:53 -0400343
344 // Do not unwind past the bottom of the stack.
345 if flr == nil {
346 break
347 }
348
349 // Unwind to next frame.
350 frame.fn = flr
351 frame.pc = frame.lr
352 frame.lr = 0
353 frame.sp = frame.fp
354 frame.fp = 0
Russ Coxf0d44db2014-09-12 07:29:19 -0400355 frame.argmap = nil
Russ Coxfa2af442014-09-02 15:12:53 -0400356
357 // On link register architectures, sighandler saves the LR on stack
358 // before faking a call to sigpanic.
359 if usesLR && waspanic {
360 x := *(*uintptr)(unsafe.Pointer(frame.sp))
361 frame.sp += ptrSize
Aram Hăvărneanu846ee042015-03-08 14:20:20 +0100362 if GOARCH == "arm64" {
363 // arm64 needs 16-byte aligned SP, always
364 frame.sp += ptrSize
365 }
Russ Coxfa2af442014-09-02 15:12:53 -0400366 f = findfunc(frame.pc)
367 frame.fn = f
368 if f == nil {
369 frame.pc = x
Russ Coxdd82d5e2015-03-01 21:29:25 -0500370 } else if funcspdelta(f, frame.pc) == 0 {
Russ Coxfa2af442014-09-02 15:12:53 -0400371 frame.lr = x
372 }
373 }
374 }
375
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900376 if printing {
Russ Coxfa2af442014-09-02 15:12:53 -0400377 n = nprint
378 }
379
380 // If callback != nil, we're being called to gather stack information during
381 // garbage collection or stack growth. In that context, require that we used
382 // up the entire defer stack. If not, then there is a bug somewhere and the
383 // garbage collection or stack growth may not have seen the correct picture
384 // of the stack. Crash now instead of silently executing the garbage collection
385 // or stack copy incorrectly and setting up for a mysterious crash later.
386 //
387 // Note that panic != nil is okay here: there can be leftover panics,
388 // because the defers on the panic stack do not nest in frame order as
389 // they do on the defer stack. If you have:
390 //
391 // frame 1 defers d1
392 // frame 2 defers d2
393 // frame 3 defers d3
394 // frame 4 panics
395 // frame 4's panic starts running defers
396 // frame 5, running d3, defers d4
397 // frame 5 panics
398 // frame 5's panic starts running defers
399 // frame 6, running d4, garbage collects
400 // frame 6, running d2, garbage collects
401 //
402 // During the execution of d4, the panic stack is d4 -> d3, which
403 // is nested properly, and we'll treat frame 3 as resumable, because we
404 // can find d3. (And in fact frame 3 is resumable. If d4 recovers
405 // and frame 5 continues running, d3, d3 can recover and we'll
406 // resume execution in (returning from) frame 3.)
407 //
408 // During the execution of d2, however, the panic stack is d2 -> d3,
409 // which is inverted. The scan will match d2 to frame 2 but having
410 // d2 on the stack until then means it will not match d3 to frame 3.
411 // This is okay: if we're running d2, then all the defers after d2 have
412 // completed and their corresponding frames are dead. Not finding d3
413 // for frame 3 means we'll set frame 3's continpc == 0, which is correct
414 // (frame 3 is dead). At the end of the walk the panic stack can thus
415 // contain defers (d3 in this case) for dead frames. The inversion here
416 // always indicates a dead frame, and the effect of the inversion on the
417 // scan is to hide those dead frames, so the scan is still okay:
418 // what's left on the panic stack are exactly (and only) the dead frames.
419 //
420 // We require callback != nil here because only when callback != nil
421 // do we know that gentraceback is being called in a "must be correct"
422 // context as opposed to a "best effort" context. The tracebacks with
423 // callbacks only happen when everything is stopped nicely.
424 // At other times, such as when gathering a stack for a profiling signal
425 // or when printing a traceback during a crash, everything may not be
426 // stopped nicely, and the stack walk may not be able to complete.
427 // It's okay in those situations not to use up the entire defer stack:
428 // incomplete information then is still better than nothing.
429 if callback != nil && n < max && _defer != nil {
430 if _defer != nil {
Keith Randall53c52262014-12-08 14:18:58 -0800431 print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400432 }
Russ Coxfa2af442014-09-02 15:12:53 -0400433 for _defer = gp._defer; _defer != nil; _defer = _defer.link {
Keith Randall53c52262014-12-08 14:18:58 -0800434 print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400435 }
Keith Randallb2a950b2014-12-27 20:58:00 -0800436 throw("traceback has leftover defers")
Russ Coxfa2af442014-09-02 15:12:53 -0400437 }
438
439 return n
440}
441
Russ Coxf95beae2014-09-16 10:36:38 -0400442func setArgInfo(frame *stkframe, f *_func, needArgMap bool) {
443 frame.arglen = uintptr(f.args)
444 if needArgMap && f.args == _ArgsSizeUnknown {
445 // Extract argument bitmaps for reflect stubs from the calls they made to reflect.
Keith Randall0bb8fc62014-12-28 23:16:32 -0800446 switch funcname(f) {
Russ Coxf95beae2014-09-16 10:36:38 -0400447 case "reflect.makeFuncStub", "reflect.methodValueCall":
448 arg0 := frame.sp
449 if usesLR {
450 arg0 += ptrSize
451 }
452 fn := *(**[2]uintptr)(unsafe.Pointer(arg0))
453 if fn[0] != f.entry {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800454 print("runtime: confused by ", funcname(f), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800455 throw("reflect mismatch")
Russ Coxf95beae2014-09-16 10:36:38 -0400456 }
457 bv := (*bitvector)(unsafe.Pointer(fn[1]))
458 frame.arglen = uintptr(bv.n / 2 * ptrSize)
459 frame.argmap = bv
460 }
461 }
462}
463
Russ Coxfa2af442014-09-02 15:12:53 -0400464func printcreatedby(gp *g) {
465 // Show what created goroutine, except main goroutine (goid 1).
466 pc := gp.gopc
467 f := findfunc(pc)
468 if f != nil && showframe(f, gp) && gp.goid != 1 {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800469 print("created by ", funcname(f), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400470 tracepc := pc // back up to CALL instruction for funcline.
471 if pc > f.entry {
472 tracepc -= _PCQuantum
473 }
Russ Cox656be312014-11-12 14:54:31 -0500474 file, line := funcline(f, tracepc)
Russ Coxfa2af442014-09-02 15:12:53 -0400475 print("\t", file, ":", line)
476 if pc > f.entry {
477 print(" +", hex(pc-f.entry))
478 }
479 print("\n")
480 }
481}
482
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900483func traceback(pc, sp, lr uintptr, gp *g) {
Russ Coxa22c11b2014-10-29 15:14:24 -0400484 traceback1(pc, sp, lr, gp, 0)
485}
486
487// tracebacktrap is like traceback but expects that the PC and SP were obtained
488// from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
489// Because they are from a trap instead of from a saved pair,
490// the initial PC must not be rewound to the previous instruction.
491// (All the saved pairs record a PC that is a return address, so we
492// rewind it into the CALL instruction.)
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900493func tracebacktrap(pc, sp, lr uintptr, gp *g) {
Russ Coxa22c11b2014-10-29 15:14:24 -0400494 traceback1(pc, sp, lr, gp, _TraceTrap)
495}
496
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900497func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
Russ Coxfa2af442014-09-02 15:12:53 -0400498 var n int
499 if readgstatus(gp)&^_Gscan == _Gsyscall {
Russ Coxa22c11b2014-10-29 15:14:24 -0400500 // Override registers if blocked in system call.
Russ Coxfa2af442014-09-02 15:12:53 -0400501 pc = gp.syscallpc
502 sp = gp.syscallsp
Russ Coxa22c11b2014-10-29 15:14:24 -0400503 flags &^= _TraceTrap
Russ Coxfa2af442014-09-02 15:12:53 -0400504 }
505 // Print traceback. By default, omits runtime frames.
506 // If that means we print nothing at all, repeat forcing all frames printed.
Russ Coxa22c11b2014-10-29 15:14:24 -0400507 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
508 if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
509 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
Russ Coxfa2af442014-09-02 15:12:53 -0400510 }
511 if n == _TracebackMaxFrames {
512 print("...additional frames elided...\n")
513 }
514 printcreatedby(gp)
515}
516
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900517func callers(skip int, pcbuf []uintptr) int {
Russ Coxfa2af442014-09-02 15:12:53 -0400518 sp := getcallersp(unsafe.Pointer(&skip))
519 pc := uintptr(getcallerpc(unsafe.Pointer(&skip)))
Russ Cox39bcbb32014-11-05 23:01:48 -0500520 var n int
Russ Cox656be312014-11-12 14:54:31 -0500521 systemstack(func() {
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900522 n = gentraceback(pc, sp, 0, getg(), skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
Russ Cox39bcbb32014-11-05 23:01:48 -0500523 })
524 return n
Russ Coxfa2af442014-09-02 15:12:53 -0400525}
526
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900527func gcallers(gp *g, skip int, pcbuf []uintptr) int {
528 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
Russ Coxfa2af442014-09-02 15:12:53 -0400529}
Russ Cox7ba41e92014-09-03 11:11:16 -0400530
Russ Cox97f83862014-09-03 13:02:48 -0400531func showframe(f *_func, gp *g) bool {
532 g := getg()
Russ Cox181e26b2015-04-17 00:21:30 -0400533 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
Russ Cox97f83862014-09-03 13:02:48 -0400534 return true
535 }
536 traceback := gotraceback(nil)
Keith Randall0bb8fc62014-12-28 23:16:32 -0800537 name := funcname(f)
Russ Cox97f83862014-09-03 13:02:48 -0400538
539 // Special case: always show runtime.panic frame, so that we can
540 // see where a panic started in the middle of a stack trace.
541 // See golang.org/issue/5832.
542 if name == "runtime.panic" {
543 return true
544 }
545
Russ Cox54245cb2014-09-18 20:35:36 -0400546 return traceback > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
547}
548
549// isExportedRuntime reports whether name is an exported runtime function.
550// It is only for runtime functions, so ASCII A-Z is fine.
551func isExportedRuntime(name string) bool {
552 const n = len("runtime.")
553 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
Russ Cox97f83862014-09-03 13:02:48 -0400554}
555
Russ Cox7ba41e92014-09-03 11:11:16 -0400556var gStatusStrings = [...]string{
557 _Gidle: "idle",
558 _Grunnable: "runnable",
559 _Grunning: "running",
560 _Gsyscall: "syscall",
561 _Gwaiting: "waiting",
562 _Gdead: "dead",
563 _Genqueue: "enqueue",
564 _Gcopystack: "copystack",
565}
566
567var gScanStatusStrings = [...]string{
568 0: "scan",
569 _Grunnable: "scanrunnable",
570 _Grunning: "scanrunning",
571 _Gsyscall: "scansyscall",
572 _Gwaiting: "scanwaiting",
573 _Gdead: "scandead",
574 _Genqueue: "scanenqueue",
575}
576
577func goroutineheader(gp *g) {
578 gpstatus := readgstatus(gp)
579
580 // Basic string status
581 var status string
582 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
583 status = gStatusStrings[gpstatus]
584 } else if gpstatus&_Gscan != 0 && 0 <= gpstatus&^_Gscan && gpstatus&^_Gscan < uint32(len(gStatusStrings)) {
585 status = gStatusStrings[gpstatus&^_Gscan]
586 } else {
587 status = "???"
588 }
589
590 // Override.
591 if (gpstatus == _Gwaiting || gpstatus == _Gscanwaiting) && gp.waitreason != "" {
592 status = gp.waitreason
593 }
594
595 // approx time the G is blocked, in minutes
596 var waitfor int64
597 gpstatus &^= _Gscan // drop the scan bit
598 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
599 waitfor = (nanotime() - gp.waitsince) / 60e9
600 }
601 print("goroutine ", gp.goid, " [", status)
602 if waitfor >= 1 {
603 print(", ", waitfor, " minutes")
604 }
605 if gp.lockedm != nil {
606 print(", locked to thread")
607 }
608 print("]:\n")
609}
610
611func tracebackothers(me *g) {
612 level := gotraceback(nil)
613
614 // Show the current goroutine first, if we haven't already.
615 g := getg()
616 gp := g.m.curg
617 if gp != nil && gp != me {
618 print("\n")
619 goroutineheader(gp)
620 traceback(^uintptr(0), ^uintptr(0), 0, gp)
621 }
622
623 lock(&allglock)
624 for _, gp := range allgs {
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300625 if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
Russ Cox7ba41e92014-09-03 11:11:16 -0400626 continue
627 }
628 print("\n")
629 goroutineheader(gp)
Keith Randall4b78c952015-04-28 14:53:19 -0700630 // Note: gp.m == g.m occurs when tracebackothers is
631 // called from a signal handler initiated during a
632 // systemstack call. The original G is still in the
633 // running state, and we want to print its stack.
634 if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
Russ Cox7ba41e92014-09-03 11:11:16 -0400635 print("\tgoroutine running on other thread; stack unavailable\n")
636 printcreatedby(gp)
637 } else {
638 traceback(^uintptr(0), ^uintptr(0), 0, gp)
639 }
640 }
641 unlock(&allglock)
642}
643
Russ Cox7ba41e92014-09-03 11:11:16 -0400644// Does f mark the top of a goroutine stack?
645func topofstack(f *_func) bool {
646 pc := f.entry
647 return pc == goexitPC ||
648 pc == mstartPC ||
649 pc == mcallPC ||
Russ Cox7ba41e92014-09-03 11:11:16 -0400650 pc == morestackPC ||
Russ Cox7ba41e92014-09-03 11:11:16 -0400651 pc == rt0_goPC ||
652 externalthreadhandlerp != 0 && pc == externalthreadhandlerp
653}
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300654
Josh Bleecher Snyder2adc4e82015-02-17 15:44:42 -0800655// isSystemGoroutine reports whether the goroutine g must be omitted in
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300656// stack dumps and deadlock detector.
657func isSystemGoroutine(gp *g) bool {
658 pc := gp.startpc
659 return pc == runfinqPC && !fingRunning ||
660 pc == backgroundgcPC ||
661 pc == bgsweepPC ||
662 pc == forcegchelperPC ||
Austin Clements8d03acc2015-03-23 21:07:33 -0400663 pc == timerprocPC ||
664 pc == gcBgMarkWorkerPC
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300665}