Debian Codegraph @

src/runtime/traceback.go

raw
1 // 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
5 package runtime
6
7 import (
8 "internal/abi"
9 "internal/bytealg"
10 "internal/goarch"
11 "internal/runtime/pprof/label"
12 "internal/runtime/sys"
13 "internal/stringslite"
14 "unsafe"
15 )
16
17 // The code in this file implements stack trace walking for all architectures.
18 // The most important fact about a given architecture is whether it uses a link register.
19 // On systems with link registers, the prologue for a non-leaf function stores the
20 // incoming value of LR at the bottom of the newly allocated stack frame.
21 // On systems without link registers (x86), the architecture pushes a return PC during
22 // the call instruction, so the return PC ends up above the stack frame.
23 // In this file, the return PC is always called LR, no matter how it was found.
24
25 const usesLR = sys.MinFrameSize > 0
26
27 const (
28 // tracebackInnerFrames is the number of innermost frames to print in a
29 // stack trace. The total maximum frames is tracebackInnerFrames +
30 // tracebackOuterFrames.
31 tracebackInnerFrames = 50
32
33 // tracebackOuterFrames is the number of outermost frames to print in a
34 // stack trace.
35 tracebackOuterFrames = 50
36 )
37
38 // unwindFlags control the behavior of various unwinders.
39 type unwindFlags uint8
40
41 const (
42 // unwindPrintErrors indicates that if unwinding encounters an error, it
43 // should print a message and stop without throwing. This is used for things
44 // like stack printing, where it's better to get incomplete information than
45 // to crash. This is also used in situations where everything may not be
46 // stopped nicely and the stack walk may not be able to complete, such as
47 // during profiling signals or during a crash.
48 //
49 // If neither unwindPrintErrors or unwindSilentErrors are set, unwinding
50 // performs extra consistency checks and throws on any error.
51 //
52 // Note that there are a small number of fatal situations that will throw
53 // regardless of unwindPrintErrors or unwindSilentErrors.
54 unwindPrintErrors unwindFlags = 1 << iota
55
56 // unwindSilentErrors silently ignores errors during unwinding.
57 unwindSilentErrors
58
59 // unwindTrap indicates that the initial PC and SP are from a trap, not a
60 // return PC from a call.
61 //
62 // The unwindTrap flag is updated during unwinding. If set, frame.pc is the
63 // address of a faulting instruction instead of the return address of a
64 // call. It also means the liveness at pc may not be known.
65 //
66 // TODO: Distinguish frame.continpc, which is really the stack map PC, from
67 // the actual continuation PC, which is computed differently depending on
68 // this flag and a few other things.
69 unwindTrap
70
71 // unwindJumpStack indicates that, if the traceback is on a system stack, it
72 // should resume tracing at the user stack when the system stack is
73 // exhausted.
74 unwindJumpStack
75 )
76
77 // An unwinder iterates the physical stack frames of a Go sack.
78 //
79 // Typical use of an unwinder looks like:
80 //
81 // var u unwinder
82 // for u.init(gp, 0); u.valid(); u.next() {
83 // // ... use frame info in u ...
84 // }
85 //
86 // Implementation note: This is carefully structured to be pointer-free because
87 // tracebacks happen in places that disallow write barriers (e.g., signals).
88 // Even if this is stack-allocated, its pointer-receiver methods don't know that
89 // their receiver is on the stack, so they still emit write barriers. Here we
90 // address that by carefully avoiding any pointers in this type. Another
91 // approach would be to split this into a mutable part that's passed by pointer
92 // but contains no pointers itself and an immutable part that's passed and
93 // returned by value and can contain pointers. We could potentially hide that
94 // we're doing that in trivial methods that are inlined into the caller that has
95 // the stack allocation, but that's fragile.
96 type unwinder struct {
97 // frame is the current physical stack frame, or all 0s if
98 // there is no frame.
99 frame stkframe
100
101 // g is the G who's stack is being unwound. If the
102 // unwindJumpStack flag is set and the unwinder jumps stacks,
103 // this will be different from the initial G.
104 g guintptr
105
106 // cgoCtxt is the index into g.cgoCtxt of the next frame on the cgo stack.
107 // The cgo stack is unwound in tandem with the Go stack as we find marker frames.
108 cgoCtxt int
109
110 // calleeFuncID is the function ID of the caller of the current
111 // frame.
112 calleeFuncID abi.FuncID
113
114 // flags are the flags to this unwind. Some of these are updated as we
115 // unwind (see the flags documentation).
116 flags unwindFlags
117 }
118
119 // init initializes u to start unwinding gp's stack and positions the
120 // iterator on gp's innermost frame. gp must not be the current G.
121 //
122 // A single unwinder can be reused for multiple unwinds.
123 func (u *unwinder) init(gp *g, flags unwindFlags) {
124 // Implementation note: This starts the iterator on the first frame and we
125 // provide a "valid" method. Alternatively, this could start in a "before
126 // the first frame" state and "next" could return whether it was able to
127 // move to the next frame, but that's both more awkward to use in a "for"
128 // loop and is harder to implement because we have to do things differently
129 // for the first frame.
130 u.initAt(^uintptr(0), ^uintptr(0), ^uintptr(0), gp, flags)
131 }
132
133 func (u *unwinder) initAt(pc0, sp0, lr0 uintptr, gp *g, flags unwindFlags) {
134 // Don't call this "g"; it's too easy get "g" and "gp" confused.
135 if ourg := getg(); ourg == gp && ourg == ourg.m.curg {
136 // The starting sp has been passed in as a uintptr, and the caller may
137 // have other uintptr-typed stack references as well.
138 // If during one of the calls that got us here or during one of the
139 // callbacks below the stack must be grown, all these uintptr references
140 // to the stack will not be updated, and traceback will continue
141 // to inspect the old stack memory, which may no longer be valid.
142 // Even if all the variables were updated correctly, it is not clear that
143 // we want to expose a traceback that begins on one stack and ends
144 // on another stack. That could confuse callers quite a bit.
145 // Instead, we require that initAt and any other function that
146 // accepts an sp for the current goroutine (typically obtained by
147 // calling GetCallerSP) must not run on that goroutine's stack but
148 // instead on the g0 stack.
149 throw("cannot trace user goroutine on its own stack")
150 }
151
152 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
153 if gp.syscallsp != 0 {
154 pc0 = gp.syscallpc
155 sp0 = gp.syscallsp
156 if usesLR {
157 lr0 = 0
158 }
159 } else {
160 pc0 = gp.sched.pc
161 sp0 = gp.sched.sp
162 if usesLR {
163 lr0 = gp.sched.lr
164 }
165 }
166 }
167
168 var frame stkframe
169 frame.pc = pc0
170 frame.sp = sp0
171 if usesLR {
172 frame.lr = lr0
173 }
174
175 // If the PC is zero, it's likely a nil function call.
176 // Start in the caller's frame.
177 if frame.pc == 0 {
178 if usesLR {
179 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
180 frame.lr = 0
181 } else {
182 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
183 frame.sp += goarch.PtrSize
184 }
185 }
186
187 // internal/runtime/atomic functions call into kernel helpers on
188 // arm < 7. See internal/runtime/atomic/sys_linux_arm.s.
189 //
190 // Start in the caller's frame.
191 if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && frame.pc&0xffff0000 == 0xffff0000 {
192 // Note that the calls are simple BL without pushing the return
193 // address, so we use LR directly.
194 //
195 // The kernel helpers are frameless leaf functions, so SP and
196 // LR are not touched.
197 frame.pc = frame.lr
198 frame.lr = 0
199 }
200
201 f := findfunc(frame.pc)
202 if !f.valid() {
203 if flags&unwindSilentErrors == 0 {
204 print("runtime: g ", gp.goid, " gp=", gp, ": unknown pc ", hex(frame.pc), "\n")
205 tracebackHexdump(gp.stack, &frame, 0)
206 }
207 if flags&(unwindPrintErrors|unwindSilentErrors) == 0 {
208 throw("unknown pc")
209 }
210 *u = unwinder{}
211 return
212 }
213 frame.fn = f
214
215 // Populate the unwinder.
216 *u = unwinder{
217 frame: frame,
218 g: gp.guintptr(),
219 cgoCtxt: len(gp.cgoCtxt) - 1,
220 calleeFuncID: abi.FuncIDNormal,
221 flags: flags,
222 }
223
224 isSyscall := frame.pc == pc0 && frame.sp == sp0 && pc0 == gp.syscallpc && sp0 == gp.syscallsp
225 u.resolveInternal(true, isSyscall)
226 }
227
228 func (u *unwinder) valid() bool {
229 return u.frame.pc != 0
230 }
231
232 // resolveInternal fills in u.frame based on u.frame.fn, pc, and sp.
233 //
234 // innermost indicates that this is the first resolve on this stack. If
235 // innermost is set, isSyscall indicates that the PC/SP was retrieved from
236 // gp.syscall*; this is otherwise ignored.
237 //
238 // On entry, u.frame contains:
239 // - fn is the running function.
240 // - pc is the PC in the running function.
241 // - sp is the stack pointer at that program counter.
242 // - For the innermost frame on LR machines, lr is the program counter that called fn.
243 //
244 // On return, u.frame contains:
245 // - fp is the stack pointer of the caller.
246 // - lr is the program counter that called fn.
247 // - varp, argp, and continpc are populated for the current frame.
248 //
249 // If fn is a stack-jumping function, resolveInternal can change the entire
250 // frame state to follow that stack jump.
251 //
252 // This is internal to unwinder.
253 func (u *unwinder) resolveInternal(innermost, isSyscall bool) {
254 frame := &u.frame
255 gp := u.g.ptr()
256
257 f := frame.fn
258 if f.pcsp == 0 {
259 // No frame information, must be external function, like race support.
260 // See golang.org/issue/13568.
261 u.finishInternal()
262 return
263 }
264
265 // Compute function info flags.
266 flag := f.flag
267 if f.funcID == abi.FuncID_cgocallback {
268 // cgocallback does write SP to switch from the g0 to the curg stack,
269 // but it carefully arranges that during the transition BOTH stacks
270 // have cgocallback frame valid for unwinding through.
271 // So we don't need to exclude it with the other SP-writing functions.
272 flag &^= abi.FuncFlagSPWrite
273 }
274 if isSyscall {
275 // Some Syscall functions write to SP, but they do so only after
276 // saving the entry PC/SP using entersyscall.
277 // Since we are using the entry PC/SP, the later SP write doesn't matter.
278 flag &^= abi.FuncFlagSPWrite
279 }
280
281 // Found an actual function.
282 // Derive frame pointer.
283 if frame.fp == 0 {
284 // Jump over system stack transitions. If we're on g0 and there's a user
285 // goroutine, try to jump. Otherwise this is a regular call.
286 // We also defensively check that this won't switch M's on us,
287 // which could happen at critical points in the scheduler.
288 // This ensures gp.m doesn't change from a stack jump.
289 if u.flags&unwindJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil && gp.m.curg.m == gp.m {
290 switch f.funcID {
291 case abi.FuncID_morestack:
292 // morestack does not return normally -- newstack()
293 // gogo's to curg.sched. Match that.
294 // This keeps morestack() from showing up in the backtrace,
295 // but that makes some sense since it'll never be returned
296 // to.
297 gp = gp.m.curg
298 u.g.set(gp)
299 frame.pc = gp.sched.pc
300 frame.fn = findfunc(frame.pc)
301 f = frame.fn
302 flag = f.flag
303 frame.lr = gp.sched.lr
304 frame.sp = gp.sched.sp
305 u.cgoCtxt = len(gp.cgoCtxt) - 1
306 case abi.FuncID_systemstack:
307 // systemstack returns normally, so just follow the
308 // stack transition.
309 if usesLR && funcspdelta(f, frame.pc) == 0 {
310 // We're at the function prologue and the stack
311 // switch hasn't happened, or epilogue where we're
312 // about to return. Just unwind normally.
313 // Do this only on LR machines because on x86
314 // systemstack doesn't have an SP delta (the CALL
315 // instruction opens the frame), therefore no way
316 // to check.
317 flag &^= abi.FuncFlagSPWrite
318 break
319 }
320 gp = gp.m.curg
321 u.g.set(gp)
322 frame.sp = gp.sched.sp
323 u.cgoCtxt = len(gp.cgoCtxt) - 1
324 flag &^= abi.FuncFlagSPWrite
325 }
326 }
327 frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc))
328 if !usesLR {
329 // On x86, call instruction pushes return PC before entering new function.
330 frame.fp += goarch.PtrSize
331 }
332 }
333
334 // Derive link register.
335 if flag&abi.FuncFlagTopFrame != 0 {
336 // This function marks the top of the stack. Stop the traceback.
337 frame.lr = 0
338 } else if flag&abi.FuncFlagSPWrite != 0 && (!innermost || u.flags&(unwindPrintErrors|unwindSilentErrors) != 0) {
339 // The function we are in does a write to SP that we don't know
340 // how to encode in the spdelta table. Examples include context
341 // switch routines like runtime.gogo but also any code that switches
342 // to the g0 stack to run host C code.
343 // We can't reliably unwind the SP (we might not even be on
344 // the stack we think we are), so stop the traceback here.
345 //
346 // The one exception (encoded in the complex condition above) is that
347 // we assume if we're doing a precise traceback, and this is the
348 // innermost frame, that the SPWRITE function voluntarily preempted itself on entry
349 // during the stack growth check. In that case, the function has
350 // not yet had a chance to do any writes to SP and is safe to unwind.
351 // isAsyncSafePoint does not allow assembly functions to be async preempted,
352 // and preemptPark double-checks that SPWRITE functions are not async preempted.
353 // So for GC stack traversal, we can safely ignore SPWRITE for the innermost frame,
354 // but farther up the stack we'd better not find any.
355 // This is somewhat imprecise because we're just guessing that we're in the stack
356 // growth check. It would be better if SPWRITE were encoded in the spdelta
357 // table so we would know for sure that we were still in safe code.
358 //
359 // uSE uPE inn | action
360 // T _ _ | frame.lr = 0
361 // F T _ | frame.lr = 0
362 // F F F | print; panic
363 // F F T | ignore SPWrite
364 if u.flags&(unwindPrintErrors|unwindSilentErrors) == 0 && !innermost {
365 println("traceback: unexpected SPWRITE function", funcname(f))
366 throw("traceback")
367 }
368 frame.lr = 0
369 } else {
370 var lrPtr uintptr
371 if usesLR {
372 if innermost && frame.sp < frame.fp || frame.lr == 0 {
373 lrPtr = frame.sp
374 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
375 }
376 } else {
377 if frame.lr == 0 {
378 lrPtr = frame.fp - goarch.PtrSize
379 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
380 }
381 }
382 }
383
384 frame.varp = frame.fp
385 if !usesLR {
386 // On x86, call instruction pushes return PC before entering new function.
387 frame.varp -= goarch.PtrSize
388 }
389
390 // For architectures with frame pointers, if there's
391 // a frame, then there's a saved frame pointer here.
392 //
393 // NOTE: This code is not as general as it looks.
394 // On x86, the ABI is to save the frame pointer word at the
395 // top of the stack frame, so we have to back down over it.
396 // On arm64, the frame pointer should be at the bottom of
397 // the stack (with R29 (aka FP) = RSP), in which case we would
398 // not want to do the subtraction here. But we started out without
399 // any frame pointer, and when we wanted to add it, we didn't
400 // want to break all the assembly doing direct writes to 8(RSP)
401 // to set the first parameter to a called function.
402 // So we decided to write the FP link *below* the stack pointer
403 // (with R29 = RSP - 8 in Go functions).
404 // This is technically ABI-compatible but not standard.
405 // And it happens to end up mimicking the x86 layout.
406 // Other architectures may make different decisions.
407 if frame.varp > frame.sp && framepointer_enabled {
408 frame.varp -= goarch.PtrSize
409 }
410
411 frame.argp = frame.fp + sys.MinFrameSize
412
413 // Determine frame's 'continuation PC', where it can continue.
414 // Normally this is the return address on the stack, but if sigpanic
415 // is immediately below this function on the stack, then the frame
416 // stopped executing due to a trap, and frame.pc is probably not
417 // a safe point for looking up liveness information. In this panicking case,
418 // the function either doesn't return at all (if it has no defers or if the
419 // defers do not recover) or it returns from one of the calls to
420 // deferproc a second time (if the corresponding deferred func recovers).
421 // In the latter case, use a deferreturn call site as the continuation pc.
422 frame.continpc = frame.pc
423 if u.calleeFuncID == abi.FuncID_sigpanic {
424 if frame.fn.deferreturn != 0 {
425 frame.continpc = frame.fn.entry() + uintptr(frame.fn.deferreturn) + 1
426 // Note: this may perhaps keep return variables alive longer than
427 // strictly necessary, as we are using "function has a defer statement"
428 // as a proxy for "function actually deferred something". It seems
429 // to be a minor drawback. (We used to actually look through the
430 // gp._defer for a defer corresponding to this function, but that
431 // is hard to do with defer records on the stack during a stack copy.)
432 // Note: the +1 is to offset the -1 that
433 // (*stkframe).getStackMap does to back up a return
434 // address make sure the pc is in the CALL instruction.
435 } else {
436 frame.continpc = 0
437 }
438 }
439 }
440
441 func isInjectedCall(id abi.FuncID) bool {
442 return id == abi.FuncID_sigpanic || id == abi.FuncID_asyncPreempt || id == abi.FuncID_debugCallV2
443 }
444
445 func (u *unwinder) next() {
446 frame := &u.frame
447 f := frame.fn
448 gp := u.g.ptr()
449
450 // Do not unwind past the bottom of the stack.
451 if frame.lr == 0 {
452 u.finishInternal()
453 return
454 }
455 flr := findfunc(frame.lr)
456 if !flr.valid() {
457 // This happens if you get a profiling interrupt at just the wrong time.
458 // In that context it is okay to stop early.
459 // But if no error flags are set, we're doing a garbage collection and must
460 // get everything, so crash loudly.
461 fail := u.flags&(unwindPrintErrors|unwindSilentErrors) == 0
462 doPrint := u.flags&unwindSilentErrors == 0
463 if doPrint && gp.m.incgo && f.funcID == abi.FuncID_sigpanic {
464 // We can inject sigpanic
465 // calls directly into C code,
466 // in which case we'll see a C
467 // return PC. Don't complain.
468 doPrint = false
469 }
470 if fail || doPrint {
471 print("runtime: g ", gp.goid, ": unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
472 tracebackHexdump(gp.stack, frame, 0)
473 }
474 if fail {
475 throw("unknown caller pc")
476 }
477 frame.lr = 0
478 u.finishInternal()
479 return
480 }
481
482 if frame.pc == frame.lr && frame.sp == frame.fp {
483 // If the next frame is identical to the current frame, we cannot make progress.
484 print("runtime: traceback stuck. pc=", hex(frame.pc), " sp=", hex(frame.sp), "\n")
485 tracebackHexdump(gp.stack, frame, frame.sp)
486 throw("traceback stuck")
487 }
488
489 injectedCall := isInjectedCall(f.funcID)
490 if injectedCall {
491 u.flags |= unwindTrap
492 } else {
493 u.flags &^= unwindTrap
494 }
495
496 // Unwind to next frame.
497 u.calleeFuncID = f.funcID
498 frame.fn = flr
499 frame.pc = frame.lr
500 frame.lr = 0
501 frame.sp = frame.fp
502 frame.fp = 0
503
504 // On link register architectures, sighandler saves the LR on stack
505 // before faking a call.
506 if usesLR && injectedCall {
507 x := *(*uintptr)(unsafe.Pointer(frame.sp))
508 // same as the size bump used in scanframeworker.
509 frame.sp += alignUp(sys.MinFrameSize, sys.StackAlign)
510 f = findfunc(frame.pc)
511 frame.fn = f
512 if !f.valid() {
513 frame.pc = x
514 } else if funcspdelta(f, frame.pc) == 0 {
515 frame.lr = x
516 }
517 }
518
519 u.resolveInternal(false, false)
520 }
521
522 // finishInternal is an unwinder-internal helper called after the stack has been
523 // exhausted. It sets the unwinder to an invalid state and checks that it
524 // successfully unwound the entire stack.
525 func (u *unwinder) finishInternal() {
526 u.frame.pc = 0
527
528 // Note that panic != nil is okay here: there can be leftover panics,
529 // because the defers on the panic stack do not nest in frame order as
530 // they do on the defer stack. If you have:
531 //
532 // frame 1 defers d1
533 // frame 2 defers d2
534 // frame 3 defers d3
535 // frame 4 panics
536 // frame 4's panic starts running defers
537 // frame 5, running d3, defers d4
538 // frame 5 panics
539 // frame 5's panic starts running defers
540 // frame 6, running d4, garbage collects
541 // frame 6, running d2, garbage collects
542 //
543 // During the execution of d4, the panic stack is d4 -> d3, which
544 // is nested properly, and we'll treat frame 3 as resumable, because we
545 // can find d3. (And in fact frame 3 is resumable. If d4 recovers
546 // and frame 5 continues running, d3, d3 can recover and we'll
547 // resume execution in (returning from) frame 3.)
548 //
549 // During the execution of d2, however, the panic stack is d2 -> d3,
550 // which is inverted. The scan will match d2 to frame 2 but having
551 // d2 on the stack until then means it will not match d3 to frame 3.
552 // This is okay: if we're running d2, then all the defers after d2 have
553 // completed and their corresponding frames are dead. Not finding d3
554 // for frame 3 means we'll set frame 3's continpc == 0, which is correct
555 // (frame 3 is dead). At the end of the walk the panic stack can thus
556 // contain defers (d3 in this case) for dead frames. The inversion here
557 // always indicates a dead frame, and the effect of the inversion on the
558 // scan is to hide those dead frames, so the scan is still okay:
559 // what's left on the panic stack are exactly (and only) the dead frames.
560 //
561 // We require callback != nil here because only when callback != nil
562 // do we know that gentraceback is being called in a "must be correct"
563 // context as opposed to a "best effort" context. The tracebacks with
564 // callbacks only happen when everything is stopped nicely.
565 // At other times, such as when gathering a stack for a profiling signal
566 // or when printing a traceback during a crash, everything may not be
567 // stopped nicely, and the stack walk may not be able to complete.
568 gp := u.g.ptr()
569 if u.flags&(unwindPrintErrors|unwindSilentErrors) == 0 && u.frame.sp != gp.stktopsp {
570 print("runtime: g", gp.goid, ": frame.sp=", hex(u.frame.sp), " top=", hex(gp.stktopsp), "\n")
571 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "\n")
572 throw("traceback did not unwind completely")
573 }
574 }
575
576 // symPC returns the PC that should be used for symbolizing the current frame.
577 // Specifically, this is the PC of the last instruction executed in this frame.
578 //
579 // If this frame did a normal call, then frame.pc is a return PC, so this will
580 // return frame.pc-1, which points into the CALL instruction. If the frame was
581 // interrupted by a signal (e.g., profiler, segv, etc) then frame.pc is for the
582 // trapped instruction, so this returns frame.pc. See issue #34123. Finally,
583 // frame.pc can be at function entry when the frame is initialized without
584 // actually running code, like in runtime.mstart, in which case this returns
585 // frame.pc because that's the best we can do.
586 func (u *unwinder) symPC() uintptr {
587 if u.flags&unwindTrap == 0 && u.frame.pc > u.frame.fn.entry() {
588 // Regular call.
589 return u.frame.pc - 1
590 }
591 // Trapping instruction or we're at the function entry point.
592 return u.frame.pc
593 }
594
595 // cgoCallers populates pcBuf with the cgo callers of the current frame using
596 // the registered cgo unwinder. It returns the number of PCs written to pcBuf.
597 // If the current frame is not a cgo frame or if there's no registered cgo
598 // unwinder, it returns 0.
599 func (u *unwinder) cgoCallers(pcBuf []uintptr) int {
600 if !cgoTracebackAvailable() || u.frame.fn.funcID != abi.FuncID_cgocallback || u.cgoCtxt < 0 {
601 // We don't have a cgo unwinder (typical case), or we do but we're not
602 // in a cgo frame or we're out of cgo context.
603 return 0
604 }
605
606 ctxt := u.g.ptr().cgoCtxt[u.cgoCtxt]
607 u.cgoCtxt--
608 cgoContextPCs(ctxt, pcBuf)
609 for i, pc := range pcBuf {
610 if pc == 0 {
611 return i
612 }
613 }
614 return len(pcBuf)
615 }
616
617 // tracebackPCs populates pcBuf with the return addresses for each frame from u
618 // and returns the number of PCs written to pcBuf. The returned PCs correspond
619 // to "logical frames" rather than "physical frames"; that is if A is inlined
620 // into B, this will still return a PCs for both A and B. This also includes PCs
621 // generated by the cgo unwinder, if one is registered.
622 //
623 // If skip != 0, this skips this many logical frames.
624 //
625 // Callers should set the unwindSilentErrors flag on u.
626 func tracebackPCs(u *unwinder, skip int, pcBuf []uintptr) int {
627 var cgoBuf [32]uintptr
628 n := 0
629 for ; n < len(pcBuf) && u.valid(); u.next() {
630 f := u.frame.fn
631 cgoN := u.cgoCallers(cgoBuf[:])
632
633 // TODO: Why does &u.cache cause u to escape? (Same in traceback2)
634 for iu, uf := newInlineUnwinder(f, u.symPC()); n < len(pcBuf) && uf.valid(); uf = iu.next(uf) {
635 sf := iu.srcFunc(uf)
636 if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(u.calleeFuncID) {
637 // ignore wrappers
638 } else if skip > 0 {
639 skip--
640 } else {
641 // Callers expect the pc buffer to contain return addresses
642 // and do the -1 themselves, so we add 1 to the call pc to
643 // create a "return pc". Since there is no actual call, here
644 // "return pc" just means a pc you subtract 1 from to get
645 // the pc of the "call". The actual no-op we insert may or
646 // may not be 1 byte.
647 pcBuf[n] = uf.pc + 1
648 n++
649 }
650 u.calleeFuncID = sf.funcID
651 }
652 // Add cgo frames (if we're done skipping over the requested number of
653 // Go frames).
654 if skip == 0 {
655 n += copy(pcBuf[n:], cgoBuf[:cgoN])
656 }
657 }
658 return n
659 }
660
661 // printArgs prints function arguments in traceback.
662 func printArgs(f funcInfo, argp unsafe.Pointer, pc uintptr) {
663 p := (*[abi.TraceArgsMaxLen]uint8)(funcdata(f, abi.FUNCDATA_ArgInfo))
664 if p == nil {
665 return
666 }
667
668 liveInfo := funcdata(f, abi.FUNCDATA_ArgLiveInfo)
669 liveIdx := pcdatavalue(f, abi.PCDATA_ArgLiveIndex, pc)
670 startOffset := uint8(0xff) // smallest offset that needs liveness info (slots with a lower offset is always live)
671 if liveInfo != nil {
672 startOffset = *(*uint8)(liveInfo)
673 }
674
675 isLive := func(off, slotIdx uint8) bool {
676 if liveInfo == nil || liveIdx <= 0 {
677 return true // no liveness info, always live
678 }
679 if off < startOffset {
680 return true
681 }
682 bits := *(*uint8)(add(liveInfo, uintptr(liveIdx)+uintptr(slotIdx/8)))
683 return bits&(1<<(slotIdx%8)) != 0
684 }
685
686 print1 := func(off, sz, slotIdx uint8) {
687 x := readUnaligned64(add(argp, uintptr(off)))
688 // mask out irrelevant bits
689 if sz < 8 {
690 shift := 64 - sz*8
691 if goarch.BigEndian {
692 x = x >> shift
693 } else {
694 x = x << shift >> shift
695 }
696 }
697 print(hex(x))
698 if !isLive(off, slotIdx) {
699 print("?")
700 }
701 }
702
703 start := true
704 printcomma := func() {
705 if !start {
706 print(", ")
707 }
708 }
709 pi := 0
710 slotIdx := uint8(0) // register arg spill slot index
711 printloop:
712 for {
713 o := p[pi]
714 pi++
715 switch o {
716 case abi.TraceArgsEndSeq:
717 break printloop
718 case abi.TraceArgsStartAgg:
719 printcomma()
720 print("{")
721 start = true
722 continue
723 case abi.TraceArgsEndAgg:
724 print("}")
725 case abi.TraceArgsDotdotdot:
726 printcomma()
727 print("...")
728 case abi.TraceArgsOffsetTooLarge:
729 printcomma()
730 print("_")
731 default:
732 printcomma()
733 sz := p[pi]
734 pi++
735 print1(o, sz, slotIdx)
736 if o >= startOffset {
737 slotIdx++
738 }
739 }
740 start = false
741 }
742 }
743
744 // funcNamePiecesForPrint returns the function name for printing to the user.
745 // It returns three pieces so it doesn't need an allocation for string
746 // concatenation.
747 func funcNamePiecesForPrint(name string) (string, string, string) {
748 // Replace the shape name in generic function with "...".
749 i := bytealg.IndexByteString(name, '[')
750 if i < 0 {
751 return name, "", ""
752 }
753 j := len(name) - 1
754 for name[j] != ']' {
755 j--
756 }
757 if j <= i {
758 return name, "", ""
759 }
760 return name[:i], "[...]", name[j+1:]
761 }
762
763 // funcNameForPrint returns the function name for printing to the user.
764 func funcNameForPrint(name string) string {
765 a, b, c := funcNamePiecesForPrint(name)
766 return a + b + c
767 }
768
769 // printFuncName prints a function name. name is the function name in
770 // the binary's func data table.
771 func printFuncName(name string) {
772 if name == "runtime.gopanic" {
773 print("panic")
774 return
775 }
776 a, b, c := funcNamePiecesForPrint(name)
777 print(a, b, c)
778 }
779
780 func printcreatedby(gp *g) {
781 // Show what created goroutine, except main goroutine (goid 1).
782 pc := gp.gopc
783 f := findfunc(pc)
784 if f.valid() && showframe(f.srcFunc(), gp, false, abi.FuncIDNormal) && gp.goid != 1 {
785 printcreatedby1(f, pc, gp.parentGoid)
786 }
787 }
788
789 func printcreatedby1(f funcInfo, pc uintptr, goid uint64) {
790 print("created by ")
791 printFuncName(funcname(f))
792 if goid != 0 {
793 print(" in goroutine ", goid)
794 }
795 print("\n")
796 tracepc := pc // back up to CALL instruction for funcline.
797 if pc > f.entry() {
798 tracepc -= sys.PCQuantum
799 }
800 file, line := funcline(f, tracepc)
801 print("\t", file, ":", line)
802 if pc > f.entry() {
803 print(" +", hex(pc-f.entry()))
804 }
805 print("\n")
806 }
807
808 func traceback(pc, sp, lr uintptr, gp *g) {
809 traceback1(pc, sp, lr, gp, 0)
810 }
811
812 // tracebacktrap is like traceback but expects that the PC and SP were obtained
813 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or GetCallerPC/GetCallerSP.
814 // Because they are from a trap instead of from a saved pair,
815 // the initial PC must not be rewound to the previous instruction.
816 // (All the saved pairs record a PC that is a return address, so we
817 // rewind it into the CALL instruction.)
818 // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
819 // the pc/sp/lr passed in.
820 func tracebacktrap(pc, sp, lr uintptr, gp *g) {
821 if gp.m.libcallsp != 0 {
822 // We're in C code somewhere, traceback from the saved position.
823 traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
824 return
825 }
826 traceback1(pc, sp, lr, gp, unwindTrap)
827 }
828
829 func traceback1(pc, sp, lr uintptr, gp *g, flags unwindFlags) {
830 // If the goroutine is in cgo, and we have a cgo traceback, print that.
831 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
832 // Lock cgoCallers so that a signal handler won't
833 // change it, copy the array, reset it, unlock it.
834 // We are locked to the thread and are not running
835 // concurrently with a signal handler.
836 // We just have to stop a signal handler from interrupting
837 // in the middle of our copy.
838 gp.m.cgoCallersUse.Store(1)
839 cgoCallers := *gp.m.cgoCallers
840 gp.m.cgoCallers[0] = 0
841 gp.m.cgoCallersUse.Store(0)
842
843 printCgoTraceback(&cgoCallers)
844 }
845
846 if readgstatus(gp)&^_Gscan == _Gsyscall {
847 // Override registers if blocked in system call.
848 pc = gp.syscallpc
849 sp = gp.syscallsp
850 flags &^= unwindTrap
851 }
852 if gp.m != nil && gp.m.vdsoSP != 0 {
853 // Override registers if running in VDSO. This comes after the
854 // _Gsyscall check to cover VDSO calls after entersyscall.
855 pc = gp.m.vdsoPC
856 sp = gp.m.vdsoSP
857 flags &^= unwindTrap
858 }
859
860 // Print traceback.
861 //
862 // We print the first tracebackInnerFrames frames, and the last
863 // tracebackOuterFrames frames. There are many possible approaches to this.
864 // There are various complications to this:
865 //
866 // - We'd prefer to walk the stack once because in really bad situations
867 // traceback may crash (and we want as much output as possible) or the stack
868 // may be changing.
869 //
870 // - Each physical frame can represent several logical frames, so we might
871 // have to pause in the middle of a physical frame and pick up in the middle
872 // of a physical frame.
873 //
874 // - The cgo symbolizer can expand a cgo PC to more than one logical frame,
875 // and involves juggling state on the C side that we don't manage. Since its
876 // expansion state is managed on the C side, we can't capture the expansion
877 // state part way through, and because the output strings are managed on the
878 // C side, we can't capture the output. Thus, our only choice is to replay a
879 // whole expansion, potentially discarding some of it.
880 //
881 // Rejected approaches:
882 //
883 // - Do two passes where the first pass just counts and the second pass does
884 // all the printing. This is undesirable if the stack is corrupted or changing
885 // because we won't see a partial stack if we panic.
886 //
887 // - Keep a ring buffer of the last N logical frames and use this to print
888 // the bottom frames once we reach the end of the stack. This works, but
889 // requires keeping a surprising amount of state on the stack, and we have
890 // to run the cgo symbolizer twice—once to count frames, and a second to
891 // print them—since we can't retain the strings it returns.
892 //
893 // Instead, we print the outer frames, and if we reach that limit, we clone
894 // the unwinder, count the remaining frames, and then skip forward and
895 // finish printing from the clone. This makes two passes over the outer part
896 // of the stack, but the single pass over the inner part ensures that's
897 // printed immediately and not revisited. It keeps minimal state on the
898 // stack. And through a combination of skip counts and limits, we can do all
899 // of the steps we need with a single traceback printer implementation.
900 //
901 // We could be more lax about exactly how many frames we print, for example
902 // always stopping and resuming on physical frame boundaries, or at least
903 // cgo expansion boundaries. It's not clear that's much simpler.
904 flags |= unwindPrintErrors
905 var u unwinder
906 tracebackWithRuntime := func(showRuntime bool) int {
907 const maxInt int = 0x7fffffff
908 u.initAt(pc, sp, lr, gp, flags)
909 n, lastN := traceback2(&u, showRuntime, 0, tracebackInnerFrames)
910 if n < tracebackInnerFrames {
911 // We printed the whole stack.
912 return n
913 }
914 // Clone the unwinder and figure out how many frames are left. This
915 // count will include any logical frames already printed for u's current
916 // physical frame.
917 u2 := u
918 remaining, _ := traceback2(&u, showRuntime, maxInt, 0)
919 elide := remaining - lastN - tracebackOuterFrames
920 if elide > 0 {
921 print("...", elide, " frames elided...\n")
922 traceback2(&u2, showRuntime, lastN+elide, tracebackOuterFrames)
923 } else if elide <= 0 {
924 // There are tracebackOuterFrames or fewer frames left to print.
925 // Just print the rest of the stack.
926 traceback2(&u2, showRuntime, lastN, tracebackOuterFrames)
927 }
928 return n
929 }
930 // By default, omits runtime frames. If that means we print nothing at all,
931 // repeat forcing all frames printed.
932 if tracebackWithRuntime(false) == 0 {
933 tracebackWithRuntime(true)
934 }
935 printcreatedby(gp)
936
937 if gp.ancestors == nil {
938 return
939 }
940 for _, ancestor := range *gp.ancestors {
941 printAncestorTraceback(ancestor)
942 }
943 }
944
945 // traceback2 prints a stack trace starting at u. It skips the first "skip"
946 // logical frames, after which it prints at most "max" logical frames. It
947 // returns n, which is the number of logical frames skipped and printed, and
948 // lastN, which is the number of logical frames skipped or printed just in the
949 // physical frame that u references.
950 func traceback2(u *unwinder, showRuntime bool, skip, max int) (n, lastN int) {
951 // commitFrame commits to a logical frame and returns whether this frame
952 // should be printed and whether iteration should stop.
953 commitFrame := func() (pr, stop bool) {
954 if skip == 0 && max == 0 {
955 // Stop
956 return false, true
957 }
958 n++
959 lastN++
960 if skip > 0 {
961 // Skip
962 skip--
963 return false, false
964 }
965 // Print
966 max--
967 return true, false
968 }
969
970 gp := u.g.ptr()
971 level, _, _ := gotraceback()
972 var cgoBuf [32]uintptr
973 for ; u.valid(); u.next() {
974 lastN = 0
975 f := u.frame.fn
976 for iu, uf := newInlineUnwinder(f, u.symPC()); uf.valid(); uf = iu.next(uf) {
977 sf := iu.srcFunc(uf)
978 callee := u.calleeFuncID
979 u.calleeFuncID = sf.funcID
980 if !(showRuntime || showframe(sf, gp, n == 0, callee)) {
981 continue
982 }
983
984 if pr, stop := commitFrame(); stop {
985 return
986 } else if !pr {
987 continue
988 }
989
990 name := sf.name()
991 file, line := iu.fileLine(uf)
992 // Print during crash.
993 // main(0x1, 0x2, 0x3)
994 // /home/rsc/go/src/runtime/x.go:23 +0xf
995 //
996 printFuncName(name)
997 print("(")
998 if iu.isInlined(uf) {
999 print("...")
1000 } else {
1001 argp := unsafe.Pointer(u.frame.argp)
1002 printArgs(f, argp, u.symPC())
1003 }
1004 print(")\n")
1005 print("\t", file, ":", line)
1006 if !iu.isInlined(uf) {
1007 if u.frame.pc > f.entry() {
1008 print(" +", hex(u.frame.pc-f.entry()))
1009 }
1010 if gp.m != nil && gp.m.throwing >= throwTypeRuntime && gp == gp.m.curg || level >= 2 {
1011 print(" fp=", hex(u.frame.fp), " sp=", hex(u.frame.sp), " pc=", hex(u.frame.pc))
1012 }
1013 }
1014 print("\n")
1015 }
1016
1017 // Print cgo frames.
1018 if cgoN := u.cgoCallers(cgoBuf[:]); cgoN > 0 {
1019 var arg cgoSymbolizerArg
1020 anySymbolized := false
1021 stop := false
1022 for _, pc := range cgoBuf[:cgoN] {
1023 if !cgoSymbolizerAvailable() {
1024 if pr, stop := commitFrame(); stop {
1025 break
1026 } else if pr {
1027 print("non-Go function at pc=", hex(pc), "\n")
1028 }
1029 } else {
1030 stop = printOneCgoTraceback(pc, commitFrame, &arg)
1031 anySymbolized = true
1032 if stop {
1033 break
1034 }
1035 }
1036 }
1037 if anySymbolized {
1038 // Free symbolization state.
1039 arg.pc = 0
1040 callCgoSymbolizer(&arg)
1041 }
1042 if stop {
1043 return
1044 }
1045 }
1046 }
1047 return n, 0
1048 }
1049
1050 // printAncestorTraceback prints the traceback of the given ancestor.
1051 // TODO: Unify this with gentraceback and CallersFrames.
1052 func printAncestorTraceback(ancestor ancestorInfo) {
1053 print("[originating from goroutine ", ancestor.goid, "]:\n")
1054 for fidx, pc := range ancestor.pcs {
1055 f := findfunc(pc) // f previously validated
1056 if showfuncinfo(f.srcFunc(), fidx == 0, abi.FuncIDNormal) {
1057 printAncestorTracebackFuncInfo(f, pc)
1058 }
1059 }
1060 if len(ancestor.pcs) == tracebackInnerFrames {
1061 print("...additional frames elided...\n")
1062 }
1063 // Show what created goroutine, except main goroutine (goid 1).
1064 f := findfunc(ancestor.gopc)
1065 if f.valid() && showfuncinfo(f.srcFunc(), false, abi.FuncIDNormal) && ancestor.goid != 1 {
1066 // In ancestor mode, we'll already print the goroutine ancestor.
1067 // Pass 0 for the goid parameter so we don't print it again.
1068 printcreatedby1(f, ancestor.gopc, 0)
1069 }
1070 }
1071
1072 // printAncestorTracebackFuncInfo prints the given function info at a given pc
1073 // within an ancestor traceback. The precision of this info is reduced
1074 // due to only have access to the pcs at the time of the caller
1075 // goroutine being created.
1076 func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
1077 u, uf := newInlineUnwinder(f, pc)
1078 file, line := u.fileLine(uf)
1079 printFuncName(u.srcFunc(uf).name())
1080 print("(...)\n")
1081 print("\t", file, ":", line)
1082 if pc > f.entry() {
1083 print(" +", hex(pc-f.entry()))
1084 }
1085 print("\n")
1086 }
1087
1088 // callers should be an internal detail,
1089 // (and is almost identical to Callers),
1090 // but widely used packages access it using linkname.
1091 // Notable members of the hall of shame include:
1092 // - github.com/phuslu/log
1093 //
1094 // Do not remove or change the type signature.
1095 // See go.dev/issue/67401.
1096 //
1097 //go:linkname callers
1098 func callers(skip int, pcbuf []uintptr) int {
1099 sp := sys.GetCallerSP()
1100 pc := sys.GetCallerPC()
1101 gp := getg()
1102 var n int
1103 systemstack(func() {
1104 var u unwinder
1105 u.initAt(pc, sp, 0, gp, unwindSilentErrors)
1106 n = tracebackPCs(&u, skip, pcbuf)
1107 })
1108 return n
1109 }
1110
1111 func gcallers(gp *g, skip int, pcbuf []uintptr) int {
1112 var u unwinder
1113 u.init(gp, unwindSilentErrors)
1114 return tracebackPCs(&u, skip, pcbuf)
1115 }
1116
1117 // showframe reports whether the frame with the given characteristics should
1118 // be printed during a traceback.
1119 func showframe(sf srcFunc, gp *g, firstFrame bool, calleeID abi.FuncID) bool {
1120 mp := getg().m
1121 if mp.throwing >= throwTypeRuntime && gp != nil && (gp == mp.curg || gp == mp.caughtsig.ptr()) {
1122 return true
1123 }
1124 return showfuncinfo(sf, firstFrame, calleeID)
1125 }
1126
1127 // showfuncinfo reports whether a function with the given characteristics should
1128 // be printed during a traceback.
1129 func showfuncinfo(sf srcFunc, firstFrame bool, calleeID abi.FuncID) bool {
1130 level, _, _ := gotraceback()
1131 if level > 1 {
1132 // Show all frames.
1133 return true
1134 }
1135
1136 if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(calleeID) {
1137 return false
1138 }
1139
1140 // Always show runtime.runFinalizers and runtime.runCleanups as
1141 // context that this goroutine is running finalizers or cleanups,
1142 // otherwise there is no obvious indicator.
1143 //
1144 // TODO(prattmic): A more general approach would be to always show the
1145 // outermost frame (besides runtime.goexit), even if it is a runtime.
1146 // Hiding the outermost frame allows the apparent outermost frame to
1147 // change across different traces, which seems impossible.
1148 //
1149 // Unfortunately, implementing this requires looking ahead at the next
1150 // frame, which goes against traceback's incremental approach (see big
1151 // comment in traceback1).
1152 if sf.funcID == abi.FuncID_runFinalizers || sf.funcID == abi.FuncID_runCleanups {
1153 return true
1154 }
1155
1156 name := sf.name()
1157
1158 // Special case: always show runtime.gopanic frame
1159 // in the middle of a stack trace, so that we can
1160 // see the boundary between ordinary code and
1161 // panic-induced deferred code.
1162 // See golang.org/issue/5832.
1163 if name == "runtime.gopanic" && !firstFrame {
1164 return true
1165 }
1166
1167 return bytealg.IndexByteString(name, '.') >= 0 && (!stringslite.HasPrefix(name, "runtime.") || isExportedRuntime(name))
1168 }
1169
1170 // isExportedRuntime reports whether name is an exported runtime function.
1171 // It is only for runtime functions, so ASCII A-Z is fine.
1172 func isExportedRuntime(name string) bool {
1173 // Check and remove package qualifier.
1174 name, found := stringslite.CutPrefix(name, "runtime.")
1175 if !found {
1176 return false
1177 }
1178 rcvr := ""
1179
1180 // Extract receiver type, if any.
1181 // For example, runtime.(*Func).Entry
1182 i := len(name) - 1
1183 for i >= 0 && name[i] != '.' {
1184 i--
1185 }
1186 if i >= 0 {
1187 rcvr = name[:i]
1188 name = name[i+1:]
1189 // Remove parentheses and star for pointer receivers.
1190 if len(rcvr) >= 3 && rcvr[0] == '(' && rcvr[1] == '*' && rcvr[len(rcvr)-1] == ')' {
1191 rcvr = rcvr[2 : len(rcvr)-1]
1192 }
1193 }
1194
1195 // Exported functions and exported methods on exported types.
1196 return len(name) > 0 && 'A' <= name[0] && name[0] <= 'Z' && (len(rcvr) == 0 || 'A' <= rcvr[0] && rcvr[0] <= 'Z')
1197 }
1198
1199 // elideWrapperCalling reports whether a wrapper function that called
1200 // function id should be elided from stack traces.
1201 func elideWrapperCalling(id abi.FuncID) bool {
1202 // If the wrapper called a panic function instead of the
1203 // wrapped function, we want to include it in stacks.
1204 return !(id == abi.FuncID_gopanic || id == abi.FuncID_sigpanic || id == abi.FuncID_panicwrap)
1205 }
1206
1207 var gStatusStrings = [...]string{
1208 _Gidle: "idle",
1209 _Grunnable: "runnable",
1210 _Grunning: "running",
1211 _Gsyscall: "syscall",
1212 _Gwaiting: "waiting",
1213 _Gdead: "dead",
1214 _Gcopystack: "copystack",
1215 _Gleaked: "leaked",
1216 _Gpreempted: "preempted",
1217 _Gdeadextra: "waiting for cgo callback",
1218 }
1219
1220 func goroutineheader(gp *g) {
1221 level, _, _ := gotraceback()
1222
1223 gpstatus := readgstatus(gp)
1224
1225 isScan := gpstatus&_Gscan != 0
1226 gpstatus &^= _Gscan // drop the scan bit
1227
1228 // Basic string status
1229 var status string
1230 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
1231 status = gStatusStrings[gpstatus]
1232 } else {
1233 status = "???"
1234 }
1235
1236 // Override.
1237 if (gpstatus == _Gwaiting || gpstatus == _Gleaked) && gp.waitreason != waitReasonZero {
1238 status = gp.waitreason.String()
1239 }
1240
1241 // approx time the G is blocked, in minutes
1242 var waitfor int64
1243 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
1244 waitfor = (nanotime() - gp.waitsince) / 60e9
1245 }
1246 print("goroutine ", gp.goid)
1247 if gp.m != nil && gp.m.throwing >= throwTypeRuntime && gp == gp.m.curg || level >= 2 {
1248 print(" gp=", gp)
1249 if gp.m != nil {
1250 print(" m=", gp.m.id, " mp=", gp.m)
1251 } else {
1252 print(" m=nil")
1253 }
1254 }
1255 print(" [", status)
1256 if gpstatus == _Gleaked {
1257 print(" (leaked)")
1258 }
1259 if isScan {
1260 print(" (scan)")
1261 }
1262 if bubble := gp.bubble; bubble != nil &&
1263 gpstatus == _Gwaiting &&
1264 gp.waitreason.isIdleInSynctest() &&
1265 !stringslite.HasSuffix(status, "(durable)") {
1266 // If this isn't a status where the name includes a (durable)
1267 // suffix to distinguish it from the non-durable form, add it here.
1268 print(" (durable)")
1269 }
1270 if waitfor >= 1 {
1271 print(", ", waitfor, " minutes")
1272 }
1273 if gp.lockedm != 0 {
1274 print(", locked to thread")
1275 }
1276 if bubble := gp.bubble; bubble != nil {
1277 print(", synctest bubble ", bubble.id)
1278 }
1279 if gp.labels != nil && debug.tracebacklabels.Load() == 1 {
1280 labels := (*label.Set)(gp.labels).List
1281 if len(labels) > 0 {
1282 print(" labels:{")
1283 for i, kv := range labels {
1284 print(quoted(kv.Key), ": ", quoted(kv.Value))
1285 if i < len(labels)-1 {
1286 print(", ")
1287 }
1288 }
1289 print("}")
1290 }
1291 }
1292 print("]:\n")
1293 }
1294
1295 func tracebackothers(me *g) {
1296 tracebacksomeothers(me, func(*g) bool { return true })
1297 }
1298
1299 func tracebacksomeothers(me *g, showf func(*g) bool) {
1300 level, _, _ := gotraceback()
1301
1302 // Show the current goroutine first, if we haven't already.
1303 curgp := getg().m.curg
1304 if curgp != nil && curgp != me {
1305 print("\n")
1306 goroutineheader(curgp)
1307 traceback(^uintptr(0), ^uintptr(0), 0, curgp)
1308 }
1309
1310 // We can't call locking forEachG here because this may be during fatal
1311 // throw/panic, where locking could be out-of-order or a direct
1312 // deadlock.
1313 //
1314 // Instead, use forEachGRace, which requires no locking. We don't lock
1315 // against concurrent creation of new Gs, but even with allglock we may
1316 // miss Gs created after this loop.
1317 forEachGRace(func(gp *g) {
1318 if gp == me || gp == curgp {
1319 return
1320 }
1321 if status := readgstatus(gp); status == _Gdead || status == _Gdeadextra {
1322 return
1323 }
1324 if !showf(gp) {
1325 return
1326 }
1327 if isSystemGoroutine(gp, false) && level < 2 {
1328 return
1329 }
1330 print("\n")
1331 goroutineheader(gp)
1332 // Note: gp.m == getg().m occurs when tracebackothers is called
1333 // from a signal handler initiated during a systemstack call.
1334 // The original G is still in the running state, and we want to
1335 // print its stack.
1336 //
1337 // There's a small window of time in exitsyscall where a goroutine could be
1338 // in _Grunning as it's exiting a syscall. This could be the case even if the
1339 // world is stopped or frozen.
1340 //
1341 // This is OK because the goroutine will not exit the syscall while the world
1342 // is stopped or frozen. This is also why it's safe to check syscallsp here,
1343 // and safe to take the goroutine's stack trace. The syscall path mutates
1344 // syscallsp only just before exiting the syscall.
1345 if gp.m != getg().m && readgstatus(gp)&^_Gscan == _Grunning && gp.syscallsp == 0 {
1346 print("\tgoroutine running on other thread; stack unavailable\n")
1347 printcreatedby(gp)
1348 } else {
1349 traceback(^uintptr(0), ^uintptr(0), 0, gp)
1350 }
1351 })
1352 }
1353
1354 // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
1355 // for debugging purposes. If the address bad is included in the
1356 // hexdumped range, it will mark it as well.
1357 func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
1358 const expand = 32 * goarch.PtrSize
1359 const maxExpand = 256 * goarch.PtrSize
1360 // Start around frame.sp.
1361 lo, hi := frame.sp, frame.sp
1362 // Expand to include frame.fp.
1363 if frame.fp != 0 && frame.fp < lo {
1364 lo = frame.fp
1365 }
1366 if frame.fp != 0 && frame.fp > hi {
1367 hi = frame.fp
1368 }
1369 // Expand a bit more.
1370 lo, hi = lo-expand, hi+expand
1371 // But don't go too far from frame.sp.
1372 if lo < frame.sp-maxExpand {
1373 lo = frame.sp - maxExpand
1374 }
1375 if hi > frame.sp+maxExpand {
1376 hi = frame.sp + maxExpand
1377 }
1378 // And don't go outside the stack bounds.
1379 if lo < stk.lo {
1380 lo = stk.lo
1381 }
1382 if hi > stk.hi {
1383 hi = stk.hi
1384 }
1385
1386 // Print the hex dump.
1387 print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
1388 hexdumpWords(lo, hi-lo, func(p uintptr, m hexdumpMarker) {
1389 if p == frame.fp {
1390 m.start()
1391 println("FP")
1392 }
1393 if p == frame.sp {
1394 m.start()
1395 println("SP")
1396 }
1397 if p == bad {
1398 m.start()
1399 println("bad")
1400 }
1401 })
1402 }
1403
1404 // isSystemGoroutine reports whether the goroutine g must be omitted
1405 // in stack dumps and deadlock detector. This is any goroutine that
1406 // starts at a runtime.* entry point, except for runtime.main,
1407 // runtime.handleAsyncEvent (wasm only) and sometimes
1408 // runtime.runFinalizers/runtime.runCleanups.
1409 //
1410 // If fixed is true, any goroutine that can vary between user and
1411 // system (that is, the finalizer goroutine) is considered a user
1412 // goroutine.
1413 func isSystemGoroutine(gp *g, fixed bool) bool {
1414 // Keep this in sync with internal/trace.IsSystemGoroutine.
1415 f := findfunc(gp.startpc)
1416 if !f.valid() {
1417 return false
1418 }
1419 if f.funcID == abi.FuncID_runtime_main || f.funcID == abi.FuncID_corostart || f.funcID == abi.FuncID_handleAsyncEvent {
1420 return false
1421 }
1422 if f.funcID == abi.FuncID_runFinalizers {
1423 // We include the finalizer goroutine if it's calling
1424 // back into user code.
1425 if fixed {
1426 // This goroutine can vary. In fixed mode,
1427 // always consider it a user goroutine.
1428 return false
1429 }
1430 return fingStatus.Load()&fingRunningFinalizer == 0
1431 }
1432 if f.funcID == abi.FuncID_runCleanups {
1433 // We include the cleanup goroutines if they're calling
1434 // back into user code.
1435 if fixed {
1436 // This goroutine can vary. In fixed mode,
1437 // always consider it a user goroutine.
1438 return false
1439 }
1440 return !gp.runningCleanups.Load()
1441 }
1442 return stringslite.HasPrefix(funcname(f), "runtime.")
1443 }
1444
1445 // SetCgoTraceback records three C functions to use to gather
1446 // traceback information from C code and to convert that traceback
1447 // information into symbolic information. These are used when printing
1448 // stack traces for a program that uses cgo.
1449 //
1450 // The traceback and context functions may be called from a signal
1451 // handler, and must therefore use only async-signal safe functions.
1452 // The symbolizer function may be called while the program is
1453 // crashing, and so must be cautious about using memory. None of the
1454 // functions may call back into Go.
1455 //
1456 // The context function will be called with a single argument, a
1457 // pointer to a struct:
1458 //
1459 // struct {
1460 // Context uintptr
1461 // }
1462 //
1463 // In C syntax, this struct will be
1464 //
1465 // struct {
1466 // uintptr_t Context;
1467 // };
1468 //
1469 // If the Context field is 0, the context function is being called to
1470 // record the current traceback context. It should record in the
1471 // Context field whatever information is needed about the current
1472 // point of execution to later produce a stack trace, probably the
1473 // stack pointer and PC. In this case the context function will be
1474 // called from C code.
1475 //
1476 // If the Context field is not 0, then it is a value returned by a
1477 // previous call to the context function. This case is called when the
1478 // context is no longer needed; that is, when the Go code is returning
1479 // to its C code caller. This permits the context function to release
1480 // any associated resources.
1481 //
1482 // While it would be correct for the context function to record a
1483 // complete a stack trace whenever it is called, and simply copy that
1484 // out in the traceback function, in a typical program the context
1485 // function will be called many times without ever recording a
1486 // traceback for that context. Recording a complete stack trace in a
1487 // call to the context function is likely to be inefficient.
1488 //
1489 // The traceback function will be called with a single argument, a
1490 // pointer to a struct:
1491 //
1492 // struct {
1493 // Context uintptr
1494 // SigContext uintptr
1495 // Buf *uintptr
1496 // Max uintptr
1497 // }
1498 //
1499 // In C syntax, this struct will be
1500 //
1501 // struct {
1502 // uintptr_t Context;
1503 // uintptr_t SigContext;
1504 // uintptr_t* Buf;
1505 // uintptr_t Max;
1506 // };
1507 //
1508 // The Context field will be zero to gather a traceback from the
1509 // current program execution point. In this case, the traceback
1510 // function will be called from C code.
1511 //
1512 // Otherwise Context will be a value previously returned by a call to
1513 // the context function. The traceback function should gather a stack
1514 // trace from that saved point in the program execution. The traceback
1515 // function may be called from an execution thread other than the one
1516 // that recorded the context, but only when the context is known to be
1517 // valid and unchanging. The traceback function may also be called
1518 // deeper in the call stack on the same thread that recorded the
1519 // context. The traceback function may be called multiple times with
1520 // the same Context value; it will usually be appropriate to cache the
1521 // result, if possible, the first time this is called for a specific
1522 // context value.
1523 //
1524 // If the traceback function is called from a signal handler on a Unix
1525 // system, SigContext will be the signal context argument passed to
1526 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
1527 // used to start tracing at the point where the signal occurred. If
1528 // the traceback function is not called from a signal handler,
1529 // SigContext will be zero.
1530 //
1531 // Buf is where the traceback information should be stored. It should
1532 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
1533 // the PC of that function's caller, and so on. Max is the maximum
1534 // number of entries to store. The function should store a zero to
1535 // indicate the top of the stack, or that the caller is on a different
1536 // stack, presumably a Go stack.
1537 //
1538 // Unlike runtime.Callers, the PC values returned should, when passed
1539 // to the symbolizer function, return the file/line of the call
1540 // instruction. No additional subtraction is required or appropriate.
1541 //
1542 // On all platforms, the traceback function is invoked when a call from
1543 // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
1544 // linux/arm64, and freebsd/amd64, the traceback function is also invoked
1545 // when a signal is received by a thread that is executing a cgo call.
1546 // The traceback function should not make assumptions about when it is
1547 // called, as future versions of Go may make additional calls.
1548 //
1549 // The symbolizer function will be called with a single argument, a
1550 // pointer to a struct:
1551 //
1552 // struct {
1553 // PC uintptr // program counter to fetch information for
1554 // File *byte // file name (NUL terminated)
1555 // Lineno uintptr // line number
1556 // Func *byte // function name (NUL terminated)
1557 // Entry uintptr // function entry point
1558 // More uintptr // set non-zero if more info for this PC
1559 // Data uintptr // unused by runtime, available for function
1560 // }
1561 //
1562 // In C syntax, this struct will be
1563 //
1564 // struct {
1565 // uintptr_t PC;
1566 // char* File;
1567 // uintptr_t Lineno;
1568 // char* Func;
1569 // uintptr_t Entry;
1570 // uintptr_t More;
1571 // uintptr_t Data;
1572 // };
1573 //
1574 // The PC field will be a value returned by a call to the traceback
1575 // function.
1576 //
1577 // The first time the function is called for a particular traceback,
1578 // all the fields except PC will be 0. The function should fill in the
1579 // other fields if possible, setting them to 0/nil if the information
1580 // is not available. The Data field may be used to store any useful
1581 // information across calls. The More field should be set to non-zero
1582 // if there is more information for this PC, zero otherwise. If More
1583 // is set non-zero, the function will be called again with the same
1584 // PC, and may return different information (this is intended for use
1585 // with inlined functions). If More is zero, the function will be
1586 // called with the next PC value in the traceback. When the traceback
1587 // is complete, the function will be called once more with PC set to
1588 // zero; this may be used to free any information. Each call will
1589 // leave the fields of the struct set to the same values they had upon
1590 // return, except for the PC field when the More field is zero. The
1591 // function must not keep a copy of the struct pointer between calls.
1592 //
1593 // When calling SetCgoTraceback, the version argument is the version
1594 // number of the structs that the functions expect to receive.
1595 // Currently this must be zero.
1596 //
1597 // The symbolizer function may be nil, in which case the results of
1598 // the traceback function will be displayed as numbers. If the
1599 // traceback function is nil, the symbolizer function will never be
1600 // called. The context function may be nil, in which case the
1601 // traceback function will only be called with the context field set
1602 // to zero. If the context function is nil, then calls from Go to C
1603 // to Go will not show a traceback for the C portion of the call stack.
1604 //
1605 // SetCgoTraceback should be called only once, ideally from an init function.
1606 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
1607 if version != 0 {
1608 panic("unsupported version")
1609 }
1610
1611 if cgoTraceback != nil && cgoTraceback != traceback ||
1612 cgoContext != nil && cgoContext != context ||
1613 cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
1614 panic("call SetCgoTraceback only once")
1615 }
1616
1617 cgoTraceback = traceback
1618 cgoContext = context
1619 cgoSymbolizer = symbolizer
1620
1621 if _cgo_set_traceback_functions != nil {
1622 type cgoSetTracebackFunctionsArg struct {
1623 traceback unsafe.Pointer
1624 context unsafe.Pointer
1625 symbolizer unsafe.Pointer
1626 }
1627 arg := cgoSetTracebackFunctionsArg{
1628 traceback: traceback,
1629 context: context,
1630 symbolizer: symbolizer,
1631 }
1632 cgocall(_cgo_set_traceback_functions, noescape(unsafe.Pointer(&arg)))
1633 }
1634 }
1635
1636 var cgoTraceback unsafe.Pointer
1637 var cgoContext unsafe.Pointer
1638 var cgoSymbolizer unsafe.Pointer
1639
1640 func cgoTracebackAvailable() bool {
1641 // - The traceback function must be registered via SetCgoTraceback.
1642 // - This must be a cgo binary (providing _cgo_call_traceback_function).
1643 return cgoTraceback != nil && _cgo_call_traceback_function != nil
1644 }
1645
1646 func cgoSymbolizerAvailable() bool {
1647 // - The symbolizer function must be registered via SetCgoTraceback.
1648 // - This must be a cgo binary (providing _cgo_call_symbolizer_function).
1649 return cgoSymbolizer != nil && _cgo_call_symbolizer_function != nil
1650 }
1651
1652 // cgoTracebackArg is the type passed to cgoTraceback.
1653 type cgoTracebackArg struct {
1654 context uintptr
1655 sigContext uintptr
1656 buf *uintptr
1657 max uintptr
1658 }
1659
1660 // cgoContextArg is the type passed to the context function.
1661 type cgoContextArg struct {
1662 context uintptr
1663 }
1664
1665 // cgoSymbolizerArg is the type passed to cgoSymbolizer.
1666 type cgoSymbolizerArg struct {
1667 pc uintptr
1668 file *byte
1669 lineno uintptr
1670 funcName *byte
1671 entry uintptr
1672 more uintptr
1673 data uintptr
1674 }
1675
1676 // printCgoTraceback prints a traceback of callers.
1677 func printCgoTraceback(callers *cgoCallers) {
1678 if !cgoSymbolizerAvailable() {
1679 for _, c := range callers {
1680 if c == 0 {
1681 break
1682 }
1683 print("non-Go function at pc=", hex(c), "\n")
1684 }
1685 return
1686 }
1687
1688 commitFrame := func() (pr, stop bool) { return true, false }
1689 var arg cgoSymbolizerArg
1690 for _, c := range callers {
1691 if c == 0 {
1692 break
1693 }
1694 printOneCgoTraceback(c, commitFrame, &arg)
1695 }
1696 arg.pc = 0
1697 callCgoSymbolizer(&arg)
1698 }
1699
1700 // printOneCgoTraceback prints the traceback of a single cgo caller.
1701 // This can print more than one line because of inlining.
1702 // It returns the "stop" result of commitFrame.
1703 //
1704 // Preconditions: cgoSymbolizerAvailable returns true.
1705 func printOneCgoTraceback(pc uintptr, commitFrame func() (pr, stop bool), arg *cgoSymbolizerArg) bool {
1706 arg.pc = pc
1707 for {
1708 if pr, stop := commitFrame(); stop {
1709 return true
1710 } else if !pr {
1711 continue
1712 }
1713
1714 callCgoSymbolizer(arg)
1715 if arg.funcName != nil {
1716 // Note that we don't print any argument
1717 // information here, not even parentheses.
1718 // The symbolizer must add that if appropriate.
1719 println(gostringnocopy(arg.funcName))
1720 } else {
1721 println("non-Go function")
1722 }
1723 print("\t")
1724 if arg.file != nil {
1725 print(gostringnocopy(arg.file), ":", arg.lineno, " ")
1726 }
1727 print("pc=", hex(pc), "\n")
1728 if arg.more == 0 {
1729 return false
1730 }
1731 }
1732 }
1733
1734 // callCgoSymbolizer calls the cgoSymbolizer function.
1735 //
1736 // Preconditions: cgoSymbolizerAvailable returns true.
1737 func callCgoSymbolizer(arg *cgoSymbolizerArg) {
1738 call := cgocall
1739 if panicking.Load() > 0 || getg().m.curg != getg() {
1740 // We do not want to call into the scheduler when panicking
1741 // or when on the system stack.
1742 call = asmcgocall
1743 }
1744 if msanenabled {
1745 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
1746 }
1747 if asanenabled {
1748 asanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
1749 }
1750 call(_cgo_call_symbolizer_function, noescape(unsafe.Pointer(arg)))
1751 }
1752
1753 // cgoContextPCs gets the PC values from a cgo traceback.
1754 //
1755 // Preconditions: cgoTracebackAvailable returns true.
1756 func cgoContextPCs(ctxt uintptr, buf []uintptr) {
1757 call := cgocall
1758 if panicking.Load() > 0 || getg().m.curg != getg() {
1759 // We do not want to call into the scheduler when panicking
1760 // or when on the system stack.
1761 call = asmcgocall
1762 }
1763 arg := cgoTracebackArg{
1764 context: ctxt,
1765 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
1766 max: uintptr(len(buf)),
1767 }
1768 if msanenabled {
1769 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
1770 }
1771 if asanenabled {
1772 asanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
1773 }
1774 call(_cgo_call_traceback_function, noescape(unsafe.Pointer(&arg)))
1775 }