blob: 39ef8a2a6408d682a917684501d2c9a89085ffb2 [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
Michael Matloob432cb662015-11-11 12:39:30 -05007import (
Ian Lance Taylorea306ae2015-12-11 17:16:48 -08008 "runtime/internal/atomic"
Michael Matloob432cb662015-11-11 12:39:30 -05009 "runtime/internal/sys"
10 "unsafe"
11)
Russ Coxfa2af442014-09-02 15:12:53 -040012
13// The code in this file implements stack trace walking for all architectures.
14// The most important fact about a given architecture is whether it uses a link register.
15// On systems with link registers, the prologue for a non-leaf function stores the
16// incoming value of LR at the bottom of the newly allocated stack frame.
17// On systems without link registers, the architecture pushes a return PC during
18// the call instruction, so the return PC ends up above the stack frame.
19// In this file, the return PC is always called LR, no matter how it was found.
20//
21// To date, the opposite of a link register architecture is an x86 architecture.
22// This code may need to change if some other kind of non-link-register
23// architecture comes along.
24//
25// The other important fact is the size of a pointer: on 32-bit systems the LR
26// takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes.
27// Typically this is ptrSize.
28//
29// As an exception, amd64p32 has ptrSize == 4 but the CALL instruction still
30// stores an 8-byte return PC onto the stack. To accommodate this, we use regSize
31// as the size of the architecture-pushed return PC.
32//
Michael Hudson-Doylea4855812015-10-08 21:52:03 +130033// usesLR is defined below in terms of minFrameSize, which is defined in
34// arch_$GOARCH.go. ptrSize and regSize are defined in stubs.go.
Russ Coxfa2af442014-09-02 15:12:53 -040035
Michael Matloob432cb662015-11-11 12:39:30 -050036const usesLR = sys.MinFrameSize > 0
Russ Coxfa2af442014-09-02 15:12:53 -040037
Russ Cox97f83862014-09-03 13:02:48 -040038var (
Keith Randall70b2da92014-09-29 21:21:36 -070039 // initialized in tracebackinit
Russ Cox656be312014-11-12 14:54:31 -050040 goexitPC uintptr
41 jmpdeferPC uintptr
42 mcallPC uintptr
43 morestackPC uintptr
44 mstartPC uintptr
Russ Cox656be312014-11-12 14:54:31 -050045 rt0_goPC uintptr
46 sigpanicPC uintptr
Dmitry Vyukov59495e82015-02-07 15:31:18 +030047 runfinqPC uintptr
Dmitry Vyukov59495e82015-02-07 15:31:18 +030048 bgsweepPC uintptr
49 forcegchelperPC uintptr
50 timerprocPC uintptr
Austin Clements8d03acc2015-03-23 21:07:33 -040051 gcBgMarkWorkerPC uintptr
Russ Cox656be312014-11-12 14:54:31 -050052 systemstack_switchPC uintptr
Daniel Morsingdb6f88a2015-04-30 15:32:54 +010053 systemstackPC uintptr
Austin Clementse2bb03f2015-08-26 12:16:51 -040054 cgocallback_gofuncPC uintptr
Daniel Morsingdb6f88a2015-04-30 15:32:54 +010055
56 gogoPC uintptr
Russ Cox97f83862014-09-03 13:02:48 -040057
58 externalthreadhandlerp uintptr // initialized elsewhere
59)
Russ Coxfa2af442014-09-02 15:12:53 -040060
Keith Randall70b2da92014-09-29 21:21:36 -070061func tracebackinit() {
62 // Go variable initialization happens late during runtime startup.
63 // Instead of initializing the variables above in the declarations,
64 // schedinit calls this function so that the variables are
65 // initialized and available earlier in the startup sequence.
Keith Randall70b2da92014-09-29 21:21:36 -070066 goexitPC = funcPC(goexit)
67 jmpdeferPC = funcPC(jmpdefer)
68 mcallPC = funcPC(mcall)
69 morestackPC = funcPC(morestack)
70 mstartPC = funcPC(mstart)
Keith Randall70b2da92014-09-29 21:21:36 -070071 rt0_goPC = funcPC(rt0_go)
72 sigpanicPC = funcPC(sigpanic)
Dmitry Vyukov59495e82015-02-07 15:31:18 +030073 runfinqPC = funcPC(runfinq)
Dmitry Vyukov59495e82015-02-07 15:31:18 +030074 bgsweepPC = funcPC(bgsweep)
75 forcegchelperPC = funcPC(forcegchelper)
76 timerprocPC = funcPC(timerproc)
Austin Clements8d03acc2015-03-23 21:07:33 -040077 gcBgMarkWorkerPC = funcPC(gcBgMarkWorker)
Russ Cox656be312014-11-12 14:54:31 -050078 systemstack_switchPC = funcPC(systemstack_switch)
Daniel Morsingdb6f88a2015-04-30 15:32:54 +010079 systemstackPC = funcPC(systemstack)
Austin Clementse2bb03f2015-08-26 12:16:51 -040080 cgocallback_gofuncPC = funcPC(cgocallback_gofunc)
Daniel Morsingdb6f88a2015-04-30 15:32:54 +010081
82 // used by sigprof handler
83 gogoPC = funcPC(gogo)
Keith Randall70b2da92014-09-29 21:21:36 -070084}
85
Russ Coxf95beae2014-09-16 10:36:38 -040086// Traceback over the deferred function calls.
87// Report them like calls that have been invoked but not started executing yet.
88func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
89 var frame stkframe
90 for d := gp._defer; d != nil; d = d.link {
91 fn := d.fn
92 if fn == nil {
93 // Defer of nil function. Args don't matter.
94 frame.pc = 0
95 frame.fn = nil
96 frame.argp = 0
97 frame.arglen = 0
98 frame.argmap = nil
99 } else {
Matthew Dempskya03bdc32016-02-29 15:01:00 -0800100 frame.pc = fn.fn
Russ Coxf95beae2014-09-16 10:36:38 -0400101 f := findfunc(frame.pc)
102 if f == nil {
103 print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800104 throw("unknown pc")
Russ Coxf95beae2014-09-16 10:36:38 -0400105 }
106 frame.fn = f
107 frame.argp = uintptr(deferArgs(d))
Austin Clementsd5bd7972016-10-16 18:23:39 -0400108 frame.arglen, frame.argmap = getArgInfo(&frame, f, true, fn)
Russ Coxf95beae2014-09-16 10:36:38 -0400109 }
110 frame.continpc = frame.pc
111 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
112 return
113 }
114 }
115}
Russ Coxfa2af442014-09-02 15:12:53 -0400116
Brad Fitzpatrick5fea2cc2016-03-01 23:21:55 +0000117// Generic traceback. Handles runtime stack prints (pcbuf == nil),
Russ Coxfa2af442014-09-02 15:12:53 -0400118// the runtime.Callers function (pcbuf != nil), as well as the garbage
119// collector (callback != nil). A little clunky to merge these, but avoids
120// duplicating the code and all its subtlety.
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900121func 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 -0700122 if goexitPC == 0 {
Keith Randallb2a950b2014-12-27 20:58:00 -0800123 throw("gentraceback before goexitPC initialization")
Keith Randall70b2da92014-09-29 21:21:36 -0700124 }
Russ Coxfa2af442014-09-02 15:12:53 -0400125 g := getg()
Russ Cox39bcbb32014-11-05 23:01:48 -0500126 if g == gp && g == g.m.curg {
127 // The starting sp has been passed in as a uintptr, and the caller may
128 // have other uintptr-typed stack references as well.
129 // If during one of the calls that got us here or during one of the
130 // callbacks below the stack must be grown, all these uintptr references
131 // to the stack will not be updated, and gentraceback will continue
132 // to inspect the old stack memory, which may no longer be valid.
133 // Even if all the variables were updated correctly, it is not clear that
134 // we want to expose a traceback that begins on one stack and ends
135 // on another stack. That could confuse callers quite a bit.
136 // Instead, we require that gentraceback and any other function that
137 // accepts an sp for the current goroutine (typically obtained by
138 // calling getcallersp) must not run on that goroutine's stack but
139 // instead on the g0 stack.
Keith Randallb2a950b2014-12-27 20:58:00 -0800140 throw("gentraceback cannot trace user goroutine on its own stack")
Russ Cox39bcbb32014-11-05 23:01:48 -0500141 }
Russ Coxbf1de1b2015-10-30 11:03:02 -0400142 level, _, _ := gotraceback()
Austin Clementsfaa7a7e2015-05-20 16:30:49 -0400143
Russ Coxfa2af442014-09-02 15:12:53 -0400144 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
Russ Cox15b76ad2014-09-09 13:39:57 -0400145 if gp.syscallsp != 0 {
Russ Coxfa2af442014-09-02 15:12:53 -0400146 pc0 = gp.syscallpc
147 sp0 = gp.syscallsp
148 if usesLR {
149 lr0 = 0
150 }
151 } else {
152 pc0 = gp.sched.pc
153 sp0 = gp.sched.sp
154 if usesLR {
155 lr0 = gp.sched.lr
156 }
157 }
158 }
159
160 nprint := 0
161 var frame stkframe
162 frame.pc = pc0
163 frame.sp = sp0
164 if usesLR {
165 frame.lr = lr0
166 }
167 waspanic := false
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700168 cgoCtxt := gp.cgoCtxt
Russ Coxfa2af442014-09-02 15:12:53 -0400169 printing := pcbuf == nil && callback == nil
Russ Coxfa2af442014-09-02 15:12:53 -0400170 _defer := gp._defer
171
Matthew Dempskya03bdc32016-02-29 15:01:00 -0800172 for _defer != nil && _defer.sp == _NoArgs {
Russ Coxfa2af442014-09-02 15:12:53 -0400173 _defer = _defer.link
174 }
Russ Coxfa2af442014-09-02 15:12:53 -0400175
176 // If the PC is zero, it's likely a nil function call.
177 // Start in the caller's frame.
178 if frame.pc == 0 {
179 if usesLR {
180 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
181 frame.lr = 0
182 } else {
Michael Matloob432cb662015-11-11 12:39:30 -0500183 frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp)))
184 frame.sp += sys.RegSize
Russ Coxfa2af442014-09-02 15:12:53 -0400185 }
186 }
187
188 f := findfunc(frame.pc)
189 if f == nil {
190 if callback != nil {
191 print("runtime: unknown pc ", hex(frame.pc), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800192 throw("unknown pc")
Russ Coxfa2af442014-09-02 15:12:53 -0400193 }
194 return 0
195 }
196 frame.fn = f
197
Austin Clementsbeedb1e2015-08-12 23:43:43 -0400198 var cache pcvalueCache
199
Russ Coxfa2af442014-09-02 15:12:53 -0400200 n := 0
Russ Coxfa2af442014-09-02 15:12:53 -0400201 for n < max {
202 // Typically:
203 // pc is the PC of the running function.
204 // sp is the stack pointer at that program counter.
205 // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
206 // stk is the stack containing sp.
207 // 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 -0400208 f = frame.fn
Russ Cox88d3db02016-01-06 12:45:23 -0500209 if f.pcsp == 0 {
210 // No frame information, must be external function, like race support.
211 // See golang.org/issue/13568.
212 break
213 }
Russ Coxfa2af442014-09-02 15:12:53 -0400214
Russ Coxfa2af442014-09-02 15:12:53 -0400215 // Found an actual function.
216 // Derive frame pointer and link register.
217 if frame.fp == 0 {
Daniel Morsingdb6f88a2015-04-30 15:32:54 +0100218 // We want to jump over the systemstack switch. If we're running on the
219 // g0, this systemstack is at the top of the stack.
220 // if we're not on g0 or there's a no curg, then this is a regular call.
221 sp := frame.sp
222 if flags&_TraceJumpStack != 0 && f.entry == systemstackPC && gp == g.m.g0 && gp.m.curg != nil {
223 sp = gp.m.curg.sched.sp
Austin Clementsa640d952016-05-20 14:57:55 -0400224 frame.sp = sp
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700225 cgoCtxt = gp.m.curg.cgoCtxt
Daniel Morsingdb6f88a2015-04-30 15:32:54 +0100226 }
Austin Clementsbeedb1e2015-08-12 23:43:43 -0400227 frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache))
Russ Coxfa2af442014-09-02 15:12:53 -0400228 if !usesLR {
229 // On x86, call instruction pushes return PC before entering new function.
Michael Matloob432cb662015-11-11 12:39:30 -0500230 frame.fp += sys.RegSize
Russ Coxfa2af442014-09-02 15:12:53 -0400231 }
232 }
233 var flr *_func
234 if topofstack(f) {
235 frame.lr = 0
236 flr = nil
237 } else if usesLR && f.entry == jmpdeferPC {
238 // jmpdefer modifies SP/LR/PC non-atomically.
239 // If a profiling interrupt arrives during jmpdefer,
240 // the stack unwind may see a mismatched register set
241 // and get confused. Stop if we see PC within jmpdefer
242 // to avoid that confusion.
243 // See golang.org/issue/8153.
244 if callback != nil {
Keith Randallb2a950b2014-12-27 20:58:00 -0800245 throw("traceback_arm: found jmpdefer when tracing with callback")
Russ Coxfa2af442014-09-02 15:12:53 -0400246 }
247 frame.lr = 0
248 } else {
Austin Clementsfaa7a7e2015-05-20 16:30:49 -0400249 var lrPtr uintptr
Russ Coxfa2af442014-09-02 15:12:53 -0400250 if usesLR {
251 if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
Austin Clementsfaa7a7e2015-05-20 16:30:49 -0400252 lrPtr = frame.sp
253 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
Russ Coxfa2af442014-09-02 15:12:53 -0400254 }
255 } else {
256 if frame.lr == 0 {
Michael Matloob432cb662015-11-11 12:39:30 -0500257 lrPtr = frame.fp - sys.RegSize
258 frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr)))
Russ Coxfa2af442014-09-02 15:12:53 -0400259 }
260 }
261 flr = findfunc(frame.lr)
262 if flr == nil {
263 // This happens if you get a profiling interrupt at just the wrong time.
264 // In that context it is okay to stop early.
265 // But if callback is set, we're doing a garbage collection and must
266 // get everything, so crash loudly.
267 if callback != nil {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800268 print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800269 throw("unknown caller pc")
Russ Coxfa2af442014-09-02 15:12:53 -0400270 }
271 }
272 }
273
274 frame.varp = frame.fp
275 if !usesLR {
276 // On x86, call instruction pushes return PC before entering new function.
Michael Matloob432cb662015-11-11 12:39:30 -0500277 frame.varp -= sys.RegSize
Russ Coxfa2af442014-09-02 15:12:53 -0400278 }
279
Austin Clements3c0fee12015-01-14 11:09:50 -0500280 // If framepointer_enabled and there's a frame, then
281 // there's a saved bp here.
Austin Clementsfc5baec2015-02-03 09:18:15 -0500282 if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp {
Michael Matloob432cb662015-11-11 12:39:30 -0500283 frame.varp -= sys.RegSize
Austin Clements3c0fee12015-01-14 11:09:50 -0500284 }
285
Russ Coxfa2af442014-09-02 15:12:53 -0400286 // Derive size of arguments.
287 // Most functions have a fixed-size argument block,
288 // so we can use metadata about the function f.
289 // Not all, though: there are some variadic functions
290 // in package runtime and reflect, and for those we use call-specific
291 // metadata recorded by f's caller.
292 if callback != nil || printing {
Michael Matloob432cb662015-11-11 12:39:30 -0500293 frame.argp = frame.fp + sys.MinFrameSize
Austin Clementsd5bd7972016-10-16 18:23:39 -0400294 frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, nil)
Russ Coxfa2af442014-09-02 15:12:53 -0400295 }
296
Russ Coxfa2af442014-09-02 15:12:53 -0400297 // Determine frame's 'continuation PC', where it can continue.
298 // Normally this is the return address on the stack, but if sigpanic
299 // is immediately below this function on the stack, then the frame
300 // stopped executing due to a trap, and frame.pc is probably not
301 // a safe point for looking up liveness information. In this panicking case,
302 // the function either doesn't return at all (if it has no defers or if the
303 // defers do not recover) or it returns from one of the calls to
304 // deferproc a second time (if the corresponding deferred func recovers).
305 // It suffices to assume that the most recent deferproc is the one that
306 // returns; everything live at earlier deferprocs is still live at that one.
307 frame.continpc = frame.pc
308 if waspanic {
Keith Randall53c52262014-12-08 14:18:58 -0800309 if _defer != nil && _defer.sp == frame.sp {
Russ Coxfa2af442014-09-02 15:12:53 -0400310 frame.continpc = _defer.pc
311 } else {
312 frame.continpc = 0
313 }
314 }
315
Russ Coxf95beae2014-09-16 10:36:38 -0400316 // Unwind our local defer stack past this frame.
Keith Randall53c52262014-12-08 14:18:58 -0800317 for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) {
Russ Coxfa2af442014-09-02 15:12:53 -0400318 _defer = _defer.link
319 }
320
321 if skip > 0 {
322 skip--
323 goto skipped
324 }
325
326 if pcbuf != nil {
327 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
328 }
329 if callback != nil {
330 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
331 return n
332 }
333 }
334 if printing {
David Lazar781fd392017-02-17 16:08:36 -0500335 // assume skip=0 for printing
Russ Coxf9feaff2016-11-12 23:01:37 -0500336 if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0) {
Russ Coxfa2af442014-09-02 15:12:53 -0400337 // Print during crash.
338 // main(0x1, 0x2, 0x3)
339 // /home/rsc/go/src/runtime/x.go:23 +0xf
340 //
341 tracepc := frame.pc // back up to CALL instruction for funcline.
Russ Coxa22c11b2014-10-29 15:14:24 -0400342 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
Russ Coxfa2af442014-09-02 15:12:53 -0400343 tracepc--
344 }
David Lazar781fd392017-02-17 16:08:36 -0500345 file, line := funcline(f, tracepc)
346 inldata := funcdata(f, _FUNCDATA_InlTree)
347 if inldata != nil {
348 inltree := (*[1 << 20]inlinedCall)(inldata)
349 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
350 for ix != -1 {
351 name := funcnameFromNameoff(f, inltree[ix].func_)
352 print(name, "(...)\n")
353 print("\t", file, ":", line, "\n")
354
355 file = funcfile(f, inltree[ix].file)
356 line = inltree[ix].line
357 ix = inltree[ix].parent
358 }
359 }
Austin Clements0c02bc02016-02-12 10:33:51 -0500360 name := funcname(f)
361 if name == "runtime.gopanic" {
362 name = "panic"
363 }
364 print(name, "(")
Russ Coxfa2af442014-09-02 15:12:53 -0400365 argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
Michael Matloob432cb662015-11-11 12:39:30 -0500366 for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
Russ Coxfa2af442014-09-02 15:12:53 -0400367 if i >= 10 {
368 print(", ...")
369 break
370 }
371 if i != 0 {
372 print(", ")
373 }
374 print(hex(argp[i]))
375 }
376 print(")\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400377 print("\t", file, ":", line)
378 if frame.pc > f.entry {
379 print(" +", hex(frame.pc-f.entry))
380 }
Russ Coxbf1de1b2015-10-30 11:03:02 -0400381 if g.m.throwing > 0 && gp == g.m.curg || level >= 2 {
Russ Coxfa2af442014-09-02 15:12:53 -0400382 print(" fp=", hex(frame.fp), " sp=", hex(frame.sp))
383 }
384 print("\n")
385 nprint++
386 }
387 }
388 n++
389
390 skipped:
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700391 if f.entry == cgocallback_gofuncPC && len(cgoCtxt) > 0 {
392 ctxt := cgoCtxt[len(cgoCtxt)-1]
393 cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
394
395 // skip only applies to Go frames.
396 // callback != nil only used when we only care
397 // about Go frames.
398 if skip == 0 && callback == nil {
399 n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
400 }
401 }
402
Russ Cox97f83862014-09-03 13:02:48 -0400403 waspanic = f.entry == sigpanicPC
Russ Coxfa2af442014-09-02 15:12:53 -0400404
405 // Do not unwind past the bottom of the stack.
406 if flr == nil {
407 break
408 }
409
410 // Unwind to next frame.
411 frame.fn = flr
412 frame.pc = frame.lr
413 frame.lr = 0
414 frame.sp = frame.fp
415 frame.fp = 0
Russ Coxf0d44db2014-09-12 07:29:19 -0400416 frame.argmap = nil
Russ Coxfa2af442014-09-02 15:12:53 -0400417
418 // On link register architectures, sighandler saves the LR on stack
419 // before faking a call to sigpanic.
420 if usesLR && waspanic {
421 x := *(*uintptr)(unsafe.Pointer(frame.sp))
Michael Matloob432cb662015-11-11 12:39:30 -0500422 frame.sp += sys.MinFrameSize
Aram Hăvărneanu846ee042015-03-08 14:20:20 +0100423 if GOARCH == "arm64" {
424 // arm64 needs 16-byte aligned SP, always
Michael Matloob432cb662015-11-11 12:39:30 -0500425 frame.sp += sys.PtrSize
Aram Hăvărneanu846ee042015-03-08 14:20:20 +0100426 }
Russ Coxfa2af442014-09-02 15:12:53 -0400427 f = findfunc(frame.pc)
428 frame.fn = f
429 if f == nil {
430 frame.pc = x
Austin Clementsbeedb1e2015-08-12 23:43:43 -0400431 } else if funcspdelta(f, frame.pc, &cache) == 0 {
Russ Coxfa2af442014-09-02 15:12:53 -0400432 frame.lr = x
433 }
434 }
435 }
436
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900437 if printing {
Russ Coxfa2af442014-09-02 15:12:53 -0400438 n = nprint
439 }
440
441 // If callback != nil, we're being called to gather stack information during
442 // garbage collection or stack growth. In that context, require that we used
443 // up the entire defer stack. If not, then there is a bug somewhere and the
444 // garbage collection or stack growth may not have seen the correct picture
445 // of the stack. Crash now instead of silently executing the garbage collection
446 // or stack copy incorrectly and setting up for a mysterious crash later.
447 //
448 // Note that panic != nil is okay here: there can be leftover panics,
449 // because the defers on the panic stack do not nest in frame order as
450 // they do on the defer stack. If you have:
451 //
452 // frame 1 defers d1
453 // frame 2 defers d2
454 // frame 3 defers d3
455 // frame 4 panics
456 // frame 4's panic starts running defers
457 // frame 5, running d3, defers d4
458 // frame 5 panics
459 // frame 5's panic starts running defers
460 // frame 6, running d4, garbage collects
461 // frame 6, running d2, garbage collects
462 //
463 // During the execution of d4, the panic stack is d4 -> d3, which
464 // is nested properly, and we'll treat frame 3 as resumable, because we
465 // can find d3. (And in fact frame 3 is resumable. If d4 recovers
466 // and frame 5 continues running, d3, d3 can recover and we'll
467 // resume execution in (returning from) frame 3.)
468 //
469 // During the execution of d2, however, the panic stack is d2 -> d3,
470 // which is inverted. The scan will match d2 to frame 2 but having
471 // d2 on the stack until then means it will not match d3 to frame 3.
472 // This is okay: if we're running d2, then all the defers after d2 have
473 // completed and their corresponding frames are dead. Not finding d3
474 // for frame 3 means we'll set frame 3's continpc == 0, which is correct
475 // (frame 3 is dead). At the end of the walk the panic stack can thus
476 // contain defers (d3 in this case) for dead frames. The inversion here
477 // always indicates a dead frame, and the effect of the inversion on the
478 // scan is to hide those dead frames, so the scan is still okay:
479 // what's left on the panic stack are exactly (and only) the dead frames.
480 //
481 // We require callback != nil here because only when callback != nil
482 // do we know that gentraceback is being called in a "must be correct"
483 // context as opposed to a "best effort" context. The tracebacks with
484 // callbacks only happen when everything is stopped nicely.
485 // At other times, such as when gathering a stack for a profiling signal
486 // or when printing a traceback during a crash, everything may not be
487 // stopped nicely, and the stack walk may not be able to complete.
488 // It's okay in those situations not to use up the entire defer stack:
489 // incomplete information then is still better than nothing.
490 if callback != nil && n < max && _defer != nil {
491 if _defer != nil {
Keith Randall53c52262014-12-08 14:18:58 -0800492 print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400493 }
Russ Coxfa2af442014-09-02 15:12:53 -0400494 for _defer = gp._defer; _defer != nil; _defer = _defer.link {
Keith Randall53c52262014-12-08 14:18:58 -0800495 print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400496 }
Keith Randallb2a950b2014-12-27 20:58:00 -0800497 throw("traceback has leftover defers")
Russ Coxfa2af442014-09-02 15:12:53 -0400498 }
499
Russ Cox9c04d002015-08-26 11:39:10 -0400500 if callback != nil && n < max && frame.sp != gp.stktopsp {
501 print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
502 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
503 throw("traceback did not unwind completely")
504 }
505
Russ Coxfa2af442014-09-02 15:12:53 -0400506 return n
507}
508
Austin Clementsddd558e2016-12-16 11:57:25 -0500509// reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
510// and reflect.methodValue.
Austin Clementsd5bd7972016-10-16 18:23:39 -0400511type reflectMethodValue struct {
512 fn uintptr
513 stack *bitvector // args bitmap
514}
515
516// getArgInfo returns the argument frame information for a call to f
517// with call frame frame.
518//
519// This is used for both actual calls with active stack frames and for
520// deferred calls that are not yet executing. If this is an actual
521// call, ctxt must be nil (getArgInfo will retrieve what it needs from
522// the active stack frame). If this is a deferred call, ctxt must be
523// the function object that was deferred.
524func getArgInfo(frame *stkframe, f *_func, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
Austin Clementsb43b3752015-11-17 17:14:32 -0500525 arglen = uintptr(f.args)
Russ Coxf95beae2014-09-16 10:36:38 -0400526 if needArgMap && f.args == _ArgsSizeUnknown {
527 // Extract argument bitmaps for reflect stubs from the calls they made to reflect.
Keith Randall0bb8fc62014-12-28 23:16:32 -0800528 switch funcname(f) {
Russ Coxf95beae2014-09-16 10:36:38 -0400529 case "reflect.makeFuncStub", "reflect.methodValueCall":
Austin Clementsd5bd7972016-10-16 18:23:39 -0400530 // These take a *reflect.methodValue as their
531 // context register.
532 var mv *reflectMethodValue
533 if ctxt != nil {
534 // This is not an actual call, but a
535 // deferred call. The function value
536 // is itself the *reflect.methodValue.
537 mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
538 } else {
539 // This is a real call that took the
540 // *reflect.methodValue as its context
541 // register and immediately saved it
542 // to 0(SP). Get the methodValue from
543 // 0(SP).
544 arg0 := frame.sp + sys.MinFrameSize
545 mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
546 }
547 if mv.fn != f.entry {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800548 print("runtime: confused by ", funcname(f), "\n")
Keith Randallb2a950b2014-12-27 20:58:00 -0800549 throw("reflect mismatch")
Russ Coxf95beae2014-09-16 10:36:38 -0400550 }
Austin Clementsd5bd7972016-10-16 18:23:39 -0400551 bv := mv.stack
Austin Clementsb43b3752015-11-17 17:14:32 -0500552 arglen = uintptr(bv.n * sys.PtrSize)
553 argmap = bv
Russ Coxf95beae2014-09-16 10:36:38 -0400554 }
555 }
Austin Clementsb43b3752015-11-17 17:14:32 -0500556 return
Russ Coxf95beae2014-09-16 10:36:38 -0400557}
558
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700559// tracebackCgoContext handles tracing back a cgo context value, from
560// the context argument to setCgoTraceback, for the gentraceback
561// function. It returns the new value of n.
562func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
563 var cgoPCs [32]uintptr
564 cgoContextPCs(ctxt, cgoPCs[:])
565 var arg cgoSymbolizerArg
566 anySymbolized := false
567 for _, pc := range cgoPCs {
568 if pc == 0 || n >= max {
569 break
570 }
571 if pcbuf != nil {
572 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
573 }
574 if printing {
575 if cgoSymbolizer == nil {
576 print("non-Go function at pc=", hex(pc), "\n")
577 } else {
578 c := printOneCgoTraceback(pc, max-n, &arg)
579 n += c - 1 // +1 a few lines down
580 anySymbolized = true
581 }
582 }
583 n++
584 }
585 if anySymbolized {
586 arg.pc = 0
587 callCgoSymbolizer(&arg)
588 }
589 return n
590}
591
Russ Coxfa2af442014-09-02 15:12:53 -0400592func printcreatedby(gp *g) {
593 // Show what created goroutine, except main goroutine (goid 1).
594 pc := gp.gopc
595 f := findfunc(pc)
Russ Coxf9feaff2016-11-12 23:01:37 -0500596 if f != nil && showframe(f, gp, false) && gp.goid != 1 {
Keith Randall0bb8fc62014-12-28 23:16:32 -0800597 print("created by ", funcname(f), "\n")
Russ Coxfa2af442014-09-02 15:12:53 -0400598 tracepc := pc // back up to CALL instruction for funcline.
599 if pc > f.entry {
Michael Matloob432cb662015-11-11 12:39:30 -0500600 tracepc -= sys.PCQuantum
Russ Coxfa2af442014-09-02 15:12:53 -0400601 }
Russ Cox656be312014-11-12 14:54:31 -0500602 file, line := funcline(f, tracepc)
Russ Coxfa2af442014-09-02 15:12:53 -0400603 print("\t", file, ":", line)
604 if pc > f.entry {
605 print(" +", hex(pc-f.entry))
606 }
607 print("\n")
608 }
609}
610
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900611func traceback(pc, sp, lr uintptr, gp *g) {
Russ Coxa22c11b2014-10-29 15:14:24 -0400612 traceback1(pc, sp, lr, gp, 0)
613}
614
615// tracebacktrap is like traceback but expects that the PC and SP were obtained
616// from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
617// Because they are from a trap instead of from a saved pair,
618// the initial PC must not be rewound to the previous instruction.
619// (All the saved pairs record a PC that is a return address, so we
620// rewind it into the CALL instruction.)
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900621func tracebacktrap(pc, sp, lr uintptr, gp *g) {
Russ Coxa22c11b2014-10-29 15:14:24 -0400622 traceback1(pc, sp, lr, gp, _TraceTrap)
623}
624
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900625func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800626 // If the goroutine is in cgo, and we have a cgo traceback, print that.
627 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
628 // Lock cgoCallers so that a signal handler won't
629 // change it, copy the array, reset it, unlock it.
630 // We are locked to the thread and are not running
631 // concurrently with a signal handler.
632 // We just have to stop a signal handler from interrupting
633 // in the middle of our copy.
634 atomic.Store(&gp.m.cgoCallersUse, 1)
635 cgoCallers := *gp.m.cgoCallers
636 gp.m.cgoCallers[0] = 0
637 atomic.Store(&gp.m.cgoCallersUse, 0)
638
639 printCgoTraceback(&cgoCallers)
640 }
641
Russ Coxfa2af442014-09-02 15:12:53 -0400642 var n int
643 if readgstatus(gp)&^_Gscan == _Gsyscall {
Russ Coxa22c11b2014-10-29 15:14:24 -0400644 // Override registers if blocked in system call.
Russ Coxfa2af442014-09-02 15:12:53 -0400645 pc = gp.syscallpc
646 sp = gp.syscallsp
Russ Coxa22c11b2014-10-29 15:14:24 -0400647 flags &^= _TraceTrap
Russ Coxfa2af442014-09-02 15:12:53 -0400648 }
649 // Print traceback. By default, omits runtime frames.
650 // If that means we print nothing at all, repeat forcing all frames printed.
Russ Coxa22c11b2014-10-29 15:14:24 -0400651 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
652 if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
653 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
Russ Coxfa2af442014-09-02 15:12:53 -0400654 }
655 if n == _TracebackMaxFrames {
656 print("...additional frames elided...\n")
657 }
658 printcreatedby(gp)
659}
660
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900661func callers(skip int, pcbuf []uintptr) int {
Russ Coxfa2af442014-09-02 15:12:53 -0400662 sp := getcallersp(unsafe.Pointer(&skip))
Matthew Dempskya03bdc32016-02-29 15:01:00 -0800663 pc := getcallerpc(unsafe.Pointer(&skip))
Austin Clements719efc72015-05-20 11:50:48 -0400664 gp := getg()
Russ Cox39bcbb32014-11-05 23:01:48 -0500665 var n int
Russ Cox656be312014-11-12 14:54:31 -0500666 systemstack(func() {
Austin Clements719efc72015-05-20 11:50:48 -0400667 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
Russ Cox39bcbb32014-11-05 23:01:48 -0500668 })
669 return n
Russ Coxfa2af442014-09-02 15:12:53 -0400670}
671
Matthew Dempsky3c8a89d2015-02-25 14:41:21 +0900672func gcallers(gp *g, skip int, pcbuf []uintptr) int {
673 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
Russ Coxfa2af442014-09-02 15:12:53 -0400674}
Russ Cox7ba41e92014-09-03 11:11:16 -0400675
Russ Coxf9feaff2016-11-12 23:01:37 -0500676func showframe(f *_func, gp *g, firstFrame bool) bool {
Russ Cox97f83862014-09-03 13:02:48 -0400677 g := getg()
Russ Cox181e26b2015-04-17 00:21:30 -0400678 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
Russ Cox97f83862014-09-03 13:02:48 -0400679 return true
680 }
Russ Coxbf1de1b2015-10-30 11:03:02 -0400681 level, _, _ := gotraceback()
Keith Randall0bb8fc62014-12-28 23:16:32 -0800682 name := funcname(f)
Russ Cox97f83862014-09-03 13:02:48 -0400683
Russ Coxf9feaff2016-11-12 23:01:37 -0500684 // Special case: always show runtime.gopanic frame
685 // in the middle of a stack trace, so that we can
686 // see the boundary between ordinary code and
687 // panic-induced deferred code.
Russ Cox97f83862014-09-03 13:02:48 -0400688 // See golang.org/issue/5832.
Russ Coxf9feaff2016-11-12 23:01:37 -0500689 if name == "runtime.gopanic" && !firstFrame {
Russ Cox97f83862014-09-03 13:02:48 -0400690 return true
691 }
692
Russ Coxbf1de1b2015-10-30 11:03:02 -0400693 return level > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
Russ Cox54245cb2014-09-18 20:35:36 -0400694}
695
696// isExportedRuntime reports whether name is an exported runtime function.
697// It is only for runtime functions, so ASCII A-Z is fine.
698func isExportedRuntime(name string) bool {
699 const n = len("runtime.")
700 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
Russ Cox97f83862014-09-03 13:02:48 -0400701}
702
Russ Cox7ba41e92014-09-03 11:11:16 -0400703var gStatusStrings = [...]string{
704 _Gidle: "idle",
705 _Grunnable: "runnable",
706 _Grunning: "running",
707 _Gsyscall: "syscall",
708 _Gwaiting: "waiting",
709 _Gdead: "dead",
Russ Cox7ba41e92014-09-03 11:11:16 -0400710 _Gcopystack: "copystack",
711}
712
Russ Cox7ba41e92014-09-03 11:11:16 -0400713func goroutineheader(gp *g) {
714 gpstatus := readgstatus(gp)
715
Austin Clementsc7c7c702015-12-21 11:26:33 -0800716 isScan := gpstatus&_Gscan != 0
717 gpstatus &^= _Gscan // drop the scan bit
718
Russ Cox7ba41e92014-09-03 11:11:16 -0400719 // Basic string status
720 var status string
721 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
722 status = gStatusStrings[gpstatus]
Russ Cox7ba41e92014-09-03 11:11:16 -0400723 } else {
724 status = "???"
725 }
726
727 // Override.
Austin Clementsc7c7c702015-12-21 11:26:33 -0800728 if gpstatus == _Gwaiting && gp.waitreason != "" {
Russ Cox7ba41e92014-09-03 11:11:16 -0400729 status = gp.waitreason
730 }
731
732 // approx time the G is blocked, in minutes
733 var waitfor int64
Russ Cox7ba41e92014-09-03 11:11:16 -0400734 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
735 waitfor = (nanotime() - gp.waitsince) / 60e9
736 }
737 print("goroutine ", gp.goid, " [", status)
Austin Clementsc7c7c702015-12-21 11:26:33 -0800738 if isScan {
739 print(" (scan)")
740 }
Russ Cox7ba41e92014-09-03 11:11:16 -0400741 if waitfor >= 1 {
742 print(", ", waitfor, " minutes")
743 }
744 if gp.lockedm != nil {
745 print(", locked to thread")
746 }
747 print("]:\n")
748}
749
750func tracebackothers(me *g) {
Russ Coxbf1de1b2015-10-30 11:03:02 -0400751 level, _, _ := gotraceback()
Russ Cox7ba41e92014-09-03 11:11:16 -0400752
753 // Show the current goroutine first, if we haven't already.
754 g := getg()
755 gp := g.m.curg
756 if gp != nil && gp != me {
757 print("\n")
758 goroutineheader(gp)
759 traceback(^uintptr(0), ^uintptr(0), 0, gp)
760 }
761
762 lock(&allglock)
763 for _, gp := range allgs {
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300764 if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
Russ Cox7ba41e92014-09-03 11:11:16 -0400765 continue
766 }
767 print("\n")
768 goroutineheader(gp)
Keith Randall4b78c952015-04-28 14:53:19 -0700769 // Note: gp.m == g.m occurs when tracebackothers is
770 // called from a signal handler initiated during a
Brad Fitzpatrick5fea2cc2016-03-01 23:21:55 +0000771 // systemstack call. The original G is still in the
Keith Randall4b78c952015-04-28 14:53:19 -0700772 // running state, and we want to print its stack.
773 if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
Russ Cox7ba41e92014-09-03 11:11:16 -0400774 print("\tgoroutine running on other thread; stack unavailable\n")
775 printcreatedby(gp)
776 } else {
777 traceback(^uintptr(0), ^uintptr(0), 0, gp)
778 }
779 }
780 unlock(&allglock)
781}
782
Russ Cox7ba41e92014-09-03 11:11:16 -0400783// Does f mark the top of a goroutine stack?
784func topofstack(f *_func) bool {
785 pc := f.entry
786 return pc == goexitPC ||
787 pc == mstartPC ||
788 pc == mcallPC ||
Russ Cox7ba41e92014-09-03 11:11:16 -0400789 pc == morestackPC ||
Russ Cox7ba41e92014-09-03 11:11:16 -0400790 pc == rt0_goPC ||
791 externalthreadhandlerp != 0 && pc == externalthreadhandlerp
792}
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300793
Josh Bleecher Snyder2adc4e82015-02-17 15:44:42 -0800794// isSystemGoroutine reports whether the goroutine g must be omitted in
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300795// stack dumps and deadlock detector.
796func isSystemGoroutine(gp *g) bool {
797 pc := gp.startpc
798 return pc == runfinqPC && !fingRunning ||
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300799 pc == bgsweepPC ||
800 pc == forcegchelperPC ||
Austin Clements8d03acc2015-03-23 21:07:33 -0400801 pc == timerprocPC ||
802 pc == gcBgMarkWorkerPC
Dmitry Vyukov59495e82015-02-07 15:31:18 +0300803}
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800804
805// SetCgoTraceback records three C functions to use to gather
806// traceback information from C code and to convert that traceback
807// information into symbolic information. These are used when printing
808// stack traces for a program that uses cgo.
809//
810// The traceback and context functions may be called from a signal
811// handler, and must therefore use only async-signal safe functions.
812// The symbolizer function may be called while the program is
813// crashing, and so must be cautious about using memory. None of the
814// functions may call back into Go.
815//
816// The context function will be called with a single argument, a
817// pointer to a struct:
818//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500819// struct {
820// Context uintptr
821// }
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800822//
823// In C syntax, this struct will be
824//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500825// struct {
826// uintptr_t Context;
827// };
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800828//
829// If the Context field is 0, the context function is being called to
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700830// record the current traceback context. It should record in the
831// Context field whatever information is needed about the current
832// point of execution to later produce a stack trace, probably the
833// stack pointer and PC. In this case the context function will be
834// called from C code.
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800835//
836// If the Context field is not 0, then it is a value returned by a
837// previous call to the context function. This case is called when the
838// context is no longer needed; that is, when the Go code is returning
Dmitry Vyukovba221722016-06-02 07:43:21 +0200839// to its C code caller. This permits the context function to release
840// any associated resources.
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800841//
842// While it would be correct for the context function to record a
843// complete a stack trace whenever it is called, and simply copy that
844// out in the traceback function, in a typical program the context
845// function will be called many times without ever recording a
846// traceback for that context. Recording a complete stack trace in a
847// call to the context function is likely to be inefficient.
848//
849// The traceback function will be called with a single argument, a
850// pointer to a struct:
851//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500852// struct {
Ian Lance Taylor3d037cf2016-05-27 10:05:52 -0700853// Context uintptr
854// SigContext uintptr
855// Buf *uintptr
856// Max uintptr
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500857// }
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800858//
859// In C syntax, this struct will be
860//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500861// struct {
862// uintptr_t Context;
Ian Lance Taylor3d037cf2016-05-27 10:05:52 -0700863// uintptr_t SigContext;
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500864// uintptr_t* Buf;
865// uintptr_t Max;
866// };
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800867//
868// The Context field will be zero to gather a traceback from the
869// current program execution point. In this case, the traceback
870// function will be called from C code.
871//
872// Otherwise Context will be a value previously returned by a call to
873// the context function. The traceback function should gather a stack
874// trace from that saved point in the program execution. The traceback
875// function may be called from an execution thread other than the one
876// that recorded the context, but only when the context is known to be
877// valid and unchanging. The traceback function may also be called
878// deeper in the call stack on the same thread that recorded the
879// context. The traceback function may be called multiple times with
880// the same Context value; it will usually be appropriate to cache the
881// result, if possible, the first time this is called for a specific
882// context value.
883//
Ian Lance Taylor3d037cf2016-05-27 10:05:52 -0700884// If the traceback function is called from a signal handler on a Unix
885// system, SigContext will be the signal context argument passed to
886// the signal handler (a C ucontext_t* cast to uintptr_t). This may be
887// used to start tracing at the point where the signal occurred. If
888// the traceback function is not called from a signal handler,
889// SigContext will be zero.
890//
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800891// Buf is where the traceback information should be stored. It should
892// be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
893// the PC of that function's caller, and so on. Max is the maximum
894// number of entries to store. The function should store a zero to
895// indicate the top of the stack, or that the caller is on a different
896// stack, presumably a Go stack.
897//
898// Unlike runtime.Callers, the PC values returned should, when passed
899// to the symbolizer function, return the file/line of the call
900// instruction. No additional subtraction is required or appropriate.
901//
902// The symbolizer function will be called with a single argument, a
903// pointer to a struct:
904//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500905// struct {
906// PC uintptr // program counter to fetch information for
907// File *byte // file name (NUL terminated)
908// Lineno uintptr // line number
909// Func *byte // function name (NUL terminated)
910// Entry uintptr // function entry point
911// More uintptr // set non-zero if more info for this PC
912// Data uintptr // unused by runtime, available for function
913// }
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800914//
915// In C syntax, this struct will be
916//
Brad Fitzpatrick06d639e2016-04-27 16:56:13 -0500917// struct {
918// uintptr_t PC;
919// char* File;
920// uintptr_t Lineno;
921// char* Func;
922// uintptr_t Entry;
923// uintptr_t More;
924// uintptr_t Data;
925// };
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800926//
927// The PC field will be a value returned by a call to the traceback
928// function.
929//
930// The first time the function is called for a particular traceback,
931// all the fields except PC will be 0. The function should fill in the
932// other fields if possible, setting them to 0/nil if the information
933// is not available. The Data field may be used to store any useful
934// information across calls. The More field should be set to non-zero
935// if there is more information for this PC, zero otherwise. If More
936// is set non-zero, the function will be called again with the same
937// PC, and may return different information (this is intended for use
938// with inlined functions). If More is zero, the function will be
939// called with the next PC value in the traceback. When the traceback
940// is complete, the function will be called once more with PC set to
941// zero; this may be used to free any information. Each call will
942// leave the fields of the struct set to the same values they had upon
943// return, except for the PC field when the More field is zero. The
944// function must not keep a copy of the struct pointer between calls.
945//
946// When calling SetCgoTraceback, the version argument is the version
947// number of the structs that the functions expect to receive.
948// Currently this must be zero.
949//
950// The symbolizer function may be nil, in which case the results of
951// the traceback function will be displayed as numbers. If the
952// traceback function is nil, the symbolizer function will never be
953// called. The context function may be nil, in which case the
954// traceback function will only be called with the context field set
955// to zero. If the context function is nil, then calls from Go to C
956// to Go will not show a traceback for the C portion of the call stack.
Ian Lance Taylor03abde42016-06-02 12:01:03 -0700957//
958// SetCgoTraceback should be called only once, ideally from an init function.
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800959func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
960 if version != 0 {
961 panic("unsupported version")
962 }
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700963
Ian Lance Taylor03abde42016-06-02 12:01:03 -0700964 if cgoTraceback != nil && cgoTraceback != traceback ||
965 cgoContext != nil && cgoContext != context ||
966 cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
967 panic("call SetCgoTraceback only once")
968 }
969
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800970 cgoTraceback = traceback
Ian Lance Taylor03abde42016-06-02 12:01:03 -0700971 cgoContext = context
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800972 cgoSymbolizer = symbolizer
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700973
974 // The context function is called when a C function calls a Go
975 // function. As such it is only called by C code in runtime/cgo.
976 if _cgo_set_context_function != nil {
977 cgocall(_cgo_set_context_function, context)
978 }
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800979}
980
981var cgoTraceback unsafe.Pointer
Ian Lance Taylor03abde42016-06-02 12:01:03 -0700982var cgoContext unsafe.Pointer
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800983var cgoSymbolizer unsafe.Pointer
984
985// cgoTracebackArg is the type passed to cgoTraceback.
986type cgoTracebackArg struct {
Ian Lance Taylor3d037cf2016-05-27 10:05:52 -0700987 context uintptr
988 sigContext uintptr
989 buf *uintptr
990 max uintptr
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800991}
992
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -0700993// cgoContextArg is the type passed to the context function.
Ian Lance Taylorea306ae2015-12-11 17:16:48 -0800994type cgoContextArg struct {
995 context uintptr
996}
997
998// cgoSymbolizerArg is the type passed to cgoSymbolizer.
999type cgoSymbolizerArg struct {
1000 pc uintptr
1001 file *byte
1002 lineno uintptr
1003 funcName *byte
1004 entry uintptr
1005 more uintptr
1006 data uintptr
1007}
1008
1009// cgoTraceback prints a traceback of callers.
1010func printCgoTraceback(callers *cgoCallers) {
1011 if cgoSymbolizer == nil {
1012 for _, c := range callers {
1013 if c == 0 {
1014 break
1015 }
1016 print("non-Go function at pc=", hex(c), "\n")
1017 }
1018 return
1019 }
1020
Ian Lance Taylorea306ae2015-12-11 17:16:48 -08001021 var arg cgoSymbolizerArg
1022 for _, c := range callers {
1023 if c == 0 {
1024 break
1025 }
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -07001026 printOneCgoTraceback(c, 0x7fffffff, &arg)
Ian Lance Taylorea306ae2015-12-11 17:16:48 -08001027 }
1028 arg.pc = 0
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -07001029 callCgoSymbolizer(&arg)
1030}
1031
1032// printOneCgoTraceback prints the traceback of a single cgo caller.
1033// This can print more than one line because of inlining.
1034// Returns the number of frames printed.
1035func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
1036 c := 0
1037 arg.pc = pc
1038 for {
1039 if c > max {
1040 break
1041 }
1042 callCgoSymbolizer(arg)
1043 if arg.funcName != nil {
1044 // Note that we don't print any argument
1045 // information here, not even parentheses.
1046 // The symbolizer must add that if appropriate.
1047 println(gostringnocopy(arg.funcName))
1048 } else {
1049 println("non-Go function")
1050 }
1051 print("\t")
1052 if arg.file != nil {
1053 print(gostringnocopy(arg.file), ":", arg.lineno, " ")
1054 }
Ian Lance Taylorc08436d2016-05-18 15:20:56 -07001055 print("pc=", hex(pc), "\n")
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -07001056 c++
1057 if arg.more == 0 {
1058 break
1059 }
1060 }
1061 return c
1062}
1063
1064// callCgoSymbolizer calls the cgoSymbolizer function.
1065func callCgoSymbolizer(arg *cgoSymbolizerArg) {
1066 call := cgocall
1067 if panicking > 0 || getg().m.curg != getg() {
1068 // We do not want to call into the scheduler when panicking
1069 // or when on the system stack.
1070 call = asmcgocall
1071 }
Ian Lance Taylord00890b2016-07-10 18:44:09 -07001072 if msanenabled {
1073 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
1074 }
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -07001075 call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
1076}
1077
1078// cgoContextPCs gets the PC values from a cgo traceback.
1079func cgoContextPCs(ctxt uintptr, buf []uintptr) {
1080 if cgoTraceback == nil {
1081 return
1082 }
1083 call := cgocall
1084 if panicking > 0 || getg().m.curg != getg() {
1085 // We do not want to call into the scheduler when panicking
1086 // or when on the system stack.
1087 call = asmcgocall
1088 }
1089 arg := cgoTracebackArg{
1090 context: ctxt,
1091 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
1092 max: uintptr(len(buf)),
1093 }
Ian Lance Taylord00890b2016-07-10 18:44:09 -07001094 if msanenabled {
1095 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
1096 }
Ian Lance Taylor5f9a8702016-04-27 14:18:29 -07001097 call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
Ian Lance Taylorea306ae2015-12-11 17:16:48 -08001098}