github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/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, fn) 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, 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 // reflectMethodValue is a partial duplicate of reflect.methodValue. 550 type reflectMethodValue struct { 551 fn uintptr 552 stack *bitvector // args bitmap 553 } 554 555 // getArgInfo returns the argument frame information for a call to f 556 // with call frame frame. 557 // 558 // This is used for both actual calls with active stack frames and for 559 // deferred calls that are not yet executing. If this is an actual 560 // call, ctxt must be nil (getArgInfo will retrieve what it needs from 561 // the active stack frame). If this is a deferred call, ctxt must be 562 // the function object that was deferred. 563 func getArgInfo(frame *stkframe, f *_func, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) { 564 arglen = uintptr(f.args) 565 if needArgMap && f.args == _ArgsSizeUnknown { 566 // Extract argument bitmaps for reflect stubs from the calls they made to reflect. 567 switch funcname(f) { 568 case "reflect.makeFuncStub", "reflect.methodValueCall": 569 // These take a *reflect.methodValue as their 570 // context register. 571 var mv *reflectMethodValue 572 if ctxt != nil { 573 // This is not an actual call, but a 574 // deferred call. The function value 575 // is itself the *reflect.methodValue. 576 mv = (*reflectMethodValue)(unsafe.Pointer(ctxt)) 577 } else { 578 // This is a real call that took the 579 // *reflect.methodValue as its context 580 // register and immediately saved it 581 // to 0(SP). Get the methodValue from 582 // 0(SP). 583 arg0 := frame.sp + sys.MinFrameSize 584 mv = *(**reflectMethodValue)(unsafe.Pointer(arg0)) 585 } 586 if mv.fn != f.entry { 587 print("runtime: confused by ", funcname(f), "\n") 588 throw("reflect mismatch") 589 } 590 bv := mv.stack 591 arglen = uintptr(bv.n * sys.PtrSize) 592 argmap = bv 593 } 594 } 595 return 596 } 597 598 // tracebackCgoContext handles tracing back a cgo context value, from 599 // the context argument to setCgoTraceback, for the gentraceback 600 // function. It returns the new value of n. 601 func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int { 602 var cgoPCs [32]uintptr 603 cgoContextPCs(ctxt, cgoPCs[:]) 604 var arg cgoSymbolizerArg 605 anySymbolized := false 606 for _, pc := range cgoPCs { 607 if pc == 0 || n >= max { 608 break 609 } 610 if pcbuf != nil { 611 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc 612 } 613 if printing { 614 if cgoSymbolizer == nil { 615 print("non-Go function at pc=", hex(pc), "\n") 616 } else { 617 c := printOneCgoTraceback(pc, max-n, &arg) 618 n += c - 1 // +1 a few lines down 619 anySymbolized = true 620 } 621 } 622 n++ 623 } 624 if anySymbolized { 625 arg.pc = 0 626 callCgoSymbolizer(&arg) 627 } 628 return n 629 } 630 631 func printcreatedby(gp *g) { 632 // Show what created goroutine, except main goroutine (goid 1). 633 pc := gp.gopc 634 f := findfunc(pc) 635 if f != nil && showframe(f, gp) && gp.goid != 1 { 636 print("created by ", funcname(f), "\n") 637 tracepc := pc // back up to CALL instruction for funcline. 638 if pc > f.entry { 639 tracepc -= sys.PCQuantum 640 } 641 file, line := funcline(f, tracepc) 642 print("\t", file, ":", line) 643 if pc > f.entry { 644 print(" +", hex(pc-f.entry)) 645 } 646 print("\n") 647 } 648 } 649 650 func traceback(pc, sp, lr uintptr, gp *g) { 651 traceback1(pc, sp, lr, gp, 0) 652 } 653 654 // tracebacktrap is like traceback but expects that the PC and SP were obtained 655 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp. 656 // Because they are from a trap instead of from a saved pair, 657 // the initial PC must not be rewound to the previous instruction. 658 // (All the saved pairs record a PC that is a return address, so we 659 // rewind it into the CALL instruction.) 660 func tracebacktrap(pc, sp, lr uintptr, gp *g) { 661 traceback1(pc, sp, lr, gp, _TraceTrap) 662 } 663 664 func traceback1(pc, sp, lr uintptr, gp *g, flags uint) { 665 // If the goroutine is in cgo, and we have a cgo traceback, print that. 666 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { 667 // Lock cgoCallers so that a signal handler won't 668 // change it, copy the array, reset it, unlock it. 669 // We are locked to the thread and are not running 670 // concurrently with a signal handler. 671 // We just have to stop a signal handler from interrupting 672 // in the middle of our copy. 673 atomic.Store(&gp.m.cgoCallersUse, 1) 674 cgoCallers := *gp.m.cgoCallers 675 gp.m.cgoCallers[0] = 0 676 atomic.Store(&gp.m.cgoCallersUse, 0) 677 678 printCgoTraceback(&cgoCallers) 679 } 680 681 var n int 682 if readgstatus(gp)&^_Gscan == _Gsyscall { 683 // Override registers if blocked in system call. 684 pc = gp.syscallpc 685 sp = gp.syscallsp 686 flags &^= _TraceTrap 687 } 688 // Print traceback. By default, omits runtime frames. 689 // If that means we print nothing at all, repeat forcing all frames printed. 690 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags) 691 if n == 0 && (flags&_TraceRuntimeFrames) == 0 { 692 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames) 693 } 694 if n == _TracebackMaxFrames { 695 print("...additional frames elided...\n") 696 } 697 printcreatedby(gp) 698 } 699 700 func callers(skip int, pcbuf []uintptr) int { 701 sp := getcallersp(unsafe.Pointer(&skip)) 702 pc := getcallerpc(unsafe.Pointer(&skip)) 703 gp := getg() 704 var n int 705 systemstack(func() { 706 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 707 }) 708 return n 709 } 710 711 func gcallers(gp *g, skip int, pcbuf []uintptr) int { 712 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 713 } 714 715 func showframe(f *_func, gp *g) bool { 716 g := getg() 717 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) { 718 return true 719 } 720 level, _, _ := gotraceback() 721 name := funcname(f) 722 723 // Special case: always show runtime.gopanic frame, so that we can 724 // see where a panic started in the middle of a stack trace. 725 // See golang.org/issue/5832. 726 if name == "runtime.gopanic" { 727 return true 728 } 729 730 return level > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name)) 731 } 732 733 // isExportedRuntime reports whether name is an exported runtime function. 734 // It is only for runtime functions, so ASCII A-Z is fine. 735 func isExportedRuntime(name string) bool { 736 const n = len("runtime.") 737 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z' 738 } 739 740 var gStatusStrings = [...]string{ 741 _Gidle: "idle", 742 _Grunnable: "runnable", 743 _Grunning: "running", 744 _Gsyscall: "syscall", 745 _Gwaiting: "waiting", 746 _Gdead: "dead", 747 _Gcopystack: "copystack", 748 } 749 750 func goroutineheader(gp *g) { 751 gpstatus := readgstatus(gp) 752 753 isScan := gpstatus&_Gscan != 0 754 gpstatus &^= _Gscan // drop the scan bit 755 756 // Basic string status 757 var status string 758 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { 759 status = gStatusStrings[gpstatus] 760 } else { 761 status = "???" 762 } 763 764 // Override. 765 if gpstatus == _Gwaiting && gp.waitreason != "" { 766 status = gp.waitreason 767 } 768 769 // approx time the G is blocked, in minutes 770 var waitfor int64 771 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { 772 waitfor = (nanotime() - gp.waitsince) / 60e9 773 } 774 print("goroutine ", gp.goid, " [", status) 775 if isScan { 776 print(" (scan)") 777 } 778 if waitfor >= 1 { 779 print(", ", waitfor, " minutes") 780 } 781 if gp.lockedm != nil { 782 print(", locked to thread") 783 } 784 print("]:\n") 785 } 786 787 func tracebackothers(me *g) { 788 level, _, _ := gotraceback() 789 790 // Show the current goroutine first, if we haven't already. 791 g := getg() 792 gp := g.m.curg 793 if gp != nil && gp != me { 794 print("\n") 795 goroutineheader(gp) 796 traceback(^uintptr(0), ^uintptr(0), 0, gp) 797 } 798 799 lock(&allglock) 800 for _, gp := range allgs { 801 if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 { 802 continue 803 } 804 print("\n") 805 goroutineheader(gp) 806 // Note: gp.m == g.m occurs when tracebackothers is 807 // called from a signal handler initiated during a 808 // systemstack call. The original G is still in the 809 // running state, and we want to print its stack. 810 if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning { 811 print("\tgoroutine running on other thread; stack unavailable\n") 812 printcreatedby(gp) 813 } else { 814 traceback(^uintptr(0), ^uintptr(0), 0, gp) 815 } 816 } 817 unlock(&allglock) 818 } 819 820 // Does f mark the top of a goroutine stack? 821 func topofstack(f *_func) bool { 822 pc := f.entry 823 return pc == goexitPC || 824 pc == mstartPC || 825 pc == mcallPC || 826 pc == morestackPC || 827 pc == rt0_goPC || 828 externalthreadhandlerp != 0 && pc == externalthreadhandlerp 829 } 830 831 // isSystemGoroutine reports whether the goroutine g must be omitted in 832 // stack dumps and deadlock detector. 833 func isSystemGoroutine(gp *g) bool { 834 pc := gp.startpc 835 return pc == runfinqPC && !fingRunning || 836 pc == bgsweepPC || 837 pc == forcegchelperPC || 838 pc == timerprocPC || 839 pc == gcBgMarkWorkerPC 840 } 841 842 // SetCgoTraceback records three C functions to use to gather 843 // traceback information from C code and to convert that traceback 844 // information into symbolic information. These are used when printing 845 // stack traces for a program that uses cgo. 846 // 847 // The traceback and context functions may be called from a signal 848 // handler, and must therefore use only async-signal safe functions. 849 // The symbolizer function may be called while the program is 850 // crashing, and so must be cautious about using memory. None of the 851 // functions may call back into Go. 852 // 853 // The context function will be called with a single argument, a 854 // pointer to a struct: 855 // 856 // struct { 857 // Context uintptr 858 // } 859 // 860 // In C syntax, this struct will be 861 // 862 // struct { 863 // uintptr_t Context; 864 // }; 865 // 866 // If the Context field is 0, the context function is being called to 867 // record the current traceback context. It should record in the 868 // Context field whatever information is needed about the current 869 // point of execution to later produce a stack trace, probably the 870 // stack pointer and PC. In this case the context function will be 871 // called from C code. 872 // 873 // If the Context field is not 0, then it is a value returned by a 874 // previous call to the context function. This case is called when the 875 // context is no longer needed; that is, when the Go code is returning 876 // to its C code caller. This permits the context function to release 877 // any associated resources. 878 // 879 // While it would be correct for the context function to record a 880 // complete a stack trace whenever it is called, and simply copy that 881 // out in the traceback function, in a typical program the context 882 // function will be called many times without ever recording a 883 // traceback for that context. Recording a complete stack trace in a 884 // call to the context function is likely to be inefficient. 885 // 886 // The traceback function will be called with a single argument, a 887 // pointer to a struct: 888 // 889 // struct { 890 // Context uintptr 891 // SigContext uintptr 892 // Buf *uintptr 893 // Max uintptr 894 // } 895 // 896 // In C syntax, this struct will be 897 // 898 // struct { 899 // uintptr_t Context; 900 // uintptr_t SigContext; 901 // uintptr_t* Buf; 902 // uintptr_t Max; 903 // }; 904 // 905 // The Context field will be zero to gather a traceback from the 906 // current program execution point. In this case, the traceback 907 // function will be called from C code. 908 // 909 // Otherwise Context will be a value previously returned by a call to 910 // the context function. The traceback function should gather a stack 911 // trace from that saved point in the program execution. The traceback 912 // function may be called from an execution thread other than the one 913 // that recorded the context, but only when the context is known to be 914 // valid and unchanging. The traceback function may also be called 915 // deeper in the call stack on the same thread that recorded the 916 // context. The traceback function may be called multiple times with 917 // the same Context value; it will usually be appropriate to cache the 918 // result, if possible, the first time this is called for a specific 919 // context value. 920 // 921 // If the traceback function is called from a signal handler on a Unix 922 // system, SigContext will be the signal context argument passed to 923 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be 924 // used to start tracing at the point where the signal occurred. If 925 // the traceback function is not called from a signal handler, 926 // SigContext will be zero. 927 // 928 // Buf is where the traceback information should be stored. It should 929 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is 930 // the PC of that function's caller, and so on. Max is the maximum 931 // number of entries to store. The function should store a zero to 932 // indicate the top of the stack, or that the caller is on a different 933 // stack, presumably a Go stack. 934 // 935 // Unlike runtime.Callers, the PC values returned should, when passed 936 // to the symbolizer function, return the file/line of the call 937 // instruction. No additional subtraction is required or appropriate. 938 // 939 // The symbolizer function will be called with a single argument, a 940 // pointer to a struct: 941 // 942 // struct { 943 // PC uintptr // program counter to fetch information for 944 // File *byte // file name (NUL terminated) 945 // Lineno uintptr // line number 946 // Func *byte // function name (NUL terminated) 947 // Entry uintptr // function entry point 948 // More uintptr // set non-zero if more info for this PC 949 // Data uintptr // unused by runtime, available for function 950 // } 951 // 952 // In C syntax, this struct will be 953 // 954 // struct { 955 // uintptr_t PC; 956 // char* File; 957 // uintptr_t Lineno; 958 // char* Func; 959 // uintptr_t Entry; 960 // uintptr_t More; 961 // uintptr_t Data; 962 // }; 963 // 964 // The PC field will be a value returned by a call to the traceback 965 // function. 966 // 967 // The first time the function is called for a particular traceback, 968 // all the fields except PC will be 0. The function should fill in the 969 // other fields if possible, setting them to 0/nil if the information 970 // is not available. The Data field may be used to store any useful 971 // information across calls. The More field should be set to non-zero 972 // if there is more information for this PC, zero otherwise. If More 973 // is set non-zero, the function will be called again with the same 974 // PC, and may return different information (this is intended for use 975 // with inlined functions). If More is zero, the function will be 976 // called with the next PC value in the traceback. When the traceback 977 // is complete, the function will be called once more with PC set to 978 // zero; this may be used to free any information. Each call will 979 // leave the fields of the struct set to the same values they had upon 980 // return, except for the PC field when the More field is zero. The 981 // function must not keep a copy of the struct pointer between calls. 982 // 983 // When calling SetCgoTraceback, the version argument is the version 984 // number of the structs that the functions expect to receive. 985 // Currently this must be zero. 986 // 987 // The symbolizer function may be nil, in which case the results of 988 // the traceback function will be displayed as numbers. If the 989 // traceback function is nil, the symbolizer function will never be 990 // called. The context function may be nil, in which case the 991 // traceback function will only be called with the context field set 992 // to zero. If the context function is nil, then calls from Go to C 993 // to Go will not show a traceback for the C portion of the call stack. 994 // 995 // SetCgoTraceback should be called only once, ideally from an init function. 996 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) { 997 if version != 0 { 998 panic("unsupported version") 999 } 1000 1001 if cgoTraceback != nil && cgoTraceback != traceback || 1002 cgoContext != nil && cgoContext != context || 1003 cgoSymbolizer != nil && cgoSymbolizer != symbolizer { 1004 panic("call SetCgoTraceback only once") 1005 } 1006 1007 cgoTraceback = traceback 1008 cgoContext = context 1009 cgoSymbolizer = symbolizer 1010 1011 // The context function is called when a C function calls a Go 1012 // function. As such it is only called by C code in runtime/cgo. 1013 if _cgo_set_context_function != nil { 1014 cgocall(_cgo_set_context_function, context) 1015 } 1016 } 1017 1018 var cgoTraceback unsafe.Pointer 1019 var cgoContext unsafe.Pointer 1020 var cgoSymbolizer unsafe.Pointer 1021 1022 // cgoTracebackArg is the type passed to cgoTraceback. 1023 type cgoTracebackArg struct { 1024 context uintptr 1025 sigContext uintptr 1026 buf *uintptr 1027 max uintptr 1028 } 1029 1030 // cgoContextArg is the type passed to the context function. 1031 type cgoContextArg struct { 1032 context uintptr 1033 } 1034 1035 // cgoSymbolizerArg is the type passed to cgoSymbolizer. 1036 type cgoSymbolizerArg struct { 1037 pc uintptr 1038 file *byte 1039 lineno uintptr 1040 funcName *byte 1041 entry uintptr 1042 more uintptr 1043 data uintptr 1044 } 1045 1046 // cgoTraceback prints a traceback of callers. 1047 func printCgoTraceback(callers *cgoCallers) { 1048 if cgoSymbolizer == nil { 1049 for _, c := range callers { 1050 if c == 0 { 1051 break 1052 } 1053 print("non-Go function at pc=", hex(c), "\n") 1054 } 1055 return 1056 } 1057 1058 var arg cgoSymbolizerArg 1059 for _, c := range callers { 1060 if c == 0 { 1061 break 1062 } 1063 printOneCgoTraceback(c, 0x7fffffff, &arg) 1064 } 1065 arg.pc = 0 1066 callCgoSymbolizer(&arg) 1067 } 1068 1069 // printOneCgoTraceback prints the traceback of a single cgo caller. 1070 // This can print more than one line because of inlining. 1071 // Returns the number of frames printed. 1072 func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int { 1073 c := 0 1074 arg.pc = pc 1075 for { 1076 if c > max { 1077 break 1078 } 1079 callCgoSymbolizer(arg) 1080 if arg.funcName != nil { 1081 // Note that we don't print any argument 1082 // information here, not even parentheses. 1083 // The symbolizer must add that if appropriate. 1084 println(gostringnocopy(arg.funcName)) 1085 } else { 1086 println("non-Go function") 1087 } 1088 print("\t") 1089 if arg.file != nil { 1090 print(gostringnocopy(arg.file), ":", arg.lineno, " ") 1091 } 1092 print("pc=", hex(pc), "\n") 1093 c++ 1094 if arg.more == 0 { 1095 break 1096 } 1097 } 1098 return c 1099 } 1100 1101 // callCgoSymbolizer calls the cgoSymbolizer function. 1102 func callCgoSymbolizer(arg *cgoSymbolizerArg) { 1103 call := cgocall 1104 if panicking > 0 || getg().m.curg != getg() { 1105 // We do not want to call into the scheduler when panicking 1106 // or when on the system stack. 1107 call = asmcgocall 1108 } 1109 if msanenabled { 1110 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) 1111 } 1112 call(cgoSymbolizer, noescape(unsafe.Pointer(arg))) 1113 } 1114 1115 // cgoContextPCs gets the PC values from a cgo traceback. 1116 func cgoContextPCs(ctxt uintptr, buf []uintptr) { 1117 if cgoTraceback == nil { 1118 return 1119 } 1120 call := cgocall 1121 if panicking > 0 || getg().m.curg != getg() { 1122 // We do not want to call into the scheduler when panicking 1123 // or when on the system stack. 1124 call = asmcgocall 1125 } 1126 arg := cgoTracebackArg{ 1127 context: ctxt, 1128 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))), 1129 max: uintptr(len(buf)), 1130 } 1131 if msanenabled { 1132 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) 1133 } 1134 call(cgoTraceback, noescape(unsafe.Pointer(&arg))) 1135 }