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