]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/traceback.go
[dev.typeparams] all: merge master (fdab5be) into dev.typeparams
[gostls13.git] / src / runtime / traceback.go
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/bytealg"
9         "runtime/internal/atomic"
10         "runtime/internal/sys"
11         "unsafe"
12 )
13
14 // The code in this file implements stack trace walking for all architectures.
15 // The most important fact about a given architecture is whether it uses a link register.
16 // On systems with link registers, the prologue for a non-leaf function stores the
17 // incoming value of LR at the bottom of the newly allocated stack frame.
18 // On systems without link registers (x86), the architecture pushes a return PC during
19 // the call instruction, so the return PC ends up above the stack frame.
20 // In this file, the return PC is always called LR, no matter how it was found.
21
22 const usesLR = sys.MinFrameSize > 0
23
24 // Generic traceback. Handles runtime stack prints (pcbuf == nil),
25 // the runtime.Callers function (pcbuf != nil), as well as the garbage
26 // collector (callback != nil).  A little clunky to merge these, but avoids
27 // duplicating the code and all its subtlety.
28 //
29 // The skip argument is only valid with pcbuf != nil and counts the number
30 // of logical frames to skip rather than physical frames (with inlining, a
31 // PC in pcbuf can represent multiple calls).
32 func gentraceback(pc0, sp0, lr0 uintptr, gp *g, skip int, pcbuf *uintptr, max int, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer, flags uint) int {
33         if skip > 0 && callback != nil {
34                 throw("gentraceback callback cannot be used with non-zero skip")
35         }
36
37         // Don't call this "g"; it's too easy get "g" and "gp" confused.
38         if ourg := getg(); ourg == gp && ourg == ourg.m.curg {
39                 // The starting sp has been passed in as a uintptr, and the caller may
40                 // have other uintptr-typed stack references as well.
41                 // If during one of the calls that got us here or during one of the
42                 // callbacks below the stack must be grown, all these uintptr references
43                 // to the stack will not be updated, and gentraceback will continue
44                 // to inspect the old stack memory, which may no longer be valid.
45                 // Even if all the variables were updated correctly, it is not clear that
46                 // we want to expose a traceback that begins on one stack and ends
47                 // on another stack. That could confuse callers quite a bit.
48                 // Instead, we require that gentraceback and any other function that
49                 // accepts an sp for the current goroutine (typically obtained by
50                 // calling getcallersp) must not run on that goroutine's stack but
51                 // instead on the g0 stack.
52                 throw("gentraceback cannot trace user goroutine on its own stack")
53         }
54         level, _, _ := gotraceback()
55
56         var ctxt *funcval // Context pointer for unstarted goroutines. See issue #25897.
57
58         if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
59                 if gp.syscallsp != 0 {
60                         pc0 = gp.syscallpc
61                         sp0 = gp.syscallsp
62                         if usesLR {
63                                 lr0 = 0
64                         }
65                 } else {
66                         pc0 = gp.sched.pc
67                         sp0 = gp.sched.sp
68                         if usesLR {
69                                 lr0 = gp.sched.lr
70                         }
71                         ctxt = (*funcval)(gp.sched.ctxt)
72                 }
73         }
74
75         nprint := 0
76         var frame stkframe
77         frame.pc = pc0
78         frame.sp = sp0
79         if usesLR {
80                 frame.lr = lr0
81         }
82         waspanic := false
83         cgoCtxt := gp.cgoCtxt
84         printing := pcbuf == nil && callback == nil
85
86         // If the PC is zero, it's likely a nil function call.
87         // Start in the caller's frame.
88         if frame.pc == 0 {
89                 if usesLR {
90                         frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
91                         frame.lr = 0
92                 } else {
93                         frame.pc = uintptr(*(*uintptr)(unsafe.Pointer(frame.sp)))
94                         frame.sp += sys.PtrSize
95                 }
96         }
97
98         f := findfunc(frame.pc)
99         if !f.valid() {
100                 if callback != nil || printing {
101                         print("runtime: unknown pc ", hex(frame.pc), "\n")
102                         tracebackHexdump(gp.stack, &frame, 0)
103                 }
104                 if callback != nil {
105                         throw("unknown pc")
106                 }
107                 return 0
108         }
109         frame.fn = f
110
111         var cache pcvalueCache
112
113         lastFuncID := funcID_normal
114         n := 0
115         for n < max {
116                 // Typically:
117                 //      pc is the PC of the running function.
118                 //      sp is the stack pointer at that program counter.
119                 //      fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
120                 //      stk is the stack containing sp.
121                 //      The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
122                 f = frame.fn
123                 if f.pcsp == 0 {
124                         // No frame information, must be external function, like race support.
125                         // See golang.org/issue/13568.
126                         break
127                 }
128
129                 // Compute function info flags.
130                 flag := f.flag
131                 if f.funcID == funcID_cgocallback {
132                         // cgocallback does write SP to switch from the g0 to the curg stack,
133                         // but it carefully arranges that during the transition BOTH stacks
134                         // have cgocallback frame valid for unwinding through.
135                         // So we don't need to exclude it with the other SP-writing functions.
136                         flag &^= funcFlag_SPWRITE
137                 }
138                 if frame.pc == pc0 && frame.sp == sp0 && pc0 == gp.syscallpc && sp0 == gp.syscallsp {
139                         // Some Syscall functions write to SP, but they do so only after
140                         // saving the entry PC/SP using entersyscall.
141                         // Since we are using the entry PC/SP, the later SP write doesn't matter.
142                         flag &^= funcFlag_SPWRITE
143                 }
144
145                 // Found an actual function.
146                 // Derive frame pointer and link register.
147                 if frame.fp == 0 {
148                         // Jump over system stack transitions. If we're on g0 and there's a user
149                         // goroutine, try to jump. Otherwise this is a regular call.
150                         if flags&_TraceJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil {
151                                 switch f.funcID {
152                                 case funcID_morestack:
153                                         // morestack does not return normally -- newstack()
154                                         // gogo's to curg.sched. Match that.
155                                         // This keeps morestack() from showing up in the backtrace,
156                                         // but that makes some sense since it'll never be returned
157                                         // to.
158                                         frame.pc = gp.m.curg.sched.pc
159                                         frame.fn = findfunc(frame.pc)
160                                         f = frame.fn
161                                         flag = f.flag
162                                         frame.sp = gp.m.curg.sched.sp
163                                         cgoCtxt = gp.m.curg.cgoCtxt
164                                 case funcID_systemstack:
165                                         // systemstack returns normally, so just follow the
166                                         // stack transition.
167                                         frame.sp = gp.m.curg.sched.sp
168                                         cgoCtxt = gp.m.curg.cgoCtxt
169                                         flag &^= funcFlag_SPWRITE
170                                 }
171                         }
172                         frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &cache))
173                         if !usesLR {
174                                 // On x86, call instruction pushes return PC before entering new function.
175                                 frame.fp += sys.PtrSize
176                         }
177                 }
178                 var flr funcInfo
179                 if flag&funcFlag_TOPFRAME != 0 {
180                         // This function marks the top of the stack. Stop the traceback.
181                         frame.lr = 0
182                         flr = funcInfo{}
183                 } else if flag&funcFlag_SPWRITE != 0 && (callback == nil || n > 0) {
184                         // The function we are in does a write to SP that we don't know
185                         // how to encode in the spdelta table. Examples include context
186                         // switch routines like runtime.gogo but also any code that switches
187                         // to the g0 stack to run host C code. Since we can't reliably unwind
188                         // the SP (we might not even be on the stack we think we are),
189                         // we stop the traceback here.
190                         // This only applies for profiling signals (callback == nil).
191                         //
192                         // For a GC stack traversal (callback != nil), we should only see
193                         // a function when it has voluntarily preempted itself on entry
194                         // during the stack growth check. In that case, the function has
195                         // not yet had a chance to do any writes to SP and is safe to unwind.
196                         // isAsyncSafePoint does not allow assembly functions to be async preempted,
197                         // and preemptPark double-checks that SPWRITE functions are not async preempted.
198                         // So for GC stack traversal we leave things alone (this if body does not execute for n == 0)
199                         // at the bottom frame of the stack. But farther up the stack we'd better not
200                         // find any.
201                         if callback != nil {
202                                 println("traceback: unexpected SPWRITE function", funcname(f))
203                                 throw("traceback")
204                         }
205                         frame.lr = 0
206                         flr = funcInfo{}
207                 } else {
208                         var lrPtr uintptr
209                         if usesLR {
210                                 if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
211                                         lrPtr = frame.sp
212                                         frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
213                                 }
214                         } else {
215                                 if frame.lr == 0 {
216                                         lrPtr = frame.fp - sys.PtrSize
217                                         frame.lr = uintptr(*(*uintptr)(unsafe.Pointer(lrPtr)))
218                                 }
219                         }
220                         flr = findfunc(frame.lr)
221                         if !flr.valid() {
222                                 // This happens if you get a profiling interrupt at just the wrong time.
223                                 // In that context it is okay to stop early.
224                                 // But if callback is set, we're doing a garbage collection and must
225                                 // get everything, so crash loudly.
226                                 doPrint := printing
227                                 if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
228                                         // We can inject sigpanic
229                                         // calls directly into C code,
230                                         // in which case we'll see a C
231                                         // return PC. Don't complain.
232                                         doPrint = false
233                                 }
234                                 if callback != nil || doPrint {
235                                         print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
236                                         tracebackHexdump(gp.stack, &frame, lrPtr)
237                                 }
238                                 if callback != nil {
239                                         throw("unknown caller pc")
240                                 }
241                         }
242                 }
243
244                 frame.varp = frame.fp
245                 if !usesLR {
246                         // On x86, call instruction pushes return PC before entering new function.
247                         frame.varp -= sys.PtrSize
248                 }
249
250                 // For architectures with frame pointers, if there's
251                 // a frame, then there's a saved frame pointer here.
252                 //
253                 // NOTE: This code is not as general as it looks.
254                 // On x86, the ABI is to save the frame pointer word at the
255                 // top of the stack frame, so we have to back down over it.
256                 // On arm64, the frame pointer should be at the bottom of
257                 // the stack (with R29 (aka FP) = RSP), in which case we would
258                 // not want to do the subtraction here. But we started out without
259                 // any frame pointer, and when we wanted to add it, we didn't
260                 // want to break all the assembly doing direct writes to 8(RSP)
261                 // to set the first parameter to a called function.
262                 // So we decided to write the FP link *below* the stack pointer
263                 // (with R29 = RSP - 8 in Go functions).
264                 // This is technically ABI-compatible but not standard.
265                 // And it happens to end up mimicking the x86 layout.
266                 // Other architectures may make different decisions.
267                 if frame.varp > frame.sp && framepointer_enabled {
268                         frame.varp -= sys.PtrSize
269                 }
270
271                 // Derive size of arguments.
272                 // Most functions have a fixed-size argument block,
273                 // so we can use metadata about the function f.
274                 // Not all, though: there are some variadic functions
275                 // in package runtime and reflect, and for those we use call-specific
276                 // metadata recorded by f's caller.
277                 if callback != nil || printing {
278                         frame.argp = frame.fp + sys.MinFrameSize
279                         var ok bool
280                         frame.arglen, frame.argmap, ok = getArgInfoFast(f, callback != nil)
281                         if !ok {
282                                 frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, ctxt)
283                         }
284                 }
285                 ctxt = nil // ctxt is only needed to get arg maps for the topmost frame
286
287                 // Determine frame's 'continuation PC', where it can continue.
288                 // Normally this is the return address on the stack, but if sigpanic
289                 // is immediately below this function on the stack, then the frame
290                 // stopped executing due to a trap, and frame.pc is probably not
291                 // a safe point for looking up liveness information. In this panicking case,
292                 // the function either doesn't return at all (if it has no defers or if the
293                 // defers do not recover) or it returns from one of the calls to
294                 // deferproc a second time (if the corresponding deferred func recovers).
295                 // In the latter case, use a deferreturn call site as the continuation pc.
296                 frame.continpc = frame.pc
297                 if waspanic {
298                         if frame.fn.deferreturn != 0 {
299                                 frame.continpc = frame.fn.entry + uintptr(frame.fn.deferreturn) + 1
300                                 // Note: this may perhaps keep return variables alive longer than
301                                 // strictly necessary, as we are using "function has a defer statement"
302                                 // as a proxy for "function actually deferred something". It seems
303                                 // to be a minor drawback. (We used to actually look through the
304                                 // gp._defer for a defer corresponding to this function, but that
305                                 // is hard to do with defer records on the stack during a stack copy.)
306                                 // Note: the +1 is to offset the -1 that
307                                 // stack.go:getStackMap does to back up a return
308                                 // address make sure the pc is in the CALL instruction.
309                         } else {
310                                 frame.continpc = 0
311                         }
312                 }
313
314                 if callback != nil {
315                         if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
316                                 return n
317                         }
318                 }
319
320                 if pcbuf != nil {
321                         pc := frame.pc
322                         // backup to CALL instruction to read inlining info (same logic as below)
323                         tracepc := pc
324                         // Normally, pc is a return address. In that case, we want to look up
325                         // file/line information using pc-1, because that is the pc of the
326                         // call instruction (more precisely, the last byte of the call instruction).
327                         // Callers expect the pc buffer to contain return addresses and do the
328                         // same -1 themselves, so we keep pc unchanged.
329                         // When the pc is from a signal (e.g. profiler or segv) then we want
330                         // to look up file/line information using pc, and we store pc+1 in the
331                         // pc buffer so callers can unconditionally subtract 1 before looking up.
332                         // See issue 34123.
333                         // The pc can be at function entry when the frame is initialized without
334                         // actually running code, like runtime.mstart.
335                         if (n == 0 && flags&_TraceTrap != 0) || waspanic || pc == f.entry {
336                                 pc++
337                         } else {
338                                 tracepc--
339                         }
340
341                         // If there is inlining info, record the inner frames.
342                         if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
343                                 inltree := (*[1 << 20]inlinedCall)(inldata)
344                                 for {
345                                         ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache)
346                                         if ix < 0 {
347                                                 break
348                                         }
349                                         if inltree[ix].funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
350                                                 // ignore wrappers
351                                         } else if skip > 0 {
352                                                 skip--
353                                         } else if n < max {
354                                                 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
355                                                 n++
356                                         }
357                                         lastFuncID = inltree[ix].funcID
358                                         // Back up to an instruction in the "caller".
359                                         tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
360                                         pc = tracepc + 1
361                                 }
362                         }
363                         // Record the main frame.
364                         if f.funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
365                                 // Ignore wrapper functions (except when they trigger panics).
366                         } else if skip > 0 {
367                                 skip--
368                         } else if n < max {
369                                 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
370                                 n++
371                         }
372                         lastFuncID = f.funcID
373                         n-- // offset n++ below
374                 }
375
376                 if printing {
377                         // assume skip=0 for printing.
378                         //
379                         // Never elide wrappers if we haven't printed
380                         // any frames. And don't elide wrappers that
381                         // called panic rather than the wrapped
382                         // function. Otherwise, leave them out.
383
384                         // backup to CALL instruction to read inlining info (same logic as below)
385                         tracepc := frame.pc
386                         if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
387                                 tracepc--
388                         }
389                         // If there is inlining info, print the inner frames.
390                         if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
391                                 inltree := (*[1 << 20]inlinedCall)(inldata)
392                                 var inlFunc _func
393                                 inlFuncInfo := funcInfo{&inlFunc, f.datap}
394                                 for {
395                                         ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
396                                         if ix < 0 {
397                                                 break
398                                         }
399
400                                         // Create a fake _func for the
401                                         // inlined function.
402                                         inlFunc.nameoff = inltree[ix].func_
403                                         inlFunc.funcID = inltree[ix].funcID
404
405                                         if (flags&_TraceRuntimeFrames) != 0 || showframe(inlFuncInfo, gp, nprint == 0, inlFuncInfo.funcID, lastFuncID) {
406                                                 name := funcname(inlFuncInfo)
407                                                 file, line := funcline(f, tracepc)
408                                                 print(name, "(...)\n")
409                                                 print("\t", file, ":", line, "\n")
410                                                 nprint++
411                                         }
412                                         lastFuncID = inltree[ix].funcID
413                                         // Back up to an instruction in the "caller".
414                                         tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
415                                 }
416                         }
417                         if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, f.funcID, lastFuncID) {
418                                 // Print during crash.
419                                 //      main(0x1, 0x2, 0x3)
420                                 //              /home/rsc/go/src/runtime/x.go:23 +0xf
421                                 //
422                                 name := funcname(f)
423                                 file, line := funcline(f, tracepc)
424                                 if name == "runtime.gopanic" {
425                                         name = "panic"
426                                 }
427                                 print(name, "(")
428                                 argp := unsafe.Pointer(frame.argp)
429                                 printArgs(f, argp)
430                                 print(")\n")
431                                 print("\t", file, ":", line)
432                                 if frame.pc > f.entry {
433                                         print(" +", hex(frame.pc-f.entry))
434                                 }
435                                 if gp.m != nil && gp.m.throwing > 0 && gp == gp.m.curg || level >= 2 {
436                                         print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
437                                 }
438                                 print("\n")
439                                 nprint++
440                         }
441                         lastFuncID = f.funcID
442                 }
443                 n++
444
445                 if f.funcID == funcID_cgocallback && len(cgoCtxt) > 0 {
446                         ctxt := cgoCtxt[len(cgoCtxt)-1]
447                         cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
448
449                         // skip only applies to Go frames.
450                         // callback != nil only used when we only care
451                         // about Go frames.
452                         if skip == 0 && callback == nil {
453                                 n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
454                         }
455                 }
456
457                 waspanic = f.funcID == funcID_sigpanic
458                 injectedCall := waspanic || f.funcID == funcID_asyncPreempt
459
460                 // Do not unwind past the bottom of the stack.
461                 if !flr.valid() {
462                         break
463                 }
464
465                 // Unwind to next frame.
466                 frame.fn = flr
467                 frame.pc = frame.lr
468                 frame.lr = 0
469                 frame.sp = frame.fp
470                 frame.fp = 0
471                 frame.argmap = nil
472
473                 // On link register architectures, sighandler saves the LR on stack
474                 // before faking a call.
475                 if usesLR && injectedCall {
476                         x := *(*uintptr)(unsafe.Pointer(frame.sp))
477                         frame.sp += alignUp(sys.MinFrameSize, sys.StackAlign)
478                         f = findfunc(frame.pc)
479                         frame.fn = f
480                         if !f.valid() {
481                                 frame.pc = x
482                         } else if funcspdelta(f, frame.pc, &cache) == 0 {
483                                 frame.lr = x
484                         }
485                 }
486         }
487
488         if printing {
489                 n = nprint
490         }
491
492         // Note that panic != nil is okay here: there can be leftover panics,
493         // because the defers on the panic stack do not nest in frame order as
494         // they do on the defer stack. If you have:
495         //
496         //      frame 1 defers d1
497         //      frame 2 defers d2
498         //      frame 3 defers d3
499         //      frame 4 panics
500         //      frame 4's panic starts running defers
501         //      frame 5, running d3, defers d4
502         //      frame 5 panics
503         //      frame 5's panic starts running defers
504         //      frame 6, running d4, garbage collects
505         //      frame 6, running d2, garbage collects
506         //
507         // During the execution of d4, the panic stack is d4 -> d3, which
508         // is nested properly, and we'll treat frame 3 as resumable, because we
509         // can find d3. (And in fact frame 3 is resumable. If d4 recovers
510         // and frame 5 continues running, d3, d3 can recover and we'll
511         // resume execution in (returning from) frame 3.)
512         //
513         // During the execution of d2, however, the panic stack is d2 -> d3,
514         // which is inverted. The scan will match d2 to frame 2 but having
515         // d2 on the stack until then means it will not match d3 to frame 3.
516         // This is okay: if we're running d2, then all the defers after d2 have
517         // completed and their corresponding frames are dead. Not finding d3
518         // for frame 3 means we'll set frame 3's continpc == 0, which is correct
519         // (frame 3 is dead). At the end of the walk the panic stack can thus
520         // contain defers (d3 in this case) for dead frames. The inversion here
521         // always indicates a dead frame, and the effect of the inversion on the
522         // scan is to hide those dead frames, so the scan is still okay:
523         // what's left on the panic stack are exactly (and only) the dead frames.
524         //
525         // We require callback != nil here because only when callback != nil
526         // do we know that gentraceback is being called in a "must be correct"
527         // context as opposed to a "best effort" context. The tracebacks with
528         // callbacks only happen when everything is stopped nicely.
529         // At other times, such as when gathering a stack for a profiling signal
530         // or when printing a traceback during a crash, everything may not be
531         // stopped nicely, and the stack walk may not be able to complete.
532         if callback != nil && n < max && frame.sp != gp.stktopsp {
533                 print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
534                 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
535                 throw("traceback did not unwind completely")
536         }
537
538         return n
539 }
540
541 // printArgs prints function arguments in traceback.
542 func printArgs(f funcInfo, argp unsafe.Pointer) {
543         // The "instruction" of argument printing is encoded in _FUNCDATA_ArgInfo.
544         // See cmd/compile/internal/ssagen.emitArgInfo for the description of the
545         // encoding.
546         // These constants need to be in sync with the compiler.
547         const (
548                 _endSeq         = 0xff
549                 _startAgg       = 0xfe
550                 _endAgg         = 0xfd
551                 _dotdotdot      = 0xfc
552                 _offsetTooLarge = 0xfb
553         )
554
555         const (
556                 limit    = 10                       // print no more than 10 args/components
557                 maxDepth = 5                        // no more than 5 layers of nesting
558                 maxLen   = (maxDepth*3+2)*limit + 1 // max length of _FUNCDATA_ArgInfo (see the compiler side for reasoning)
559         )
560
561         p := (*[maxLen]uint8)(funcdata(f, _FUNCDATA_ArgInfo))
562         if p == nil {
563                 return
564         }
565
566         print1 := func(off, sz uint8) {
567                 x := readUnaligned64(add(argp, uintptr(off)))
568                 // mask out irrelavant bits
569                 if sz < 8 {
570                         shift := 64 - sz*8
571                         if sys.BigEndian {
572                                 x = x >> shift
573                         } else {
574                                 x = x << shift >> shift
575                         }
576                 }
577                 print(hex(x))
578         }
579
580         start := true
581         printcomma := func() {
582                 if !start {
583                         print(", ")
584                 }
585         }
586         pi := 0
587 printloop:
588         for {
589                 o := p[pi]
590                 pi++
591                 switch o {
592                 case _endSeq:
593                         break printloop
594                 case _startAgg:
595                         printcomma()
596                         print("{")
597                         start = true
598                         continue
599                 case _endAgg:
600                         print("}")
601                 case _dotdotdot:
602                         printcomma()
603                         print("...")
604                 case _offsetTooLarge:
605                         printcomma()
606                         print("_")
607                 default:
608                         printcomma()
609                         sz := p[pi]
610                         pi++
611                         print1(o, sz)
612                 }
613                 start = false
614         }
615 }
616
617 // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
618 // and reflect.methodValue.
619 type reflectMethodValue struct {
620         fn     uintptr
621         stack  *bitvector // ptrmap for both args and results
622         argLen uintptr    // just args
623 }
624
625 // getArgInfoFast returns the argument frame information for a call to f.
626 // It is short and inlineable. However, it does not handle all functions.
627 // If ok reports false, you must call getArgInfo instead.
628 // TODO(josharian): once we do mid-stack inlining,
629 // call getArgInfo directly from getArgInfoFast and stop returning an ok bool.
630 func getArgInfoFast(f funcInfo, needArgMap bool) (arglen uintptr, argmap *bitvector, ok bool) {
631         return uintptr(f.args), nil, !(needArgMap && f.args == _ArgsSizeUnknown)
632 }
633
634 // getArgInfo returns the argument frame information for a call to f
635 // with call frame frame.
636 //
637 // This is used for both actual calls with active stack frames and for
638 // deferred calls or goroutines that are not yet executing. If this is an actual
639 // call, ctxt must be nil (getArgInfo will retrieve what it needs from
640 // the active stack frame). If this is a deferred call or unstarted goroutine,
641 // ctxt must be the function object that was deferred or go'd.
642 func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
643         arglen = uintptr(f.args)
644         if needArgMap && f.args == _ArgsSizeUnknown {
645                 // Extract argument bitmaps for reflect stubs from the calls they made to reflect.
646                 switch funcname(f) {
647                 case "reflect.makeFuncStub", "reflect.methodValueCall":
648                         // These take a *reflect.methodValue as their
649                         // context register.
650                         var mv *reflectMethodValue
651                         var retValid bool
652                         if ctxt != nil {
653                                 // This is not an actual call, but a
654                                 // deferred call or an unstarted goroutine.
655                                 // The function value is itself the *reflect.methodValue.
656                                 mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
657                         } else {
658                                 // This is a real call that took the
659                                 // *reflect.methodValue as its context
660                                 // register and immediately saved it
661                                 // to 0(SP). Get the methodValue from
662                                 // 0(SP).
663                                 arg0 := frame.sp + sys.MinFrameSize
664                                 mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
665                                 // Figure out whether the return values are valid.
666                                 // Reflect will update this value after it copies
667                                 // in the return values.
668                                 retValid = *(*bool)(unsafe.Pointer(arg0 + 4*sys.PtrSize))
669                         }
670                         if mv.fn != f.entry {
671                                 print("runtime: confused by ", funcname(f), "\n")
672                                 throw("reflect mismatch")
673                         }
674                         bv := mv.stack
675                         arglen = uintptr(bv.n * sys.PtrSize)
676                         if !retValid {
677                                 arglen = uintptr(mv.argLen) &^ (sys.PtrSize - 1)
678                         }
679                         argmap = bv
680                 }
681         }
682         return
683 }
684
685 // tracebackCgoContext handles tracing back a cgo context value, from
686 // the context argument to setCgoTraceback, for the gentraceback
687 // function. It returns the new value of n.
688 func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
689         var cgoPCs [32]uintptr
690         cgoContextPCs(ctxt, cgoPCs[:])
691         var arg cgoSymbolizerArg
692         anySymbolized := false
693         for _, pc := range cgoPCs {
694                 if pc == 0 || n >= max {
695                         break
696                 }
697                 if pcbuf != nil {
698                         (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
699                 }
700                 if printing {
701                         if cgoSymbolizer == nil {
702                                 print("non-Go function at pc=", hex(pc), "\n")
703                         } else {
704                                 c := printOneCgoTraceback(pc, max-n, &arg)
705                                 n += c - 1 // +1 a few lines down
706                                 anySymbolized = true
707                         }
708                 }
709                 n++
710         }
711         if anySymbolized {
712                 arg.pc = 0
713                 callCgoSymbolizer(&arg)
714         }
715         return n
716 }
717
718 func printcreatedby(gp *g) {
719         // Show what created goroutine, except main goroutine (goid 1).
720         pc := gp.gopc
721         f := findfunc(pc)
722         if f.valid() && showframe(f, gp, false, funcID_normal, funcID_normal) && gp.goid != 1 {
723                 printcreatedby1(f, pc)
724         }
725 }
726
727 func printcreatedby1(f funcInfo, pc uintptr) {
728         print("created by ", funcname(f), "\n")
729         tracepc := pc // back up to CALL instruction for funcline.
730         if pc > f.entry {
731                 tracepc -= sys.PCQuantum
732         }
733         file, line := funcline(f, tracepc)
734         print("\t", file, ":", line)
735         if pc > f.entry {
736                 print(" +", hex(pc-f.entry))
737         }
738         print("\n")
739 }
740
741 func traceback(pc, sp, lr uintptr, gp *g) {
742         traceback1(pc, sp, lr, gp, 0)
743 }
744
745 // tracebacktrap is like traceback but expects that the PC and SP were obtained
746 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
747 // Because they are from a trap instead of from a saved pair,
748 // the initial PC must not be rewound to the previous instruction.
749 // (All the saved pairs record a PC that is a return address, so we
750 // rewind it into the CALL instruction.)
751 // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
752 // the pc/sp/lr passed in.
753 func tracebacktrap(pc, sp, lr uintptr, gp *g) {
754         if gp.m.libcallsp != 0 {
755                 // We're in C code somewhere, traceback from the saved position.
756                 traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
757                 return
758         }
759         traceback1(pc, sp, lr, gp, _TraceTrap)
760 }
761
762 func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
763         // If the goroutine is in cgo, and we have a cgo traceback, print that.
764         if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
765                 // Lock cgoCallers so that a signal handler won't
766                 // change it, copy the array, reset it, unlock it.
767                 // We are locked to the thread and are not running
768                 // concurrently with a signal handler.
769                 // We just have to stop a signal handler from interrupting
770                 // in the middle of our copy.
771                 atomic.Store(&gp.m.cgoCallersUse, 1)
772                 cgoCallers := *gp.m.cgoCallers
773                 gp.m.cgoCallers[0] = 0
774                 atomic.Store(&gp.m.cgoCallersUse, 0)
775
776                 printCgoTraceback(&cgoCallers)
777         }
778
779         var n int
780         if readgstatus(gp)&^_Gscan == _Gsyscall {
781                 // Override registers if blocked in system call.
782                 pc = gp.syscallpc
783                 sp = gp.syscallsp
784                 flags &^= _TraceTrap
785         }
786         // Print traceback. By default, omits runtime frames.
787         // If that means we print nothing at all, repeat forcing all frames printed.
788         n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
789         if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
790                 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
791         }
792         if n == _TracebackMaxFrames {
793                 print("...additional frames elided...\n")
794         }
795         printcreatedby(gp)
796
797         if gp.ancestors == nil {
798                 return
799         }
800         for _, ancestor := range *gp.ancestors {
801                 printAncestorTraceback(ancestor)
802         }
803 }
804
805 // printAncestorTraceback prints the traceback of the given ancestor.
806 // TODO: Unify this with gentraceback and CallersFrames.
807 func printAncestorTraceback(ancestor ancestorInfo) {
808         print("[originating from goroutine ", ancestor.goid, "]:\n")
809         for fidx, pc := range ancestor.pcs {
810                 f := findfunc(pc) // f previously validated
811                 if showfuncinfo(f, fidx == 0, funcID_normal, funcID_normal) {
812                         printAncestorTracebackFuncInfo(f, pc)
813                 }
814         }
815         if len(ancestor.pcs) == _TracebackMaxFrames {
816                 print("...additional frames elided...\n")
817         }
818         // Show what created goroutine, except main goroutine (goid 1).
819         f := findfunc(ancestor.gopc)
820         if f.valid() && showfuncinfo(f, false, funcID_normal, funcID_normal) && ancestor.goid != 1 {
821                 printcreatedby1(f, ancestor.gopc)
822         }
823 }
824
825 // printAncestorTraceback prints the given function info at a given pc
826 // within an ancestor traceback. The precision of this info is reduced
827 // due to only have access to the pcs at the time of the caller
828 // goroutine being created.
829 func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
830         name := funcname(f)
831         if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
832                 inltree := (*[1 << 20]inlinedCall)(inldata)
833                 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, pc, nil)
834                 if ix >= 0 {
835                         name = funcnameFromNameoff(f, inltree[ix].func_)
836                 }
837         }
838         file, line := funcline(f, pc)
839         if name == "runtime.gopanic" {
840                 name = "panic"
841         }
842         print(name, "(...)\n")
843         print("\t", file, ":", line)
844         if pc > f.entry {
845                 print(" +", hex(pc-f.entry))
846         }
847         print("\n")
848 }
849
850 func callers(skip int, pcbuf []uintptr) int {
851         sp := getcallersp()
852         pc := getcallerpc()
853         gp := getg()
854         var n int
855         systemstack(func() {
856                 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
857         })
858         return n
859 }
860
861 func gcallers(gp *g, skip int, pcbuf []uintptr) int {
862         return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
863 }
864
865 // showframe reports whether the frame with the given characteristics should
866 // be printed during a traceback.
867 func showframe(f funcInfo, gp *g, firstFrame bool, funcID, childID funcID) bool {
868         g := getg()
869         if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
870                 return true
871         }
872         return showfuncinfo(f, firstFrame, funcID, childID)
873 }
874
875 // showfuncinfo reports whether a function with the given characteristics should
876 // be printed during a traceback.
877 func showfuncinfo(f funcInfo, firstFrame bool, funcID, childID funcID) bool {
878         // Note that f may be a synthesized funcInfo for an inlined
879         // function, in which case only nameoff and funcID are set.
880
881         level, _, _ := gotraceback()
882         if level > 1 {
883                 // Show all frames.
884                 return true
885         }
886
887         if !f.valid() {
888                 return false
889         }
890
891         if funcID == funcID_wrapper && elideWrapperCalling(childID) {
892                 return false
893         }
894
895         name := funcname(f)
896
897         // Special case: always show runtime.gopanic frame
898         // in the middle of a stack trace, so that we can
899         // see the boundary between ordinary code and
900         // panic-induced deferred code.
901         // See golang.org/issue/5832.
902         if name == "runtime.gopanic" && !firstFrame {
903                 return true
904         }
905
906         return bytealg.IndexByteString(name, '.') >= 0 && (!hasPrefix(name, "runtime.") || isExportedRuntime(name))
907 }
908
909 // isExportedRuntime reports whether name is an exported runtime function.
910 // It is only for runtime functions, so ASCII A-Z is fine.
911 func isExportedRuntime(name string) bool {
912         const n = len("runtime.")
913         return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
914 }
915
916 // elideWrapperCalling reports whether a wrapper function that called
917 // function id should be elided from stack traces.
918 func elideWrapperCalling(id funcID) bool {
919         // If the wrapper called a panic function instead of the
920         // wrapped function, we want to include it in stacks.
921         return !(id == funcID_gopanic || id == funcID_sigpanic || id == funcID_panicwrap)
922 }
923
924 var gStatusStrings = [...]string{
925         _Gidle:      "idle",
926         _Grunnable:  "runnable",
927         _Grunning:   "running",
928         _Gsyscall:   "syscall",
929         _Gwaiting:   "waiting",
930         _Gdead:      "dead",
931         _Gcopystack: "copystack",
932         _Gpreempted: "preempted",
933 }
934
935 func goroutineheader(gp *g) {
936         gpstatus := readgstatus(gp)
937
938         isScan := gpstatus&_Gscan != 0
939         gpstatus &^= _Gscan // drop the scan bit
940
941         // Basic string status
942         var status string
943         if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
944                 status = gStatusStrings[gpstatus]
945         } else {
946                 status = "???"
947         }
948
949         // Override.
950         if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
951                 status = gp.waitreason.String()
952         }
953
954         // approx time the G is blocked, in minutes
955         var waitfor int64
956         if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
957                 waitfor = (nanotime() - gp.waitsince) / 60e9
958         }
959         print("goroutine ", gp.goid, " [", status)
960         if isScan {
961                 print(" (scan)")
962         }
963         if waitfor >= 1 {
964                 print(", ", waitfor, " minutes")
965         }
966         if gp.lockedm != 0 {
967                 print(", locked to thread")
968         }
969         print("]:\n")
970 }
971
972 func tracebackothers(me *g) {
973         level, _, _ := gotraceback()
974
975         // Show the current goroutine first, if we haven't already.
976         curgp := getg().m.curg
977         if curgp != nil && curgp != me {
978                 print("\n")
979                 goroutineheader(curgp)
980                 traceback(^uintptr(0), ^uintptr(0), 0, curgp)
981         }
982
983         // We can't call locking forEachG here because this may be during fatal
984         // throw/panic, where locking could be out-of-order or a direct
985         // deadlock.
986         //
987         // Instead, use forEachGRace, which requires no locking. We don't lock
988         // against concurrent creation of new Gs, but even with allglock we may
989         // miss Gs created after this loop.
990         forEachGRace(func(gp *g) {
991                 if gp == me || gp == curgp || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 {
992                         return
993                 }
994                 print("\n")
995                 goroutineheader(gp)
996                 // Note: gp.m == g.m occurs when tracebackothers is
997                 // called from a signal handler initiated during a
998                 // systemstack call. The original G is still in the
999                 // running state, and we want to print its stack.
1000                 if gp.m != getg().m && readgstatus(gp)&^_Gscan == _Grunning {
1001                         print("\tgoroutine running on other thread; stack unavailable\n")
1002                         printcreatedby(gp)
1003                 } else {
1004                         traceback(^uintptr(0), ^uintptr(0), 0, gp)
1005                 }
1006         })
1007 }
1008
1009 // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
1010 // for debugging purposes. If the address bad is included in the
1011 // hexdumped range, it will mark it as well.
1012 func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
1013         const expand = 32 * sys.PtrSize
1014         const maxExpand = 256 * sys.PtrSize
1015         // Start around frame.sp.
1016         lo, hi := frame.sp, frame.sp
1017         // Expand to include frame.fp.
1018         if frame.fp != 0 && frame.fp < lo {
1019                 lo = frame.fp
1020         }
1021         if frame.fp != 0 && frame.fp > hi {
1022                 hi = frame.fp
1023         }
1024         // Expand a bit more.
1025         lo, hi = lo-expand, hi+expand
1026         // But don't go too far from frame.sp.
1027         if lo < frame.sp-maxExpand {
1028                 lo = frame.sp - maxExpand
1029         }
1030         if hi > frame.sp+maxExpand {
1031                 hi = frame.sp + maxExpand
1032         }
1033         // And don't go outside the stack bounds.
1034         if lo < stk.lo {
1035                 lo = stk.lo
1036         }
1037         if hi > stk.hi {
1038                 hi = stk.hi
1039         }
1040
1041         // Print the hex dump.
1042         print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
1043         hexdumpWords(lo, hi, func(p uintptr) byte {
1044                 switch p {
1045                 case frame.fp:
1046                         return '>'
1047                 case frame.sp:
1048                         return '<'
1049                 case bad:
1050                         return '!'
1051                 }
1052                 return 0
1053         })
1054 }
1055
1056 // isSystemGoroutine reports whether the goroutine g must be omitted
1057 // in stack dumps and deadlock detector. This is any goroutine that
1058 // starts at a runtime.* entry point, except for runtime.main,
1059 // runtime.handleAsyncEvent (wasm only) and sometimes runtime.runfinq.
1060 //
1061 // If fixed is true, any goroutine that can vary between user and
1062 // system (that is, the finalizer goroutine) is considered a user
1063 // goroutine.
1064 func isSystemGoroutine(gp *g, fixed bool) bool {
1065         // Keep this in sync with cmd/trace/trace.go:isSystemGoroutine.
1066         f := findfunc(gp.startpc)
1067         if !f.valid() {
1068                 return false
1069         }
1070         if f.funcID == funcID_runtime_main || f.funcID == funcID_handleAsyncEvent {
1071                 return false
1072         }
1073         if f.funcID == funcID_runfinq {
1074                 // We include the finalizer goroutine if it's calling
1075                 // back into user code.
1076                 if fixed {
1077                         // This goroutine can vary. In fixed mode,
1078                         // always consider it a user goroutine.
1079                         return false
1080                 }
1081                 return !fingRunning
1082         }
1083         return hasPrefix(funcname(f), "runtime.")
1084 }
1085
1086 // SetCgoTraceback records three C functions to use to gather
1087 // traceback information from C code and to convert that traceback
1088 // information into symbolic information. These are used when printing
1089 // stack traces for a program that uses cgo.
1090 //
1091 // The traceback and context functions may be called from a signal
1092 // handler, and must therefore use only async-signal safe functions.
1093 // The symbolizer function may be called while the program is
1094 // crashing, and so must be cautious about using memory.  None of the
1095 // functions may call back into Go.
1096 //
1097 // The context function will be called with a single argument, a
1098 // pointer to a struct:
1099 //
1100 //      struct {
1101 //              Context uintptr
1102 //      }
1103 //
1104 // In C syntax, this struct will be
1105 //
1106 //      struct {
1107 //              uintptr_t Context;
1108 //      };
1109 //
1110 // If the Context field is 0, the context function is being called to
1111 // record the current traceback context. It should record in the
1112 // Context field whatever information is needed about the current
1113 // point of execution to later produce a stack trace, probably the
1114 // stack pointer and PC. In this case the context function will be
1115 // called from C code.
1116 //
1117 // If the Context field is not 0, then it is a value returned by a
1118 // previous call to the context function. This case is called when the
1119 // context is no longer needed; that is, when the Go code is returning
1120 // to its C code caller. This permits the context function to release
1121 // any associated resources.
1122 //
1123 // While it would be correct for the context function to record a
1124 // complete a stack trace whenever it is called, and simply copy that
1125 // out in the traceback function, in a typical program the context
1126 // function will be called many times without ever recording a
1127 // traceback for that context. Recording a complete stack trace in a
1128 // call to the context function is likely to be inefficient.
1129 //
1130 // The traceback function will be called with a single argument, a
1131 // pointer to a struct:
1132 //
1133 //      struct {
1134 //              Context    uintptr
1135 //              SigContext uintptr
1136 //              Buf        *uintptr
1137 //              Max        uintptr
1138 //      }
1139 //
1140 // In C syntax, this struct will be
1141 //
1142 //      struct {
1143 //              uintptr_t  Context;
1144 //              uintptr_t  SigContext;
1145 //              uintptr_t* Buf;
1146 //              uintptr_t  Max;
1147 //      };
1148 //
1149 // The Context field will be zero to gather a traceback from the
1150 // current program execution point. In this case, the traceback
1151 // function will be called from C code.
1152 //
1153 // Otherwise Context will be a value previously returned by a call to
1154 // the context function. The traceback function should gather a stack
1155 // trace from that saved point in the program execution. The traceback
1156 // function may be called from an execution thread other than the one
1157 // that recorded the context, but only when the context is known to be
1158 // valid and unchanging. The traceback function may also be called
1159 // deeper in the call stack on the same thread that recorded the
1160 // context. The traceback function may be called multiple times with
1161 // the same Context value; it will usually be appropriate to cache the
1162 // result, if possible, the first time this is called for a specific
1163 // context value.
1164 //
1165 // If the traceback function is called from a signal handler on a Unix
1166 // system, SigContext will be the signal context argument passed to
1167 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
1168 // used to start tracing at the point where the signal occurred. If
1169 // the traceback function is not called from a signal handler,
1170 // SigContext will be zero.
1171 //
1172 // Buf is where the traceback information should be stored. It should
1173 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
1174 // the PC of that function's caller, and so on.  Max is the maximum
1175 // number of entries to store.  The function should store a zero to
1176 // indicate the top of the stack, or that the caller is on a different
1177 // stack, presumably a Go stack.
1178 //
1179 // Unlike runtime.Callers, the PC values returned should, when passed
1180 // to the symbolizer function, return the file/line of the call
1181 // instruction.  No additional subtraction is required or appropriate.
1182 //
1183 // On all platforms, the traceback function is invoked when a call from
1184 // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
1185 // and freebsd/amd64, the traceback function is also invoked when a
1186 // signal is received by a thread that is executing a cgo call. The
1187 // traceback function should not make assumptions about when it is
1188 // called, as future versions of Go may make additional calls.
1189 //
1190 // The symbolizer function will be called with a single argument, a
1191 // pointer to a struct:
1192 //
1193 //      struct {
1194 //              PC      uintptr // program counter to fetch information for
1195 //              File    *byte   // file name (NUL terminated)
1196 //              Lineno  uintptr // line number
1197 //              Func    *byte   // function name (NUL terminated)
1198 //              Entry   uintptr // function entry point
1199 //              More    uintptr // set non-zero if more info for this PC
1200 //              Data    uintptr // unused by runtime, available for function
1201 //      }
1202 //
1203 // In C syntax, this struct will be
1204 //
1205 //      struct {
1206 //              uintptr_t PC;
1207 //              char*     File;
1208 //              uintptr_t Lineno;
1209 //              char*     Func;
1210 //              uintptr_t Entry;
1211 //              uintptr_t More;
1212 //              uintptr_t Data;
1213 //      };
1214 //
1215 // The PC field will be a value returned by a call to the traceback
1216 // function.
1217 //
1218 // The first time the function is called for a particular traceback,
1219 // all the fields except PC will be 0. The function should fill in the
1220 // other fields if possible, setting them to 0/nil if the information
1221 // is not available. The Data field may be used to store any useful
1222 // information across calls. The More field should be set to non-zero
1223 // if there is more information for this PC, zero otherwise. If More
1224 // is set non-zero, the function will be called again with the same
1225 // PC, and may return different information (this is intended for use
1226 // with inlined functions). If More is zero, the function will be
1227 // called with the next PC value in the traceback. When the traceback
1228 // is complete, the function will be called once more with PC set to
1229 // zero; this may be used to free any information. Each call will
1230 // leave the fields of the struct set to the same values they had upon
1231 // return, except for the PC field when the More field is zero. The
1232 // function must not keep a copy of the struct pointer between calls.
1233 //
1234 // When calling SetCgoTraceback, the version argument is the version
1235 // number of the structs that the functions expect to receive.
1236 // Currently this must be zero.
1237 //
1238 // The symbolizer function may be nil, in which case the results of
1239 // the traceback function will be displayed as numbers. If the
1240 // traceback function is nil, the symbolizer function will never be
1241 // called. The context function may be nil, in which case the
1242 // traceback function will only be called with the context field set
1243 // to zero.  If the context function is nil, then calls from Go to C
1244 // to Go will not show a traceback for the C portion of the call stack.
1245 //
1246 // SetCgoTraceback should be called only once, ideally from an init function.
1247 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
1248         if version != 0 {
1249                 panic("unsupported version")
1250         }
1251
1252         if cgoTraceback != nil && cgoTraceback != traceback ||
1253                 cgoContext != nil && cgoContext != context ||
1254                 cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
1255                 panic("call SetCgoTraceback only once")
1256         }
1257
1258         cgoTraceback = traceback
1259         cgoContext = context
1260         cgoSymbolizer = symbolizer
1261
1262         // The context function is called when a C function calls a Go
1263         // function. As such it is only called by C code in runtime/cgo.
1264         if _cgo_set_context_function != nil {
1265                 cgocall(_cgo_set_context_function, context)
1266         }
1267 }
1268
1269 var cgoTraceback unsafe.Pointer
1270 var cgoContext unsafe.Pointer
1271 var cgoSymbolizer unsafe.Pointer
1272
1273 // cgoTracebackArg is the type passed to cgoTraceback.
1274 type cgoTracebackArg struct {
1275         context    uintptr
1276         sigContext uintptr
1277         buf        *uintptr
1278         max        uintptr
1279 }
1280
1281 // cgoContextArg is the type passed to the context function.
1282 type cgoContextArg struct {
1283         context uintptr
1284 }
1285
1286 // cgoSymbolizerArg is the type passed to cgoSymbolizer.
1287 type cgoSymbolizerArg struct {
1288         pc       uintptr
1289         file     *byte
1290         lineno   uintptr
1291         funcName *byte
1292         entry    uintptr
1293         more     uintptr
1294         data     uintptr
1295 }
1296
1297 // cgoTraceback prints a traceback of callers.
1298 func printCgoTraceback(callers *cgoCallers) {
1299         if cgoSymbolizer == nil {
1300                 for _, c := range callers {
1301                         if c == 0 {
1302                                 break
1303                         }
1304                         print("non-Go function at pc=", hex(c), "\n")
1305                 }
1306                 return
1307         }
1308
1309         var arg cgoSymbolizerArg
1310         for _, c := range callers {
1311                 if c == 0 {
1312                         break
1313                 }
1314                 printOneCgoTraceback(c, 0x7fffffff, &arg)
1315         }
1316         arg.pc = 0
1317         callCgoSymbolizer(&arg)
1318 }
1319
1320 // printOneCgoTraceback prints the traceback of a single cgo caller.
1321 // This can print more than one line because of inlining.
1322 // Returns the number of frames printed.
1323 func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
1324         c := 0
1325         arg.pc = pc
1326         for c <= max {
1327                 callCgoSymbolizer(arg)
1328                 if arg.funcName != nil {
1329                         // Note that we don't print any argument
1330                         // information here, not even parentheses.
1331                         // The symbolizer must add that if appropriate.
1332                         println(gostringnocopy(arg.funcName))
1333                 } else {
1334                         println("non-Go function")
1335                 }
1336                 print("\t")
1337                 if arg.file != nil {
1338                         print(gostringnocopy(arg.file), ":", arg.lineno, " ")
1339                 }
1340                 print("pc=", hex(pc), "\n")
1341                 c++
1342                 if arg.more == 0 {
1343                         break
1344                 }
1345         }
1346         return c
1347 }
1348
1349 // callCgoSymbolizer calls the cgoSymbolizer function.
1350 func callCgoSymbolizer(arg *cgoSymbolizerArg) {
1351         call := cgocall
1352         if panicking > 0 || getg().m.curg != getg() {
1353                 // We do not want to call into the scheduler when panicking
1354                 // or when on the system stack.
1355                 call = asmcgocall
1356         }
1357         if msanenabled {
1358                 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
1359         }
1360         call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
1361 }
1362
1363 // cgoContextPCs gets the PC values from a cgo traceback.
1364 func cgoContextPCs(ctxt uintptr, buf []uintptr) {
1365         if cgoTraceback == nil {
1366                 return
1367         }
1368         call := cgocall
1369         if panicking > 0 || getg().m.curg != getg() {
1370                 // We do not want to call into the scheduler when panicking
1371                 // or when on the system stack.
1372                 call = asmcgocall
1373         }
1374         arg := cgoTracebackArg{
1375                 context: ctxt,
1376                 buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
1377                 max:     uintptr(len(buf)),
1378         }
1379         if msanenabled {
1380                 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
1381         }
1382         call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
1383 }