github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/src/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 "runtime/internal/atomic" 9 "runtime/internal/sys" 10 "unsafe" 11 ) 12 13 // The code in this file implements stack trace walking for all architectures. 14 // The most important fact about a given architecture is whether it uses a link register. 15 // On systems with link registers, the prologue for a non-leaf function stores the 16 // incoming value of LR at the bottom of the newly allocated stack frame. 17 // On systems without link registers, the architecture pushes a return PC during 18 // the call instruction, so the return PC ends up above the stack frame. 19 // In this file, the return PC is always called LR, no matter how it was found. 20 // 21 // To date, the opposite of a link register architecture is an x86 architecture. 22 // This code may need to change if some other kind of non-link-register 23 // architecture comes along. 24 // 25 // The other important fact is the size of a pointer: on 32-bit systems the LR 26 // takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes. 27 // Typically this is ptrSize. 28 // 29 // As an exception, amd64p32 has ptrSize == 4 but the CALL instruction still 30 // stores an 8-byte return PC onto the stack. To accommodate this, we use regSize 31 // as the size of the architecture-pushed return PC. 32 // 33 // usesLR is defined below in terms of minFrameSize, which is defined in 34 // arch_$GOARCH.go. ptrSize and regSize are defined in stubs.go. 35 36 const usesLR = sys.MinFrameSize > 0 37 38 var ( 39 // initialized in tracebackinit 40 goexitPC uintptr 41 jmpdeferPC uintptr 42 mcallPC uintptr 43 morestackPC uintptr 44 mstartPC uintptr 45 rt0_goPC uintptr 46 sigpanicPC uintptr 47 runfinqPC uintptr 48 bgsweepPC uintptr 49 forcegchelperPC uintptr 50 timerprocPC uintptr 51 gcBgMarkWorkerPC uintptr 52 systemstack_switchPC uintptr 53 systemstackPC uintptr 54 stackBarrierPC uintptr 55 cgocallback_gofuncPC uintptr 56 57 gogoPC uintptr 58 59 externalthreadhandlerp uintptr // initialized elsewhere 60 ) 61 62 func tracebackinit() { 63 // Go variable initialization happens late during runtime startup. 64 // Instead of initializing the variables above in the declarations, 65 // schedinit calls this function so that the variables are 66 // initialized and available earlier in the startup sequence. 67 goexitPC = funcPC(goexit) 68 jmpdeferPC = funcPC(jmpdefer) 69 mcallPC = funcPC(mcall) 70 morestackPC = funcPC(morestack) 71 mstartPC = funcPC(mstart) 72 rt0_goPC = funcPC(rt0_go) 73 sigpanicPC = funcPC(sigpanic) 74 runfinqPC = funcPC(runfinq) 75 bgsweepPC = funcPC(bgsweep) 76 forcegchelperPC = funcPC(forcegchelper) 77 timerprocPC = funcPC(timerproc) 78 gcBgMarkWorkerPC = funcPC(gcBgMarkWorker) 79 systemstack_switchPC = funcPC(systemstack_switch) 80 systemstackPC = funcPC(systemstack) 81 stackBarrierPC = funcPC(stackBarrier) 82 cgocallback_gofuncPC = funcPC(cgocallback_gofunc) 83 84 // used by sigprof handler 85 gogoPC = funcPC(gogo) 86 } 87 88 // Traceback over the deferred function calls. 89 // Report them like calls that have been invoked but not started executing yet. 90 func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) { 91 var frame stkframe 92 for d := gp._defer; d != nil; d = d.link { 93 fn := d.fn 94 if fn == nil { 95 // Defer of nil function. Args don't matter. 96 frame.pc = 0 97 frame.fn = nil 98 frame.argp = 0 99 frame.arglen = 0 100 frame.argmap = nil 101 } else { 102 frame.pc = fn.fn 103 f := findfunc(frame.pc) 104 if f == nil { 105 print("runtime: unknown pc in defer ", hex(frame.pc), "\n") 106 throw("unknown pc") 107 } 108 frame.fn = f 109 frame.argp = uintptr(deferArgs(d)) 110 frame.arglen, frame.argmap = getArgInfo(&frame, f, true) 111 } 112 frame.continpc = frame.pc 113 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { 114 return 115 } 116 } 117 } 118 119 // Generic traceback. Handles runtime stack prints (pcbuf == nil), 120 // the runtime.Callers function (pcbuf != nil), as well as the garbage 121 // collector (callback != nil). A little clunky to merge these, but avoids 122 // duplicating the code and all its subtlety. 123 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 { 124 if goexitPC == 0 { 125 throw("gentraceback before goexitPC initialization") 126 } 127 g := getg() 128 if g == gp && g == g.m.curg { 129 // The starting sp has been passed in as a uintptr, and the caller may 130 // have other uintptr-typed stack references as well. 131 // If during one of the calls that got us here or during one of the 132 // callbacks below the stack must be grown, all these uintptr references 133 // to the stack will not be updated, and gentraceback will continue 134 // to inspect the old stack memory, which may no longer be valid. 135 // Even if all the variables were updated correctly, it is not clear that 136 // we want to expose a traceback that begins on one stack and ends 137 // on another stack. That could confuse callers quite a bit. 138 // Instead, we require that gentraceback and any other function that 139 // accepts an sp for the current goroutine (typically obtained by 140 // calling getcallersp) must not run on that goroutine's stack but 141 // instead on the g0 stack. 142 throw("gentraceback cannot trace user goroutine on its own stack") 143 } 144 level, _, _ := gotraceback() 145 146 // Fix up returns to the stack barrier by fetching the 147 // original return PC from gp.stkbar. 148 stkbarG := gp 149 stkbar := stkbarG.stkbar[stkbarG.stkbarPos:] 150 151 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp. 152 if gp.syscallsp != 0 { 153 pc0 = gp.syscallpc 154 sp0 = gp.syscallsp 155 if usesLR { 156 lr0 = 0 157 } 158 } else { 159 pc0 = gp.sched.pc 160 sp0 = gp.sched.sp 161 if usesLR { 162 lr0 = gp.sched.lr 163 } 164 } 165 } 166 167 nprint := 0 168 var frame stkframe 169 frame.pc = pc0 170 frame.sp = sp0 171 if usesLR { 172 frame.lr = lr0 173 } 174 waspanic := false 175 cgoCtxt := gp.cgoCtxt 176 printing := pcbuf == nil && callback == nil 177 _defer := gp._defer 178 179 for _defer != nil && _defer.sp == _NoArgs { 180 _defer = _defer.link 181 } 182 183 // If the PC is zero, it's likely a nil function call. 184 // Start in the caller's frame. 185 if frame.pc == 0 { 186 if usesLR { 187 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp)) 188 frame.lr = 0 189 } else { 190 frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp))) 191 frame.sp += sys.RegSize 192 } 193 } 194 195 f := findfunc(frame.pc) 196 if f != nil && f.entry == stackBarrierPC { 197 // We got caught in the middle of a stack barrier 198 // (presumably by a signal), so stkbar may be 199 // inconsistent with the barriers on the stack. 200 // Simulate the completion of the barrier. 201 // 202 // On x86, SP will be exactly one word above 203 // savedLRPtr. On LR machines, SP will be above 204 // savedLRPtr by some frame size. 205 var stkbarPos uintptr 206 if len(stkbar) > 0 && stkbar[0].savedLRPtr < sp0 { 207 // stackBarrier has not incremented stkbarPos. 208 stkbarPos = gp.stkbarPos 209 } else if gp.stkbarPos > 0 && gp.stkbar[gp.stkbarPos-1].savedLRPtr < sp0 { 210 // stackBarrier has incremented stkbarPos. 211 stkbarPos = gp.stkbarPos - 1 212 } else { 213 printlock() 214 print("runtime: failed to unwind through stackBarrier at SP ", hex(sp0), "; ") 215 gcPrintStkbars(gp, int(gp.stkbarPos)) 216 print("\n") 217 throw("inconsistent state in stackBarrier") 218 } 219 220 frame.pc = gp.stkbar[stkbarPos].savedLRVal 221 stkbar = gp.stkbar[stkbarPos+1:] 222 f = findfunc(frame.pc) 223 } 224 if f == nil { 225 if callback != nil { 226 print("runtime: unknown pc ", hex(frame.pc), "\n") 227 throw("unknown pc") 228 } 229 return 0 230 } 231 frame.fn = f 232 233 var cache pcvalueCache 234 235 n := 0 236 for n < max { 237 // Typically: 238 // pc is the PC of the running function. 239 // sp is the stack pointer at that program counter. 240 // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown. 241 // stk is the stack containing sp. 242 // The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp. 243 f = frame.fn 244 if f.pcsp == 0 { 245 // No frame information, must be external function, like race support. 246 // See golang.org/issue/13568. 247 break 248 } 249 250 // Found an actual function. 251 // Derive frame pointer and link register. 252 if frame.fp == 0 { 253 // We want to jump over the systemstack switch. If we're running on the 254 // g0, this systemstack is at the top of the stack. 255 // if we're not on g0 or there's a no curg, then this is a regular call. 256 sp := frame.sp 257 if flags&_TraceJumpStack != 0 && f.entry == systemstackPC && gp == g.m.g0 && gp.m.curg != nil { 258 sp = gp.m.curg.sched.sp 259 frame.sp = sp 260 stkbarG = gp.m.curg 261 stkbar = stkbarG.stkbar[stkbarG.stkbarPos:] 262 cgoCtxt = gp.m.curg.cgoCtxt 263 } 264 frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache)) 265 if !usesLR { 266 // On x86, call instruction pushes return PC before entering new function. 267 frame.fp += sys.RegSize 268 } 269 } 270 var flr *_func 271 if topofstack(f) { 272 frame.lr = 0 273 flr = nil 274 } else if usesLR && f.entry == jmpdeferPC { 275 // jmpdefer modifies SP/LR/PC non-atomically. 276 // If a profiling interrupt arrives during jmpdefer, 277 // the stack unwind may see a mismatched register set 278 // and get confused. Stop if we see PC within jmpdefer 279 // to avoid that confusion. 280 // See golang.org/issue/8153. 281 if callback != nil { 282 throw("traceback_arm: found jmpdefer when tracing with callback") 283 } 284 frame.lr = 0 285 } else { 286 var lrPtr uintptr 287 if usesLR { 288 if n == 0 && frame.sp < frame.fp || frame.lr == 0 { 289 lrPtr = frame.sp 290 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr)) 291 } 292 } else { 293 if frame.lr == 0 { 294 lrPtr = frame.fp - sys.RegSize 295 frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr))) 296 } 297 } 298 if frame.lr == stackBarrierPC { 299 // Recover original PC. 300 if len(stkbar) == 0 || stkbar[0].savedLRPtr != lrPtr { 301 print("found next stack barrier at ", hex(lrPtr), "; expected ") 302 gcPrintStkbars(stkbarG, len(stkbarG.stkbar)-len(stkbar)) 303 print("\n") 304 throw("missed stack barrier") 305 } 306 frame.lr = stkbar[0].savedLRVal 307 stkbar = stkbar[1:] 308 } 309 flr = findfunc(frame.lr) 310 if flr == nil { 311 // This happens if you get a profiling interrupt at just the wrong time. 312 // In that context it is okay to stop early. 313 // But if callback is set, we're doing a garbage collection and must 314 // get everything, so crash loudly. 315 if callback != nil { 316 print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n") 317 throw("unknown caller pc") 318 } 319 } 320 } 321 322 frame.varp = frame.fp 323 if !usesLR { 324 // On x86, call instruction pushes return PC before entering new function. 325 frame.varp -= sys.RegSize 326 } 327 328 // If framepointer_enabled and there's a frame, then 329 // there's a saved bp here. 330 if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp { 331 frame.varp -= sys.RegSize 332 } 333 334 // Derive size of arguments. 335 // Most functions have a fixed-size argument block, 336 // so we can use metadata about the function f. 337 // Not all, though: there are some variadic functions 338 // in package runtime and reflect, and for those we use call-specific 339 // metadata recorded by f's caller. 340 if callback != nil || printing { 341 frame.argp = frame.fp + sys.MinFrameSize 342 frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil) 343 } 344 345 // Determine frame's 'continuation PC', where it can continue. 346 // Normally this is the return address on the stack, but if sigpanic 347 // is immediately below this function on the stack, then the frame 348 // stopped executing due to a trap, and frame.pc is probably not 349 // a safe point for looking up liveness information. In this panicking case, 350 // the function either doesn't return at all (if it has no defers or if the 351 // defers do not recover) or it returns from one of the calls to 352 // deferproc a second time (if the corresponding deferred func recovers). 353 // It suffices to assume that the most recent deferproc is the one that 354 // returns; everything live at earlier deferprocs is still live at that one. 355 frame.continpc = frame.pc 356 if waspanic { 357 if _defer != nil && _defer.sp == frame.sp { 358 frame.continpc = _defer.pc 359 } else { 360 frame.continpc = 0 361 } 362 } 363 364 // Unwind our local defer stack past this frame. 365 for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) { 366 _defer = _defer.link 367 } 368 369 if skip > 0 { 370 skip-- 371 goto skipped 372 } 373 374 if pcbuf != nil { 375 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc 376 } 377 if callback != nil { 378 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { 379 return n 380 } 381 } 382 if printing { 383 if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp) { 384 // Print during crash. 385 // main(0x1, 0x2, 0x3) 386 // /home/rsc/go/src/runtime/x.go:23 +0xf 387 // 388 tracepc := frame.pc // back up to CALL instruction for funcline. 389 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic { 390 tracepc-- 391 } 392 name := funcname(f) 393 if name == "runtime.gopanic" { 394 name = "panic" 395 } 396 print(name, "(") 397 argp := (*[100]uintptr)(unsafe.Pointer(frame.argp)) 398 for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ { 399 if i >= 10 { 400 print(", ...") 401 break 402 } 403 if i != 0 { 404 print(", ") 405 } 406 print(hex(argp[i])) 407 } 408 print(")\n") 409 file, line := funcline(f, tracepc) 410 print("\t", file, ":", line) 411 if frame.pc > f.entry { 412 print(" +", hex(frame.pc-f.entry)) 413 } 414 if g.m.throwing > 0 && gp == g.m.curg || level >= 2 { 415 print(" fp=", hex(frame.fp), " sp=", hex(frame.sp)) 416 } 417 print("\n") 418 nprint++ 419 } 420 } 421 n++ 422 423 skipped: 424 if f.entry == cgocallback_gofuncPC && len(cgoCtxt) > 0 { 425 ctxt := cgoCtxt[len(cgoCtxt)-1] 426 cgoCtxt = cgoCtxt[:len(cgoCtxt)-1] 427 428 // skip only applies to Go frames. 429 // callback != nil only used when we only care 430 // about Go frames. 431 if skip == 0 && callback == nil { 432 n = tracebackCgoContext(pcbuf, printing, ctxt, n, max) 433 } 434 } 435 436 waspanic = f.entry == sigpanicPC 437 438 // Do not unwind past the bottom of the stack. 439 if flr == nil { 440 break 441 } 442 443 // Unwind to next frame. 444 frame.fn = flr 445 frame.pc = frame.lr 446 frame.lr = 0 447 frame.sp = frame.fp 448 frame.fp = 0 449 frame.argmap = nil 450 451 // On link register architectures, sighandler saves the LR on stack 452 // before faking a call to sigpanic. 453 if usesLR && waspanic { 454 x := *(*uintptr)(unsafe.Pointer(frame.sp)) 455 frame.sp += sys.MinFrameSize 456 if GOARCH == "arm64" { 457 // arm64 needs 16-byte aligned SP, always 458 frame.sp += sys.PtrSize 459 } 460 f = findfunc(frame.pc) 461 frame.fn = f 462 if f == nil { 463 frame.pc = x 464 } else if funcspdelta(f, frame.pc, &cache) == 0 { 465 frame.lr = x 466 } 467 } 468 } 469 470 if printing { 471 n = nprint 472 } 473 474 // If callback != nil, we're being called to gather stack information during 475 // garbage collection or stack growth. In that context, require that we used 476 // up the entire defer stack. If not, then there is a bug somewhere and the 477 // garbage collection or stack growth may not have seen the correct picture 478 // of the stack. Crash now instead of silently executing the garbage collection 479 // or stack copy incorrectly and setting up for a mysterious crash later. 480 // 481 // Note that panic != nil is okay here: there can be leftover panics, 482 // because the defers on the panic stack do not nest in frame order as 483 // they do on the defer stack. If you have: 484 // 485 // frame 1 defers d1 486 // frame 2 defers d2 487 // frame 3 defers d3 488 // frame 4 panics 489 // frame 4's panic starts running defers 490 // frame 5, running d3, defers d4 491 // frame 5 panics 492 // frame 5's panic starts running defers 493 // frame 6, running d4, garbage collects 494 // frame 6, running d2, garbage collects 495 // 496 // During the execution of d4, the panic stack is d4 -> d3, which 497 // is nested properly, and we'll treat frame 3 as resumable, because we 498 // can find d3. (And in fact frame 3 is resumable. If d4 recovers 499 // and frame 5 continues running, d3, d3 can recover and we'll 500 // resume execution in (returning from) frame 3.) 501 // 502 // During the execution of d2, however, the panic stack is d2 -> d3, 503 // which is inverted. The scan will match d2 to frame 2 but having 504 // d2 on the stack until then means it will not match d3 to frame 3. 505 // This is okay: if we're running d2, then all the defers after d2 have 506 // completed and their corresponding frames are dead. Not finding d3 507 // for frame 3 means we'll set frame 3's continpc == 0, which is correct 508 // (frame 3 is dead). At the end of the walk the panic stack can thus 509 // contain defers (d3 in this case) for dead frames. The inversion here 510 // always indicates a dead frame, and the effect of the inversion on the 511 // scan is to hide those dead frames, so the scan is still okay: 512 // what's left on the panic stack are exactly (and only) the dead frames. 513 // 514 // We require callback != nil here because only when callback != nil 515 // do we know that gentraceback is being called in a "must be correct" 516 // context as opposed to a "best effort" context. The tracebacks with 517 // callbacks only happen when everything is stopped nicely. 518 // At other times, such as when gathering a stack for a profiling signal 519 // or when printing a traceback during a crash, everything may not be 520 // stopped nicely, and the stack walk may not be able to complete. 521 // It's okay in those situations not to use up the entire defer stack: 522 // incomplete information then is still better than nothing. 523 if callback != nil && n < max && _defer != nil { 524 if _defer != nil { 525 print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n") 526 } 527 for _defer = gp._defer; _defer != nil; _defer = _defer.link { 528 print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n") 529 } 530 throw("traceback has leftover defers") 531 } 532 533 if callback != nil && n < max && len(stkbar) > 0 { 534 print("runtime: g", gp.goid, ": leftover stack barriers ") 535 gcPrintStkbars(stkbarG, len(stkbarG.stkbar)-len(stkbar)) 536 print("\n") 537 throw("traceback has leftover stack barriers") 538 } 539 540 if callback != nil && n < max && frame.sp != gp.stktopsp { 541 print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n") 542 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n") 543 throw("traceback did not unwind completely") 544 } 545 546 return n 547 } 548 549 func getArgInfo(frame *stkframe, f *_func, needArgMap bool) (arglen uintptr, argmap *bitvector) { 550 arglen = uintptr(f.args) 551 if needArgMap && f.args == _ArgsSizeUnknown { 552 // Extract argument bitmaps for reflect stubs from the calls they made to reflect. 553 switch funcname(f) { 554 case "reflect.makeFuncStub", "reflect.methodValueCall": 555 arg0 := frame.sp + sys.MinFrameSize 556 fn := *(**[2]uintptr)(unsafe.Pointer(arg0)) 557 if fn[0] != f.entry { 558 print("runtime: confused by ", funcname(f), "\n") 559 throw("reflect mismatch") 560 } 561 bv := (*bitvector)(unsafe.Pointer(fn[1])) 562 arglen = uintptr(bv.n * sys.PtrSize) 563 argmap = bv 564 } 565 } 566 return 567 } 568 569 // tracebackCgoContext handles tracing back a cgo context value, from 570 // the context argument to setCgoTraceback, for the gentraceback 571 // function. It returns the new value of n. 572 func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int { 573 var cgoPCs [32]uintptr 574 cgoContextPCs(ctxt, cgoPCs[:]) 575 var arg cgoSymbolizerArg 576 anySymbolized := false 577 for _, pc := range cgoPCs { 578 if pc == 0 || n >= max { 579 break 580 } 581 if pcbuf != nil { 582 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc 583 } 584 if printing { 585 if cgoSymbolizer == nil { 586 print("non-Go function at pc=", hex(pc), "\n") 587 } else { 588 c := printOneCgoTraceback(pc, max-n, &arg) 589 n += c - 1 // +1 a few lines down 590 anySymbolized = true 591 } 592 } 593 n++ 594 } 595 if anySymbolized { 596 arg.pc = 0 597 callCgoSymbolizer(&arg) 598 } 599 return n 600 } 601 602 func printcreatedby(gp *g) { 603 // Show what created goroutine, except main goroutine (goid 1). 604 pc := gp.gopc 605 f := findfunc(pc) 606 if f != nil && showframe(f, gp) && gp.goid != 1 { 607 print("created by ", funcname(f), "\n") 608 tracepc := pc // back up to CALL instruction for funcline. 609 if pc > f.entry { 610 tracepc -= sys.PCQuantum 611 } 612 file, line := funcline(f, tracepc) 613 print("\t", file, ":", line) 614 if pc > f.entry { 615 print(" +", hex(pc-f.entry)) 616 } 617 print("\n") 618 } 619 } 620 621 func traceback(pc, sp, lr uintptr, gp *g) { 622 traceback1(pc, sp, lr, gp, 0) 623 } 624 625 // tracebacktrap is like traceback but expects that the PC and SP were obtained 626 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp. 627 // Because they are from a trap instead of from a saved pair, 628 // the initial PC must not be rewound to the previous instruction. 629 // (All the saved pairs record a PC that is a return address, so we 630 // rewind it into the CALL instruction.) 631 func tracebacktrap(pc, sp, lr uintptr, gp *g) { 632 traceback1(pc, sp, lr, gp, _TraceTrap) 633 } 634 635 func traceback1(pc, sp, lr uintptr, gp *g, flags uint) { 636 // If the goroutine is in cgo, and we have a cgo traceback, print that. 637 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { 638 // Lock cgoCallers so that a signal handler won't 639 // change it, copy the array, reset it, unlock it. 640 // We are locked to the thread and are not running 641 // concurrently with a signal handler. 642 // We just have to stop a signal handler from interrupting 643 // in the middle of our copy. 644 atomic.Store(&gp.m.cgoCallersUse, 1) 645 cgoCallers := *gp.m.cgoCallers 646 gp.m.cgoCallers[0] = 0 647 atomic.Store(&gp.m.cgoCallersUse, 0) 648 649 printCgoTraceback(&cgoCallers) 650 } 651 652 var n int 653 if readgstatus(gp)&^_Gscan == _Gsyscall { 654 // Override registers if blocked in system call. 655 pc = gp.syscallpc 656 sp = gp.syscallsp 657 flags &^= _TraceTrap 658 } 659 // Print traceback. By default, omits runtime frames. 660 // If that means we print nothing at all, repeat forcing all frames printed. 661 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags) 662 if n == 0 && (flags&_TraceRuntimeFrames) == 0 { 663 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames) 664 } 665 if n == _TracebackMaxFrames { 666 print("...additional frames elided...\n") 667 } 668 printcreatedby(gp) 669 } 670 671 func callers(skip int, pcbuf []uintptr) int { 672 sp := getcallersp(unsafe.Pointer(&skip)) 673 pc := getcallerpc(unsafe.Pointer(&skip)) 674 gp := getg() 675 var n int 676 systemstack(func() { 677 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 678 }) 679 return n 680 } 681 682 func gcallers(gp *g, skip int, pcbuf []uintptr) int { 683 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 684 } 685 686 func showframe(f *_func, gp *g) bool { 687 g := getg() 688 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) { 689 return true 690 } 691 level, _, _ := gotraceback() 692 name := funcname(f) 693 694 // Special case: always show runtime.gopanic frame, so that we can 695 // see where a panic started in the middle of a stack trace. 696 // See golang.org/issue/5832. 697 if name == "runtime.gopanic" { 698 return true 699 } 700 701 return level > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name)) 702 } 703 704 // isExportedRuntime reports whether name is an exported runtime function. 705 // It is only for runtime functions, so ASCII A-Z is fine. 706 func isExportedRuntime(name string) bool { 707 const n = len("runtime.") 708 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z' 709 } 710 711 var gStatusStrings = [...]string{ 712 _Gidle: "idle", 713 _Grunnable: "runnable", 714 _Grunning: "running", 715 _Gsyscall: "syscall", 716 _Gwaiting: "waiting", 717 _Gdead: "dead", 718 _Gcopystack: "copystack", 719 } 720 721 func goroutineheader(gp *g) { 722 gpstatus := readgstatus(gp) 723 724 isScan := gpstatus&_Gscan != 0 725 gpstatus &^= _Gscan // drop the scan bit 726 727 // Basic string status 728 var status string 729 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { 730 status = gStatusStrings[gpstatus] 731 } else { 732 status = "???" 733 } 734 735 // Override. 736 if gpstatus == _Gwaiting && gp.waitreason != "" { 737 status = gp.waitreason 738 } 739 740 // approx time the G is blocked, in minutes 741 var waitfor int64 742 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { 743 waitfor = (nanotime() - gp.waitsince) / 60e9 744 } 745 print("goroutine ", gp.goid, " [", status) 746 if isScan { 747 print(" (scan)") 748 } 749 if waitfor >= 1 { 750 print(", ", waitfor, " minutes") 751 } 752 if gp.lockedm != nil { 753 print(", locked to thread") 754 } 755 print("]:\n") 756 } 757 758 func tracebackothers(me *g) { 759 level, _, _ := gotraceback() 760 761 // Show the current goroutine first, if we haven't already. 762 g := getg() 763 gp := g.m.curg 764 if gp != nil && gp != me { 765 print("\n") 766 goroutineheader(gp) 767 traceback(^uintptr(0), ^uintptr(0), 0, gp) 768 } 769 770 lock(&allglock) 771 for _, gp := range allgs { 772 if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 { 773 continue 774 } 775 print("\n") 776 goroutineheader(gp) 777 // Note: gp.m == g.m occurs when tracebackothers is 778 // called from a signal handler initiated during a 779 // systemstack call. The original G is still in the 780 // running state, and we want to print its stack. 781 if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning { 782 print("\tgoroutine running on other thread; stack unavailable\n") 783 printcreatedby(gp) 784 } else { 785 traceback(^uintptr(0), ^uintptr(0), 0, gp) 786 } 787 } 788 unlock(&allglock) 789 } 790 791 // Does f mark the top of a goroutine stack? 792 func topofstack(f *_func) bool { 793 pc := f.entry 794 return pc == goexitPC || 795 pc == mstartPC || 796 pc == mcallPC || 797 pc == morestackPC || 798 pc == rt0_goPC || 799 externalthreadhandlerp != 0 && pc == externalthreadhandlerp 800 } 801 802 // isSystemGoroutine reports whether the goroutine g must be omitted in 803 // stack dumps and deadlock detector. 804 func isSystemGoroutine(gp *g) bool { 805 pc := gp.startpc 806 return pc == runfinqPC && !fingRunning || 807 pc == bgsweepPC || 808 pc == forcegchelperPC || 809 pc == timerprocPC || 810 pc == gcBgMarkWorkerPC 811 } 812 813 // SetCgoTraceback records three C functions to use to gather 814 // traceback information from C code and to convert that traceback 815 // information into symbolic information. These are used when printing 816 // stack traces for a program that uses cgo. 817 // 818 // The traceback and context functions may be called from a signal 819 // handler, and must therefore use only async-signal safe functions. 820 // The symbolizer function may be called while the program is 821 // crashing, and so must be cautious about using memory. None of the 822 // functions may call back into Go. 823 // 824 // The context function will be called with a single argument, a 825 // pointer to a struct: 826 // 827 // struct { 828 // Context uintptr 829 // } 830 // 831 // In C syntax, this struct will be 832 // 833 // struct { 834 // uintptr_t Context; 835 // }; 836 // 837 // If the Context field is 0, the context function is being called to 838 // record the current traceback context. It should record in the 839 // Context field whatever information is needed about the current 840 // point of execution to later produce a stack trace, probably the 841 // stack pointer and PC. In this case the context function will be 842 // called from C code. 843 // 844 // If the Context field is not 0, then it is a value returned by a 845 // previous call to the context function. This case is called when the 846 // context is no longer needed; that is, when the Go code is returning 847 // to its C code caller. This permits the context function to release 848 // any associated resources. 849 // 850 // While it would be correct for the context function to record a 851 // complete a stack trace whenever it is called, and simply copy that 852 // out in the traceback function, in a typical program the context 853 // function will be called many times without ever recording a 854 // traceback for that context. Recording a complete stack trace in a 855 // call to the context function is likely to be inefficient. 856 // 857 // The traceback function will be called with a single argument, a 858 // pointer to a struct: 859 // 860 // struct { 861 // Context uintptr 862 // SigContext uintptr 863 // Buf *uintptr 864 // Max uintptr 865 // } 866 // 867 // In C syntax, this struct will be 868 // 869 // struct { 870 // uintptr_t Context; 871 // uintptr_t SigContext; 872 // uintptr_t* Buf; 873 // uintptr_t Max; 874 // }; 875 // 876 // The Context field will be zero to gather a traceback from the 877 // current program execution point. In this case, the traceback 878 // function will be called from C code. 879 // 880 // Otherwise Context will be a value previously returned by a call to 881 // the context function. The traceback function should gather a stack 882 // trace from that saved point in the program execution. The traceback 883 // function may be called from an execution thread other than the one 884 // that recorded the context, but only when the context is known to be 885 // valid and unchanging. The traceback function may also be called 886 // deeper in the call stack on the same thread that recorded the 887 // context. The traceback function may be called multiple times with 888 // the same Context value; it will usually be appropriate to cache the 889 // result, if possible, the first time this is called for a specific 890 // context value. 891 // 892 // If the traceback function is called from a signal handler on a Unix 893 // system, SigContext will be the signal context argument passed to 894 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be 895 // used to start tracing at the point where the signal occurred. If 896 // the traceback function is not called from a signal handler, 897 // SigContext will be zero. 898 // 899 // Buf is where the traceback information should be stored. It should 900 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is 901 // the PC of that function's caller, and so on. Max is the maximum 902 // number of entries to store. The function should store a zero to 903 // indicate the top of the stack, or that the caller is on a different 904 // stack, presumably a Go stack. 905 // 906 // Unlike runtime.Callers, the PC values returned should, when passed 907 // to the symbolizer function, return the file/line of the call 908 // instruction. No additional subtraction is required or appropriate. 909 // 910 // The symbolizer function will be called with a single argument, a 911 // pointer to a struct: 912 // 913 // struct { 914 // PC uintptr // program counter to fetch information for 915 // File *byte // file name (NUL terminated) 916 // Lineno uintptr // line number 917 // Func *byte // function name (NUL terminated) 918 // Entry uintptr // function entry point 919 // More uintptr // set non-zero if more info for this PC 920 // Data uintptr // unused by runtime, available for function 921 // } 922 // 923 // In C syntax, this struct will be 924 // 925 // struct { 926 // uintptr_t PC; 927 // char* File; 928 // uintptr_t Lineno; 929 // char* Func; 930 // uintptr_t Entry; 931 // uintptr_t More; 932 // uintptr_t Data; 933 // }; 934 // 935 // The PC field will be a value returned by a call to the traceback 936 // function. 937 // 938 // The first time the function is called for a particular traceback, 939 // all the fields except PC will be 0. The function should fill in the 940 // other fields if possible, setting them to 0/nil if the information 941 // is not available. The Data field may be used to store any useful 942 // information across calls. The More field should be set to non-zero 943 // if there is more information for this PC, zero otherwise. If More 944 // is set non-zero, the function will be called again with the same 945 // PC, and may return different information (this is intended for use 946 // with inlined functions). If More is zero, the function will be 947 // called with the next PC value in the traceback. When the traceback 948 // is complete, the function will be called once more with PC set to 949 // zero; this may be used to free any information. Each call will 950 // leave the fields of the struct set to the same values they had upon 951 // return, except for the PC field when the More field is zero. The 952 // function must not keep a copy of the struct pointer between calls. 953 // 954 // When calling SetCgoTraceback, the version argument is the version 955 // number of the structs that the functions expect to receive. 956 // Currently this must be zero. 957 // 958 // The symbolizer function may be nil, in which case the results of 959 // the traceback function will be displayed as numbers. If the 960 // traceback function is nil, the symbolizer function will never be 961 // called. The context function may be nil, in which case the 962 // traceback function will only be called with the context field set 963 // to zero. If the context function is nil, then calls from Go to C 964 // to Go will not show a traceback for the C portion of the call stack. 965 // 966 // SetCgoTraceback should be called only once, ideally from an init function. 967 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) { 968 if version != 0 { 969 panic("unsupported version") 970 } 971 972 if cgoTraceback != nil && cgoTraceback != traceback || 973 cgoContext != nil && cgoContext != context || 974 cgoSymbolizer != nil && cgoSymbolizer != symbolizer { 975 panic("call SetCgoTraceback only once") 976 } 977 978 cgoTraceback = traceback 979 cgoContext = context 980 cgoSymbolizer = symbolizer 981 982 // The context function is called when a C function calls a Go 983 // function. As such it is only called by C code in runtime/cgo. 984 if _cgo_set_context_function != nil { 985 cgocall(_cgo_set_context_function, context) 986 } 987 } 988 989 var cgoTraceback unsafe.Pointer 990 var cgoContext unsafe.Pointer 991 var cgoSymbolizer unsafe.Pointer 992 993 // cgoTracebackArg is the type passed to cgoTraceback. 994 type cgoTracebackArg struct { 995 context uintptr 996 sigContext uintptr 997 buf *uintptr 998 max uintptr 999 } 1000 1001 // cgoContextArg is the type passed to the context function. 1002 type cgoContextArg struct { 1003 context uintptr 1004 } 1005 1006 // cgoSymbolizerArg is the type passed to cgoSymbolizer. 1007 type cgoSymbolizerArg struct { 1008 pc uintptr 1009 file *byte 1010 lineno uintptr 1011 funcName *byte 1012 entry uintptr 1013 more uintptr 1014 data uintptr 1015 } 1016 1017 // cgoTraceback prints a traceback of callers. 1018 func printCgoTraceback(callers *cgoCallers) { 1019 if cgoSymbolizer == nil { 1020 for _, c := range callers { 1021 if c == 0 { 1022 break 1023 } 1024 print("non-Go function at pc=", hex(c), "\n") 1025 } 1026 return 1027 } 1028 1029 var arg cgoSymbolizerArg 1030 for _, c := range callers { 1031 if c == 0 { 1032 break 1033 } 1034 printOneCgoTraceback(c, 0x7fffffff, &arg) 1035 } 1036 arg.pc = 0 1037 callCgoSymbolizer(&arg) 1038 } 1039 1040 // printOneCgoTraceback prints the traceback of a single cgo caller. 1041 // This can print more than one line because of inlining. 1042 // Returns the number of frames printed. 1043 func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int { 1044 c := 0 1045 arg.pc = pc 1046 for { 1047 if c > max { 1048 break 1049 } 1050 callCgoSymbolizer(arg) 1051 if arg.funcName != nil { 1052 // Note that we don't print any argument 1053 // information here, not even parentheses. 1054 // The symbolizer must add that if appropriate. 1055 println(gostringnocopy(arg.funcName)) 1056 } else { 1057 println("non-Go function") 1058 } 1059 print("\t") 1060 if arg.file != nil { 1061 print(gostringnocopy(arg.file), ":", arg.lineno, " ") 1062 } 1063 print("pc=", hex(pc), "\n") 1064 c++ 1065 if arg.more == 0 { 1066 break 1067 } 1068 } 1069 return c 1070 } 1071 1072 // callCgoSymbolizer calls the cgoSymbolizer function. 1073 func callCgoSymbolizer(arg *cgoSymbolizerArg) { 1074 call := cgocall 1075 if panicking > 0 || getg().m.curg != getg() { 1076 // We do not want to call into the scheduler when panicking 1077 // or when on the system stack. 1078 call = asmcgocall 1079 } 1080 if msanenabled { 1081 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) 1082 } 1083 call(cgoSymbolizer, noescape(unsafe.Pointer(arg))) 1084 } 1085 1086 // cgoContextPCs gets the PC values from a cgo traceback. 1087 func cgoContextPCs(ctxt uintptr, buf []uintptr) { 1088 if cgoTraceback == nil { 1089 return 1090 } 1091 call := cgocall 1092 if panicking > 0 || getg().m.curg != getg() { 1093 // We do not want to call into the scheduler when panicking 1094 // or when on the system stack. 1095 call = asmcgocall 1096 } 1097 arg := cgoTracebackArg{ 1098 context: ctxt, 1099 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))), 1100 max: uintptr(len(buf)), 1101 } 1102 if msanenabled { 1103 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) 1104 } 1105 call(cgoTraceback, noescape(unsafe.Pointer(&arg))) 1106 }