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