github.com/ltltlt/go-source-code@v0.0.0-20190830023027-95be009773aa/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 skipPC uintptr 39 40 func tracebackinit() { 41 // Go variable initialization happens late during runtime startup. 42 // Instead of initializing the variables above in the declarations, 43 // schedinit calls this function so that the variables are 44 // initialized and available earlier in the startup sequence. 45 skipPC = funcPC(skipPleaseUseCallersFrames) 46 } 47 48 // Traceback over the deferred function calls. 49 // Report them like calls that have been invoked but not started executing yet. 50 func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) { 51 var frame stkframe 52 for d := gp._defer; d != nil; d = d.link { 53 fn := d.fn 54 if fn == nil { 55 // Defer of nil function. Args don't matter. 56 frame.pc = 0 57 frame.fn = funcInfo{} 58 frame.argp = 0 59 frame.arglen = 0 60 frame.argmap = nil 61 } else { 62 frame.pc = fn.fn 63 f := findfunc(frame.pc) 64 if !f.valid() { 65 print("runtime: unknown pc in defer ", hex(frame.pc), "\n") 66 throw("unknown pc") 67 } 68 frame.fn = f 69 frame.argp = uintptr(deferArgs(d)) 70 frame.arglen, frame.argmap = getArgInfo(&frame, f, true, fn) 71 } 72 frame.continpc = frame.pc 73 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { 74 return 75 } 76 } 77 } 78 79 const sizeofSkipFunction = 256 80 81 // This function is defined in asm.s to be sizeofSkipFunction bytes long. 82 func skipPleaseUseCallersFrames() 83 84 // Generic traceback. Handles runtime stack prints (pcbuf == nil), 85 // the runtime.Callers function (pcbuf != nil), as well as the garbage 86 // collector (callback != nil). A little clunky to merge these, but avoids 87 // duplicating the code and all its subtlety. 88 // 89 // The skip argument is only valid with pcbuf != nil and counts the number 90 // of logical frames to skip rather than physical frames (with inlining, a 91 // PC in pcbuf can represent multiple calls). If a PC is partially skipped 92 // and max > 1, pcbuf[1] will be runtime.skipPleaseUseCallersFrames+N where 93 // N indicates the number of logical frames to skip in pcbuf[0]. 94 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 { 95 if skip > 0 && callback != nil { 96 throw("gentraceback callback cannot be used with non-zero skip") 97 } 98 g := getg() 99 if g == gp && g == g.m.curg { 100 // The starting sp has been passed in as a uintptr, and the caller may 101 // have other uintptr-typed stack references as well. 102 // If during one of the calls that got us here or during one of the 103 // callbacks below the stack must be grown, all these uintptr references 104 // to the stack will not be updated, and gentraceback will continue 105 // to inspect the old stack memory, which may no longer be valid. 106 // Even if all the variables were updated correctly, it is not clear that 107 // we want to expose a traceback that begins on one stack and ends 108 // on another stack. That could confuse callers quite a bit. 109 // Instead, we require that gentraceback and any other function that 110 // accepts an sp for the current goroutine (typically obtained by 111 // calling getcallersp) must not run on that goroutine's stack but 112 // instead on the g0 stack. 113 throw("gentraceback cannot trace user goroutine on its own stack") 114 } 115 level, _, _ := gotraceback() 116 117 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp. 118 if gp.syscallsp != 0 { 119 pc0 = gp.syscallpc 120 sp0 = gp.syscallsp 121 if usesLR { 122 lr0 = 0 123 } 124 } else { 125 pc0 = gp.sched.pc 126 sp0 = gp.sched.sp 127 if usesLR { 128 lr0 = gp.sched.lr 129 } 130 } 131 } 132 133 nprint := 0 134 var frame stkframe 135 frame.pc = pc0 136 frame.sp = sp0 137 if usesLR { 138 frame.lr = lr0 139 } 140 waspanic := false 141 cgoCtxt := gp.cgoCtxt 142 printing := pcbuf == nil && callback == nil 143 _defer := gp._defer 144 elideWrapper := false 145 146 for _defer != nil && _defer.sp == _NoArgs { 147 _defer = _defer.link 148 } 149 150 // If the PC is zero, it's likely a nil function call. 151 // Start in the caller's frame. 152 if frame.pc == 0 { 153 if usesLR { 154 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp)) 155 frame.lr = 0 156 } else { 157 frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp))) 158 frame.sp += sys.RegSize 159 } 160 } 161 162 f := findfunc(frame.pc) 163 if !f.valid() { 164 if callback != nil || printing { 165 print("runtime: unknown pc ", hex(frame.pc), "\n") 166 tracebackHexdump(gp.stack, &frame, 0) 167 } 168 if callback != nil { 169 throw("unknown pc") 170 } 171 return 0 172 } 173 frame.fn = f 174 175 var cache pcvalueCache 176 177 n := 0 178 for n < max { 179 // Typically: 180 // pc is the PC of the running function. 181 // sp is the stack pointer at that program counter. 182 // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown. 183 // stk is the stack containing sp. 184 // The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp. 185 f = frame.fn 186 if f.pcsp == 0 { 187 // No frame information, must be external function, like race support. 188 // See golang.org/issue/13568. 189 break 190 } 191 192 // Found an actual function. 193 // Derive frame pointer and link register. 194 if frame.fp == 0 { 195 // We want to jump over the systemstack switch. If we're running on the 196 // g0, this systemstack is at the top of the stack. 197 // if we're not on g0 or there's a no curg, then this is a regular call. 198 sp := frame.sp 199 if flags&_TraceJumpStack != 0 && f.funcID == funcID_systemstack && gp == g.m.g0 && gp.m.curg != nil { 200 sp = gp.m.curg.sched.sp 201 frame.sp = sp 202 cgoCtxt = gp.m.curg.cgoCtxt 203 } 204 frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache)) 205 if !usesLR { 206 // On x86, call instruction pushes return PC before entering new function. 207 frame.fp += sys.RegSize 208 } 209 } 210 var flr funcInfo 211 if topofstack(f, gp.m != nil && gp == gp.m.g0) { 212 frame.lr = 0 213 flr = funcInfo{} 214 } else if usesLR && f.funcID == funcID_jmpdefer { 215 // jmpdefer modifies SP/LR/PC non-atomically. 216 // If a profiling interrupt arrives during jmpdefer, 217 // the stack unwind may see a mismatched register set 218 // and get confused. Stop if we see PC within jmpdefer 219 // to avoid that confusion. 220 // See golang.org/issue/8153. 221 if callback != nil { 222 throw("traceback_arm: found jmpdefer when tracing with callback") 223 } 224 frame.lr = 0 225 } else { 226 var lrPtr uintptr 227 if usesLR { 228 if n == 0 && frame.sp < frame.fp || frame.lr == 0 { 229 lrPtr = frame.sp 230 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr)) 231 } 232 } else { 233 if frame.lr == 0 { 234 lrPtr = frame.fp - sys.RegSize 235 frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr))) 236 } 237 } 238 flr = findfunc(frame.lr) 239 if !flr.valid() { 240 // This happens if you get a profiling interrupt at just the wrong time. 241 // In that context it is okay to stop early. 242 // But if callback is set, we're doing a garbage collection and must 243 // get everything, so crash loudly. 244 doPrint := printing 245 if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic { 246 // We can inject sigpanic 247 // calls directly into C code, 248 // in which case we'll see a C 249 // return PC. Don't complain. 250 doPrint = false 251 } 252 if callback != nil || doPrint { 253 print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n") 254 tracebackHexdump(gp.stack, &frame, lrPtr) 255 } 256 if callback != nil { 257 throw("unknown caller pc") 258 } 259 } 260 } 261 262 frame.varp = frame.fp 263 if !usesLR { 264 // On x86, call instruction pushes return PC before entering new function. 265 frame.varp -= sys.RegSize 266 } 267 268 // If framepointer_enabled and there's a frame, then 269 // there's a saved bp here. 270 if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp { 271 frame.varp -= sys.RegSize 272 } 273 274 // Derive size of arguments. 275 // Most functions have a fixed-size argument block, 276 // so we can use metadata about the function f. 277 // Not all, though: there are some variadic functions 278 // in package runtime and reflect, and for those we use call-specific 279 // metadata recorded by f's caller. 280 if callback != nil || printing { 281 frame.argp = frame.fp + sys.MinFrameSize 282 frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, nil) 283 } 284 285 // Determine frame's 'continuation PC', where it can continue. 286 // Normally this is the return address on the stack, but if sigpanic 287 // is immediately below this function on the stack, then the frame 288 // stopped executing due to a trap, and frame.pc is probably not 289 // a safe point for looking up liveness information. In this panicking case, 290 // the function either doesn't return at all (if it has no defers or if the 291 // defers do not recover) or it returns from one of the calls to 292 // deferproc a second time (if the corresponding deferred func recovers). 293 // It suffices to assume that the most recent deferproc is the one that 294 // returns; everything live at earlier deferprocs is still live at that one. 295 frame.continpc = frame.pc 296 if waspanic { 297 if _defer != nil && _defer.sp == frame.sp { 298 frame.continpc = _defer.pc 299 } else { 300 frame.continpc = 0 301 } 302 } 303 304 // Unwind our local defer stack past this frame. 305 for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) { 306 _defer = _defer.link 307 } 308 309 if callback != nil { 310 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) { 311 return n 312 } 313 } 314 315 if pcbuf != nil { 316 if skip == 0 { 317 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc 318 } else { 319 // backup to CALL instruction to read inlining info (same logic as below) 320 tracepc := frame.pc 321 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic { 322 tracepc-- 323 } 324 inldata := funcdata(f, _FUNCDATA_InlTree) 325 326 // no inlining info, skip the physical frame 327 if inldata == nil { 328 skip-- 329 goto skipped 330 } 331 332 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache) 333 inltree := (*[1 << 20]inlinedCall)(inldata) 334 // skip the logical (inlined) frames 335 logicalSkipped := 0 336 for ix >= 0 && skip > 0 { 337 skip-- 338 logicalSkipped++ 339 ix = inltree[ix].parent 340 } 341 342 // skip the physical frame if there's more to skip 343 if skip > 0 { 344 skip-- 345 goto skipped 346 } 347 348 // now we have a partially skipped frame 349 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc 350 351 // if there's room, pcbuf[1] is a skip PC that encodes the number of skipped frames in pcbuf[0] 352 if n+1 < max { 353 n++ 354 pc := skipPC + uintptr(logicalSkipped) 355 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc 356 } 357 } 358 } 359 360 if printing { 361 // assume skip=0 for printing. 362 // 363 // Never elide wrappers if we haven't printed 364 // any frames. And don't elide wrappers that 365 // called panic rather than the wrapped 366 // function. Otherwise, leave them out. 367 name := funcname(f) 368 nextElideWrapper := elideWrapperCalling(name) 369 if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, elideWrapper && nprint != 0) { 370 // Print during crash. 371 // main(0x1, 0x2, 0x3) 372 // /home/rsc/go/src/runtime/x.go:23 +0xf 373 // 374 tracepc := frame.pc // back up to CALL instruction for funcline. 375 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic { 376 tracepc-- 377 } 378 file, line := funcline(f, tracepc) 379 inldata := funcdata(f, _FUNCDATA_InlTree) 380 if inldata != nil { 381 inltree := (*[1 << 20]inlinedCall)(inldata) 382 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil) 383 for ix != -1 { 384 name := funcnameFromNameoff(f, inltree[ix].func_) 385 print(name, "(...)\n") 386 print("\t", file, ":", line, "\n") 387 388 file = funcfile(f, inltree[ix].file) 389 line = inltree[ix].line 390 ix = inltree[ix].parent 391 } 392 } 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 print("\t", file, ":", line) 410 if frame.pc > f.entry { 411 print(" +", hex(frame.pc-f.entry)) 412 } 413 if g.m.throwing > 0 && gp == g.m.curg || level >= 2 { 414 print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc)) 415 } 416 print("\n") 417 nprint++ 418 } 419 elideWrapper = nextElideWrapper 420 } 421 n++ 422 423 skipped: 424 if f.funcID == funcID_cgocallback_gofunc && 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.funcID == funcID_sigpanic 437 438 // Do not unwind past the bottom of the stack. 439 if !flr.valid() { 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.valid() { 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 && frame.sp != gp.stktopsp { 534 print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n") 535 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n") 536 throw("traceback did not unwind completely") 537 } 538 539 return n 540 } 541 542 // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl 543 // and reflect.methodValue. 544 type reflectMethodValue struct { 545 fn uintptr 546 stack *bitvector // args bitmap 547 } 548 549 // getArgInfo returns the argument frame information for a call to f 550 // with call frame frame. 551 // 552 // This is used for both actual calls with active stack frames and for 553 // deferred calls that are not yet executing. If this is an actual 554 // call, ctxt must be nil (getArgInfo will retrieve what it needs from 555 // the active stack frame). If this is a deferred call, ctxt must be 556 // the function object that was deferred. 557 func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) { 558 arglen = uintptr(f.args) 559 if needArgMap && f.args == _ArgsSizeUnknown { 560 // Extract argument bitmaps for reflect stubs from the calls they made to reflect. 561 switch funcname(f) { 562 case "reflect.makeFuncStub", "reflect.methodValueCall": 563 // These take a *reflect.methodValue as their 564 // context register. 565 var mv *reflectMethodValue 566 if ctxt != nil { 567 // This is not an actual call, but a 568 // deferred call. The function value 569 // is itself the *reflect.methodValue. 570 mv = (*reflectMethodValue)(unsafe.Pointer(ctxt)) 571 } else { 572 // This is a real call that took the 573 // *reflect.methodValue as its context 574 // register and immediately saved it 575 // to 0(SP). Get the methodValue from 576 // 0(SP). 577 arg0 := frame.sp + sys.MinFrameSize 578 mv = *(**reflectMethodValue)(unsafe.Pointer(arg0)) 579 } 580 if mv.fn != f.entry { 581 print("runtime: confused by ", funcname(f), "\n") 582 throw("reflect mismatch") 583 } 584 bv := mv.stack 585 arglen = uintptr(bv.n * sys.PtrSize) 586 argmap = bv 587 } 588 } 589 return 590 } 591 592 // tracebackCgoContext handles tracing back a cgo context value, from 593 // the context argument to setCgoTraceback, for the gentraceback 594 // function. It returns the new value of n. 595 func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int { 596 var cgoPCs [32]uintptr 597 cgoContextPCs(ctxt, cgoPCs[:]) 598 var arg cgoSymbolizerArg 599 anySymbolized := false 600 for _, pc := range cgoPCs { 601 if pc == 0 || n >= max { 602 break 603 } 604 if pcbuf != nil { 605 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc 606 } 607 if printing { 608 if cgoSymbolizer == nil { 609 print("non-Go function at pc=", hex(pc), "\n") 610 } else { 611 c := printOneCgoTraceback(pc, max-n, &arg) 612 n += c - 1 // +1 a few lines down 613 anySymbolized = true 614 } 615 } 616 n++ 617 } 618 if anySymbolized { 619 arg.pc = 0 620 callCgoSymbolizer(&arg) 621 } 622 return n 623 } 624 625 func printcreatedby(gp *g) { 626 // Show what created goroutine, except main goroutine (goid 1). 627 pc := gp.gopc 628 f := findfunc(pc) 629 if f.valid() && showframe(f, gp, false, false) && gp.goid != 1 { 630 print("created by ", funcname(f), "\n") 631 tracepc := pc // back up to CALL instruction for funcline. 632 if pc > f.entry { 633 tracepc -= sys.PCQuantum 634 } 635 file, line := funcline(f, tracepc) 636 print("\t", file, ":", line) 637 if pc > f.entry { 638 print(" +", hex(pc-f.entry)) 639 } 640 print("\n") 641 } 642 } 643 644 func traceback(pc, sp, lr uintptr, gp *g) { 645 traceback1(pc, sp, lr, gp, 0) 646 } 647 648 // tracebacktrap is like traceback but expects that the PC and SP were obtained 649 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp. 650 // Because they are from a trap instead of from a saved pair, 651 // the initial PC must not be rewound to the previous instruction. 652 // (All the saved pairs record a PC that is a return address, so we 653 // rewind it into the CALL instruction.) 654 func tracebacktrap(pc, sp, lr uintptr, gp *g) { 655 traceback1(pc, sp, lr, gp, _TraceTrap) 656 } 657 658 func traceback1(pc, sp, lr uintptr, gp *g, flags uint) { 659 // If the goroutine is in cgo, and we have a cgo traceback, print that. 660 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { 661 // Lock cgoCallers so that a signal handler won't 662 // change it, copy the array, reset it, unlock it. 663 // We are locked to the thread and are not running 664 // concurrently with a signal handler. 665 // We just have to stop a signal handler from interrupting 666 // in the middle of our copy. 667 atomic.Store(&gp.m.cgoCallersUse, 1) 668 cgoCallers := *gp.m.cgoCallers 669 gp.m.cgoCallers[0] = 0 670 atomic.Store(&gp.m.cgoCallersUse, 0) 671 672 printCgoTraceback(&cgoCallers) 673 } 674 675 var n int 676 if readgstatus(gp)&^_Gscan == _Gsyscall { 677 // Override registers if blocked in system call. 678 pc = gp.syscallpc 679 sp = gp.syscallsp 680 flags &^= _TraceTrap 681 } 682 // Print traceback. By default, omits runtime frames. 683 // If that means we print nothing at all, repeat forcing all frames printed. 684 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags) 685 if n == 0 && (flags&_TraceRuntimeFrames) == 0 { 686 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames) 687 } 688 if n == _TracebackMaxFrames { 689 print("...additional frames elided...\n") 690 } 691 printcreatedby(gp) 692 } 693 694 func callers(skip int, pcbuf []uintptr) int { 695 sp := getcallersp(unsafe.Pointer(&skip)) 696 pc := getcallerpc() 697 gp := getg() 698 var n int 699 systemstack(func() { 700 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 701 }) 702 return n 703 } 704 705 func gcallers(gp *g, skip int, pcbuf []uintptr) int { 706 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) 707 } 708 709 func showframe(f funcInfo, gp *g, firstFrame, elideWrapper bool) bool { 710 g := getg() 711 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) { 712 return true 713 } 714 level, _, _ := gotraceback() 715 if level > 1 { 716 // Show all frames. 717 return true 718 } 719 720 if !f.valid() { 721 return false 722 } 723 724 if elideWrapper { 725 file, _ := funcline(f, f.entry) 726 if file == "<autogenerated>" { 727 return false 728 } 729 } 730 731 name := funcname(f) 732 733 // Special case: always show runtime.gopanic frame 734 // in the middle of a stack trace, so that we can 735 // see the boundary between ordinary code and 736 // panic-induced deferred code. 737 // See golang.org/issue/5832. 738 if name == "runtime.gopanic" && !firstFrame { 739 return true 740 } 741 742 return contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name)) 743 } 744 745 // isExportedRuntime reports whether name is an exported runtime function. 746 // It is only for runtime functions, so ASCII A-Z is fine. 747 func isExportedRuntime(name string) bool { 748 const n = len("runtime.") 749 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z' 750 } 751 752 // elideWrapperCalling returns whether a wrapper function that called 753 // function "name" should be elided from stack traces. 754 func elideWrapperCalling(name string) bool { 755 // If the wrapper called a panic function instead of the 756 // wrapped function, we want to include it in stacks. 757 return !(name == "runtime.gopanic" || name == "runtime.sigpanic" || name == "runtime.panicwrap") 758 } 759 760 var gStatusStrings = [...]string{ 761 _Gidle: "idle", 762 _Grunnable: "runnable", 763 _Grunning: "running", 764 _Gsyscall: "syscall", 765 _Gwaiting: "waiting", 766 _Gdead: "dead", 767 _Gcopystack: "copystack", 768 } 769 770 func goroutineheader(gp *g) { 771 gpstatus := readgstatus(gp) 772 773 isScan := gpstatus&_Gscan != 0 774 gpstatus &^= _Gscan // drop the scan bit 775 776 // Basic string status 777 var status string 778 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { 779 status = gStatusStrings[gpstatus] 780 } else { 781 status = "???" 782 } 783 784 // Override. 785 if gpstatus == _Gwaiting && gp.waitreason != "" { 786 status = gp.waitreason 787 } 788 789 // approx time the G is blocked, in minutes 790 var waitfor int64 791 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { 792 waitfor = (nanotime() - gp.waitsince) / 60e9 793 } 794 print("goroutine ", gp.goid, " [", status) 795 if isScan { 796 print(" (scan)") 797 } 798 if waitfor >= 1 { 799 print(", ", waitfor, " minutes") 800 } 801 if gp.lockedm != 0 { 802 print(", locked to thread") 803 } 804 print("]:\n") 805 } 806 807 func tracebackothers(me *g) { 808 level, _, _ := gotraceback() 809 810 // Show the current goroutine first, if we haven't already. 811 g := getg() 812 gp := g.m.curg 813 if gp != nil && gp != me { 814 print("\n") 815 goroutineheader(gp) 816 traceback(^uintptr(0), ^uintptr(0), 0, gp) 817 } 818 819 lock(&allglock) 820 for _, gp := range allgs { 821 if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 { 822 continue 823 } 824 print("\n") 825 goroutineheader(gp) 826 // Note: gp.m == g.m occurs when tracebackothers is 827 // called from a signal handler initiated during a 828 // systemstack call. The original G is still in the 829 // running state, and we want to print its stack. 830 if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning { 831 print("\tgoroutine running on other thread; stack unavailable\n") 832 printcreatedby(gp) 833 } else { 834 traceback(^uintptr(0), ^uintptr(0), 0, gp) 835 } 836 } 837 unlock(&allglock) 838 } 839 840 // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp 841 // for debugging purposes. If the address bad is included in the 842 // hexdumped range, it will mark it as well. 843 func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) { 844 const expand = 32 * sys.PtrSize 845 const maxExpand = 256 * sys.PtrSize 846 // Start around frame.sp. 847 lo, hi := frame.sp, frame.sp 848 // Expand to include frame.fp. 849 if frame.fp != 0 && frame.fp < lo { 850 lo = frame.fp 851 } 852 if frame.fp != 0 && frame.fp > hi { 853 hi = frame.fp 854 } 855 // Expand a bit more. 856 lo, hi = lo-expand, hi+expand 857 // But don't go too far from frame.sp. 858 if lo < frame.sp-maxExpand { 859 lo = frame.sp - maxExpand 860 } 861 if hi > frame.sp+maxExpand { 862 hi = frame.sp + maxExpand 863 } 864 // And don't go outside the stack bounds. 865 if lo < stk.lo { 866 lo = stk.lo 867 } 868 if hi > stk.hi { 869 hi = stk.hi 870 } 871 872 // Print the hex dump. 873 print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n") 874 hexdumpWords(lo, hi, func(p uintptr) byte { 875 switch p { 876 case frame.fp: 877 return '>' 878 case frame.sp: 879 return '<' 880 case bad: 881 return '!' 882 } 883 return 0 884 }) 885 } 886 887 // Does f mark the top of a goroutine stack? 888 func topofstack(f funcInfo, g0 bool) bool { 889 return f.funcID == funcID_goexit || 890 f.funcID == funcID_mstart || 891 f.funcID == funcID_mcall || 892 f.funcID == funcID_morestack || 893 f.funcID == funcID_rt0_go || 894 f.funcID == funcID_externalthreadhandler || 895 // asmcgocall is TOS on the system stack because it 896 // switches to the system stack, but in this case we 897 // can come back to the regular stack and still want 898 // to be able to unwind through the call that appeared 899 // on the regular stack. 900 (g0 && f.funcID == funcID_asmcgocall) 901 } 902 903 // isSystemGoroutine reports whether the goroutine g must be omitted in 904 // stack dumps and deadlock detector. 905 func isSystemGoroutine(gp *g) bool { 906 f := findfunc(gp.startpc) 907 if !f.valid() { 908 return false 909 } 910 return f.funcID == funcID_runfinq && !fingRunning || 911 f.funcID == funcID_bgsweep || 912 f.funcID == funcID_forcegchelper || 913 f.funcID == funcID_timerproc || 914 f.funcID == funcID_gcBgMarkWorker 915 } 916 917 // SetCgoTraceback records three C functions to use to gather 918 // traceback information from C code and to convert that traceback 919 // information into symbolic information. These are used when printing 920 // stack traces for a program that uses cgo. 921 // 922 // The traceback and context functions may be called from a signal 923 // handler, and must therefore use only async-signal safe functions. 924 // The symbolizer function may be called while the program is 925 // crashing, and so must be cautious about using memory. None of the 926 // functions may call back into Go. 927 // 928 // The context function will be called with a single argument, a 929 // pointer to a struct: 930 // 931 // struct { 932 // Context uintptr 933 // } 934 // 935 // In C syntax, this struct will be 936 // 937 // struct { 938 // uintptr_t Context; 939 // }; 940 // 941 // If the Context field is 0, the context function is being called to 942 // record the current traceback context. It should record in the 943 // Context field whatever information is needed about the current 944 // point of execution to later produce a stack trace, probably the 945 // stack pointer and PC. In this case the context function will be 946 // called from C code. 947 // 948 // If the Context field is not 0, then it is a value returned by a 949 // previous call to the context function. This case is called when the 950 // context is no longer needed; that is, when the Go code is returning 951 // to its C code caller. This permits the context function to release 952 // any associated resources. 953 // 954 // While it would be correct for the context function to record a 955 // complete a stack trace whenever it is called, and simply copy that 956 // out in the traceback function, in a typical program the context 957 // function will be called many times without ever recording a 958 // traceback for that context. Recording a complete stack trace in a 959 // call to the context function is likely to be inefficient. 960 // 961 // The traceback function will be called with a single argument, a 962 // pointer to a struct: 963 // 964 // struct { 965 // Context uintptr 966 // SigContext uintptr 967 // Buf *uintptr 968 // Max uintptr 969 // } 970 // 971 // In C syntax, this struct will be 972 // 973 // struct { 974 // uintptr_t Context; 975 // uintptr_t SigContext; 976 // uintptr_t* Buf; 977 // uintptr_t Max; 978 // }; 979 // 980 // The Context field will be zero to gather a traceback from the 981 // current program execution point. In this case, the traceback 982 // function will be called from C code. 983 // 984 // Otherwise Context will be a value previously returned by a call to 985 // the context function. The traceback function should gather a stack 986 // trace from that saved point in the program execution. The traceback 987 // function may be called from an execution thread other than the one 988 // that recorded the context, but only when the context is known to be 989 // valid and unchanging. The traceback function may also be called 990 // deeper in the call stack on the same thread that recorded the 991 // context. The traceback function may be called multiple times with 992 // the same Context value; it will usually be appropriate to cache the 993 // result, if possible, the first time this is called for a specific 994 // context value. 995 // 996 // If the traceback function is called from a signal handler on a Unix 997 // system, SigContext will be the signal context argument passed to 998 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be 999 // used to start tracing at the point where the signal occurred. If 1000 // the traceback function is not called from a signal handler, 1001 // SigContext will be zero. 1002 // 1003 // Buf is where the traceback information should be stored. It should 1004 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is 1005 // the PC of that function's caller, and so on. Max is the maximum 1006 // number of entries to store. The function should store a zero to 1007 // indicate the top of the stack, or that the caller is on a different 1008 // stack, presumably a Go stack. 1009 // 1010 // Unlike runtime.Callers, the PC values returned should, when passed 1011 // to the symbolizer function, return the file/line of the call 1012 // instruction. No additional subtraction is required or appropriate. 1013 // 1014 // The symbolizer function will be called with a single argument, a 1015 // pointer to a struct: 1016 // 1017 // struct { 1018 // PC uintptr // program counter to fetch information for 1019 // File *byte // file name (NUL terminated) 1020 // Lineno uintptr // line number 1021 // Func *byte // function name (NUL terminated) 1022 // Entry uintptr // function entry point 1023 // More uintptr // set non-zero if more info for this PC 1024 // Data uintptr // unused by runtime, available for function 1025 // } 1026 // 1027 // In C syntax, this struct will be 1028 // 1029 // struct { 1030 // uintptr_t PC; 1031 // char* File; 1032 // uintptr_t Lineno; 1033 // char* Func; 1034 // uintptr_t Entry; 1035 // uintptr_t More; 1036 // uintptr_t Data; 1037 // }; 1038 // 1039 // The PC field will be a value returned by a call to the traceback 1040 // function. 1041 // 1042 // The first time the function is called for a particular traceback, 1043 // all the fields except PC will be 0. The function should fill in the 1044 // other fields if possible, setting them to 0/nil if the information 1045 // is not available. The Data field may be used to store any useful 1046 // information across calls. The More field should be set to non-zero 1047 // if there is more information for this PC, zero otherwise. If More 1048 // is set non-zero, the function will be called again with the same 1049 // PC, and may return different information (this is intended for use 1050 // with inlined functions). If More is zero, the function will be 1051 // called with the next PC value in the traceback. When the traceback 1052 // is complete, the function will be called once more with PC set to 1053 // zero; this may be used to free any information. Each call will 1054 // leave the fields of the struct set to the same values they had upon 1055 // return, except for the PC field when the More field is zero. The 1056 // function must not keep a copy of the struct pointer between calls. 1057 // 1058 // When calling SetCgoTraceback, the version argument is the version 1059 // number of the structs that the functions expect to receive. 1060 // Currently this must be zero. 1061 // 1062 // The symbolizer function may be nil, in which case the results of 1063 // the traceback function will be displayed as numbers. If the 1064 // traceback function is nil, the symbolizer function will never be 1065 // called. The context function may be nil, in which case the 1066 // traceback function will only be called with the context field set 1067 // to zero. If the context function is nil, then calls from Go to C 1068 // to Go will not show a traceback for the C portion of the call stack. 1069 // 1070 // SetCgoTraceback should be called only once, ideally from an init function. 1071 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) { 1072 if version != 0 { 1073 panic("unsupported version") 1074 } 1075 1076 if cgoTraceback != nil && cgoTraceback != traceback || 1077 cgoContext != nil && cgoContext != context || 1078 cgoSymbolizer != nil && cgoSymbolizer != symbolizer { 1079 panic("call SetCgoTraceback only once") 1080 } 1081 1082 cgoTraceback = traceback 1083 cgoContext = context 1084 cgoSymbolizer = symbolizer 1085 1086 // The context function is called when a C function calls a Go 1087 // function. As such it is only called by C code in runtime/cgo. 1088 if _cgo_set_context_function != nil { 1089 cgocall(_cgo_set_context_function, context) 1090 } 1091 } 1092 1093 var cgoTraceback unsafe.Pointer 1094 var cgoContext unsafe.Pointer 1095 var cgoSymbolizer unsafe.Pointer 1096 1097 // cgoTracebackArg is the type passed to cgoTraceback. 1098 type cgoTracebackArg struct { 1099 context uintptr 1100 sigContext uintptr 1101 buf *uintptr 1102 max uintptr 1103 } 1104 1105 // cgoContextArg is the type passed to the context function. 1106 type cgoContextArg struct { 1107 context uintptr 1108 } 1109 1110 // cgoSymbolizerArg is the type passed to cgoSymbolizer. 1111 type cgoSymbolizerArg struct { 1112 pc uintptr 1113 file *byte 1114 lineno uintptr 1115 funcName *byte 1116 entry uintptr 1117 more uintptr 1118 data uintptr 1119 } 1120 1121 // cgoTraceback prints a traceback of callers. 1122 func printCgoTraceback(callers *cgoCallers) { 1123 if cgoSymbolizer == nil { 1124 for _, c := range callers { 1125 if c == 0 { 1126 break 1127 } 1128 print("non-Go function at pc=", hex(c), "\n") 1129 } 1130 return 1131 } 1132 1133 var arg cgoSymbolizerArg 1134 for _, c := range callers { 1135 if c == 0 { 1136 break 1137 } 1138 printOneCgoTraceback(c, 0x7fffffff, &arg) 1139 } 1140 arg.pc = 0 1141 callCgoSymbolizer(&arg) 1142 } 1143 1144 // printOneCgoTraceback prints the traceback of a single cgo caller. 1145 // This can print more than one line because of inlining. 1146 // Returns the number of frames printed. 1147 func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int { 1148 c := 0 1149 arg.pc = pc 1150 for { 1151 if c > max { 1152 break 1153 } 1154 callCgoSymbolizer(arg) 1155 if arg.funcName != nil { 1156 // Note that we don't print any argument 1157 // information here, not even parentheses. 1158 // The symbolizer must add that if appropriate. 1159 println(gostringnocopy(arg.funcName)) 1160 } else { 1161 println("non-Go function") 1162 } 1163 print("\t") 1164 if arg.file != nil { 1165 print(gostringnocopy(arg.file), ":", arg.lineno, " ") 1166 } 1167 print("pc=", hex(pc), "\n") 1168 c++ 1169 if arg.more == 0 { 1170 break 1171 } 1172 } 1173 return c 1174 } 1175 1176 // callCgoSymbolizer calls the cgoSymbolizer function. 1177 func callCgoSymbolizer(arg *cgoSymbolizerArg) { 1178 call := cgocall 1179 if panicking > 0 || getg().m.curg != getg() { 1180 // We do not want to call into the scheduler when panicking 1181 // or when on the system stack. 1182 call = asmcgocall 1183 } 1184 if msanenabled { 1185 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) 1186 } 1187 call(cgoSymbolizer, noescape(unsafe.Pointer(arg))) 1188 } 1189 1190 // cgoContextPCs gets the PC values from a cgo traceback. 1191 func cgoContextPCs(ctxt uintptr, buf []uintptr) { 1192 if cgoTraceback == nil { 1193 return 1194 } 1195 call := cgocall 1196 if panicking > 0 || getg().m.curg != getg() { 1197 // We do not want to call into the scheduler when panicking 1198 // or when on the system stack. 1199 call = asmcgocall 1200 } 1201 arg := cgoTracebackArg{ 1202 context: ctxt, 1203 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))), 1204 max: uintptr(len(buf)), 1205 } 1206 if msanenabled { 1207 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) 1208 } 1209 call(cgoTraceback, noescape(unsafe.Pointer(&arg))) 1210 }