// Copyright 2013 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package runtimeimport ()/*Stack layout parameters.Included both by runtime (compiled via 6c) and linkers (compiled via gcc).The per-goroutine g->stackguard is set to point StackGuard bytesabove the bottom of the stack. Each function compares its stackpointer against g->stackguard to check for overflow. To cut oneinstruction from the check sequence for functions with tiny frames,the stack is allowed to protrude StackSmall bytes below the stackguard. Functions with large frames don't bother with the check andalways call morestack. The sequences are (for amd64, others aresimilar): guard = g->stackguard frame = function's stack frame size argsize = size of function arguments (call + return) stack frame size <= StackSmall: CMPQ guard, SP JHI 3(PC) MOVQ m->morearg, $(argsize << 32) CALL morestack(SB) stack frame size > StackSmall but < StackBig LEAQ (frame-StackSmall)(SP), R0 CMPQ guard, R0 JHI 3(PC) MOVQ m->morearg, $(argsize << 32) CALL morestack(SB) stack frame size >= StackBig: MOVQ m->morearg, $((argsize << 32) | frame) CALL morestack(SB)The bottom StackGuard - StackSmall bytes are important: there hasto be enough room to execute functions that refuse to check forstack overflow, either because they need to be adjacent to theactual caller's frame (deferproc) or because they handle the imminentstack overflow (morestack).For example, deferproc might call malloc, which does one of theabove checks (without allocating a full frame), which might triggera call to morestack. This sequence needs to fit in the bottomsection of the stack. On amd64, morestack's frame is 40 bytes, anddeferproc's frame is 56 bytes. That fits well within theStackGuard - StackSmall bytes at the bottom.The linkers explore all possible call traces involving non-splittingfunctions to make sure that this limit cannot be violated.*/const (// stackSystem is a number of additional bytes to add // to each stack below the usual guard area for OS-specific // purposes like signal handling. Used on Windows, Plan 9, // and iOS because they do not use a separate stack. stackSystem = goos.IsWindows*512*goarch.PtrSize + goos.IsPlan9*512 + goos.IsIos*goarch.IsArm64*1024// The minimum size of stack used by Go code stackMin = 2048// The minimum stack size to allocate. // The hackery here rounds fixedStack0 up to a power of 2. fixedStack0 = stackMin + stackSystem fixedStack1 = fixedStack0 - 1 fixedStack2 = fixedStack1 | (fixedStack1 >> 1) fixedStack3 = fixedStack2 | (fixedStack2 >> 2) fixedStack4 = fixedStack3 | (fixedStack3 >> 4) fixedStack5 = fixedStack4 | (fixedStack4 >> 8) fixedStack6 = fixedStack5 | (fixedStack5 >> 16) fixedStack = fixedStack6 + 1// stackNosplit is the maximum number of bytes that a chain of NOSPLIT // functions can use. // This arithmetic must match that in cmd/internal/objabi/stack.go:StackNosplit. stackNosplit = abi.StackNosplitBase * sys.StackGuardMultiplier// The stack guard is a pointer this many bytes above the // bottom of the stack. // // The guard leaves enough room for a stackNosplit chain of NOSPLIT calls // plus one stackSmall frame plus stackSystem bytes for the OS. // This arithmetic must match that in cmd/internal/objabi/stack.go:StackLimit. stackGuard = stackNosplit + stackSystem + abi.StackSmall)const (// stackDebug == 0: no logging // == 1: logging of per-stack operations // == 2: logging of per-frame operations // == 3: logging of per-word updates // == 4: logging of per-word reads stackDebug = 0 stackFromSystem = 0// allocate stacks from system memory instead of the heap stackFaultOnFree = 0// old stacks are mapped noaccess to detect use after free stackNoCache = 0// disable per-P small stack caches// check the BP links during traceback. debugCheckBP = false)var ( stackPoisonCopy = 0// fill stack that should not be accessed with garbage, to detect bad dereferences during copy)const ( uintptrMask = 1<<(8*goarch.PtrSize) - 1// The values below can be stored to g.stackguard0 to force // the next stack check to fail. // These are all larger than any real SP.// Goroutine preemption request. // 0xfffffade in hex. stackPreempt = uintptrMask & -1314// Thread is forking. Causes a split stack check failure. // 0xfffffb2e in hex. stackFork = uintptrMask & -1234// Force a stack movement. Used for debugging. // 0xfffffeed in hex. stackForceMove = uintptrMask & -275// stackPoisonMin is the lowest allowed stack poison value. stackPoisonMin = uintptrMask & -4096)// Global pool of spans that have free stacks.// Stacks are assigned an order according to size.//// order = log_2(size/FixedStack)//// There is a free list for each order.var stackpool [_NumStackOrders]struct { item stackpoolItem _ [(cpu.CacheLinePadSize - unsafe.Sizeof(stackpoolItem{})%cpu.CacheLinePadSize) % cpu.CacheLinePadSize]byte}type stackpoolItem struct { _ sys.NotInHeap mu mutex span mSpanList}// Global pool of large stack spans.var stackLarge struct { lock mutex free [heapAddrBits - pageShift]mSpanList// free lists by log_2(s.npages)}func stackinit() {if_StackCacheSize&_PageMask != 0 {throw("cache size must be a multiple of page size") }for := rangestackpool {stackpool[].item.span.init()lockInit(&stackpool[].item.mu, lockRankStackpool) }for := rangestackLarge.free {stackLarge.free[].init()lockInit(&stackLarge.lock, lockRankStackLarge) }}// stacklog2 returns ⌊log_2(n)⌋.func stacklog2( uintptr) int { := 0for > 1 { >>= 1 ++ }return}// Allocates a stack from the free pool. Must be called with// stackpool[order].item.mu held.func stackpoolalloc( uint8) gclinkptr { := &stackpool[].item.span := .firstlockWithRankMayAcquire(&mheap_.lock, lockRankMheap)if == nil {// no free stacks. Allocate another span worth. = mheap_.allocManual(_StackCacheSize>>_PageShift, spanAllocStack)if == nil {throw("out of memory") }if .allocCount != 0 {throw("bad allocCount") }if .manualFreeList.ptr() != nil {throw("bad manualFreeList") }osStackAlloc() .elemsize = fixedStack << for := uintptr(0); < _StackCacheSize; += .elemsize { := gclinkptr(.base() + ) .ptr().next = .manualFreeList .manualFreeList = } .insert() } := .manualFreeListif .ptr() == nil {throw("span has no free stacks") } .manualFreeList = .ptr().next .allocCount++if .manualFreeList.ptr() == nil {// all stacks in s are allocated. .remove() }return}// Adds stack x to the free pool. Must be called with stackpool[order].item.mu held.func stackpoolfree( gclinkptr, uint8) { := spanOfUnchecked(uintptr())if .state.get() != mSpanManual {throw("freeing stack not in a stack span") }if .manualFreeList.ptr() == nil {// s will now have a free stackstackpool[].item.span.insert() } .ptr().next = .manualFreeList .manualFreeList = .allocCount--ifgcphase == _GCoff && .allocCount == 0 {// Span is completely free. Return it to the heap // immediately if we're sweeping. // // If GC is active, we delay the free until the end of // GC to avoid the following type of situation: // // 1) GC starts, scans a SudoG but does not yet mark the SudoG.elem pointer // 2) The stack that pointer points to is copied // 3) The old stack is freed // 4) The containing span is marked free // 5) GC attempts to mark the SudoG.elem pointer. The // marking fails because the pointer looks like a // pointer into a free span. // // By not freeing, we prevent step #4 until GC is done.stackpool[].item.span.remove() .manualFreeList = 0osStackFree()mheap_.freeManual(, spanAllocStack) }}// stackcacherefill/stackcacherelease implement a global pool of stack segments.// The pool is required to prevent unlimited growth of per-thread caches.////go:systemstackfunc stackcacherefill( *mcache, uint8) {ifstackDebug >= 1 {print("stackcacherefill order=", , "\n") }// Grab some stacks from the global cache. // Grab half of the allowed capacity (to prevent thrashing).vargclinkptrvaruintptrlock(&stackpool[].item.mu)for < _StackCacheSize/2 { := stackpoolalloc() .ptr().next = = += fixedStack << }unlock(&stackpool[].item.mu) .stackcache[].list = .stackcache[].size = }//go:systemstackfunc stackcacherelease( *mcache, uint8) {ifstackDebug >= 1 {print("stackcacherelease order=", , "\n") } := .stackcache[].list := .stackcache[].sizelock(&stackpool[].item.mu)for > _StackCacheSize/2 { := .ptr().nextstackpoolfree(, ) = -= fixedStack << }unlock(&stackpool[].item.mu) .stackcache[].list = .stackcache[].size = }//go:systemstackfunc stackcache_clear( *mcache) {ifstackDebug >= 1 {print("stackcache clear\n") }for := uint8(0); < _NumStackOrders; ++ {lock(&stackpool[].item.mu) := .stackcache[].listfor .ptr() != nil { := .ptr().nextstackpoolfree(, ) = } .stackcache[].list = 0 .stackcache[].size = 0unlock(&stackpool[].item.mu) }}// stackalloc allocates an n byte stack.//// stackalloc must run on the system stack because it uses per-P// resources and must not split the stack.////go:systemstackfunc stackalloc( uint32) stack {// Stackalloc must be called on scheduler stack, so that we // never try to grow the stack during the code that stackalloc runs. // Doing so would cause a deadlock (issue 1547). := getg()if != .m.g0 {throw("stackalloc not on scheduler stack") }if &(-1) != 0 {throw("stack size not a power of 2") }ifstackDebug >= 1 {print("stackalloc ", , "\n") }ifdebug.efence != 0 || stackFromSystem != 0 { = uint32(alignUp(uintptr(), physPageSize)) := sysAlloc(uintptr(), &memstats.stacks_sys)if == nil {throw("out of memory (stackalloc)") }returnstack{uintptr(), uintptr() + uintptr()} }// Small stacks are allocated with a fixed-size free-list allocator. // If we need a stack of a bigger size, we fall back on allocating // a dedicated span.varunsafe.Pointerif < fixedStack<<_NumStackOrders && < _StackCacheSize { := uint8(0) := for > fixedStack { ++ >>= 1 }vargclinkptrifstackNoCache != 0 || .m.p == 0 || .m.preemptoff != "" {// thisg.m.p == 0 can happen in the guts of exitsyscall // or procresize. Just get a stack from the global pool. // Also don't touch stackcache during gc // as it's flushed concurrently.lock(&stackpool[].item.mu) = stackpoolalloc()unlock(&stackpool[].item.mu) } else { := .m.p.ptr().mcache = .stackcache[].listif .ptr() == nil {stackcacherefill(, ) = .stackcache[].list } .stackcache[].list = .ptr().next .stackcache[].size -= uintptr() } = unsafe.Pointer() } else {var *mspan := uintptr() >> _PageShift := stacklog2()// Try to get a stack from the large stack cache.lock(&stackLarge.lock)if !stackLarge.free[].isEmpty() { = stackLarge.free[].firststackLarge.free[].remove() }unlock(&stackLarge.lock)lockWithRankMayAcquire(&mheap_.lock, lockRankMheap)if == nil {// Allocate a new stack from the heap. = mheap_.allocManual(, spanAllocStack)if == nil {throw("out of memory") }osStackAlloc() .elemsize = uintptr() } = unsafe.Pointer(.base()) }iftraceAllocFreeEnabled() { := traceTryAcquire()if .ok() { .GoroutineStackAlloc(uintptr(), uintptr())traceRelease() } }ifraceenabled {racemalloc(, uintptr()) }ifmsanenabled {msanmalloc(, uintptr()) }ifasanenabled {asanunpoison(, uintptr()) }ifstackDebug >= 1 {print(" allocated ", , "\n") }returnstack{uintptr(), uintptr() + uintptr()}}// stackfree frees an n byte stack allocation at stk.//// stackfree must run on the system stack because it uses per-P// resources and must not split the stack.////go:systemstackfunc stackfree( stack) { := getg() := unsafe.Pointer(.lo) := .hi - .loif &(-1) != 0 {throw("stack not a power of 2") }if .lo+ < .hi {throw("bad stack size") }ifstackDebug >= 1 {println("stackfree", , )memclrNoHeapPointers(, ) // for testing, clobber stack data }ifdebug.efence != 0 || stackFromSystem != 0 {ifdebug.efence != 0 || stackFaultOnFree != 0 {sysFault(, ) } else {sysFree(, , &memstats.stacks_sys) }return }iftraceAllocFreeEnabled() { := traceTryAcquire()if .ok() { .GoroutineStackFree(uintptr())traceRelease() } }ifmsanenabled {msanfree(, ) }ifasanenabled {asanpoison(, ) }if < fixedStack<<_NumStackOrders && < _StackCacheSize { := uint8(0) := for > fixedStack { ++ >>= 1 } := gclinkptr()ifstackNoCache != 0 || .m.p == 0 || .m.preemptoff != "" {lock(&stackpool[].item.mu)stackpoolfree(, )unlock(&stackpool[].item.mu) } else { := .m.p.ptr().mcacheif .stackcache[].size >= _StackCacheSize {stackcacherelease(, ) } .ptr().next = .stackcache[].list .stackcache[].list = .stackcache[].size += } } else { := spanOfUnchecked(uintptr())if .state.get() != mSpanManual {println(hex(.base()), )throw("bad span state") }ifgcphase == _GCoff {// Free the stack immediately if we're // sweeping.osStackFree()mheap_.freeManual(, spanAllocStack) } else {// If the GC is running, we can't return a // stack span to the heap because it could be // reused as a heap span, and this state // change would race with GC. Add it to the // large stack cache instead. := stacklog2(.npages)lock(&stackLarge.lock)stackLarge.free[].insert()unlock(&stackLarge.lock) } }}var maxstacksize uintptr = 1 << 20// enough until runtime.main sets it for realvar maxstackceiling = maxstacksizevar ptrnames = []string{0: "scalar",1: "ptr",}// Stack frame layout//// (x86)// +------------------+// | args from caller |// +------------------+ <- frame->argp// | return address |// +------------------+// | caller's BP (*) | (*) if framepointer_enabled && varp > sp// +------------------+ <- frame->varp// | locals |// +------------------+// | args to callee |// +------------------+ <- frame->sp//// (arm)// +------------------+// | args from caller |// +------------------+ <- frame->argp// | caller's retaddr |// +------------------+// | caller's FP (*) | (*) on ARM64, if framepointer_enabled && varp > sp// +------------------+ <- frame->varp// | locals |// +------------------+// | args to callee |// +------------------+// | return address |// +------------------+ <- frame->sp//// varp > sp means that the function has a frame;// varp == sp means frameless function.type adjustinfo struct { old stack delta uintptr// ptr distance from old to new stack (newbase - oldbase)// sghi is the highest sudog.elem on the stack. sghi uintptr}// adjustpointer checks whether *vpp is in the old stack described by adjinfo.// If so, it rewrites *vpp to point into the new stack.func adjustpointer( *adjustinfo, unsafe.Pointer) { := (*uintptr)() := *ifstackDebug >= 4 {print(" ", , ":", hex(), "\n") }if .old.lo <= && < .old.hi { * = + .deltaifstackDebug >= 3 {print(" adjust ptr ", , ":", hex(), " -> ", hex(*), "\n") } }}// Information from the compiler about the layout of stack frames.// Note: this type must agree with reflect.bitVector.type bitvector struct { n int32// # of bits bytedata *uint8}// ptrbit returns the i'th bit in bv.// ptrbit is less efficient than iterating directly over bitvector bits,// and should only be used in non-performance-critical code.// See adjustpointers for an example of a high-efficiency walk of a bitvector.func ( *bitvector) ( uintptr) uint8 { := *(addb(.bytedata, /8))return ( >> ( % 8)) & 1}// bv describes the memory starting at address scanp.// Adjust any pointers contained therein.func adjustpointers( unsafe.Pointer, *bitvector, *adjustinfo, funcInfo) { := .old.lo := .old.hi := .delta := uintptr(.n)// If this frame might contain channel receive slots, use CAS // to adjust pointers. If the slot hasn't been received into // yet, it may contain stack pointers and a concurrent send // could race with adjusting those pointers. (The sent value // itself can never contain stack pointers.) := uintptr() < .sghifor := uintptr(0); < ; += 8 {ifstackDebug >= 4 {for := uintptr(0); < 8; ++ {print(" ", add(, (+)*goarch.PtrSize), ":", ptrnames[.ptrbit(+)], ":", hex(*(*uintptr)(add(, (+)*goarch.PtrSize))), " # ", , " ", *addb(.bytedata, /8), "\n") } } := *(addb(.bytedata, /8))for != 0 { := uintptr(sys.TrailingZeros8()) &= - 1 := (*uintptr)(add(, (+)*goarch.PtrSize)) : := *if .valid() && 0 < && < minLegalPointer && debug.invalidptr != 0 {// Looks like a junk value in a pointer slot. // Live analysis wrong?getg().m.traceback = 2print("runtime: bad pointer in frame ", funcname(), " at ", , ": ", hex(), "\n")throw("invalid pointer found on stack") }if <= && < {ifstackDebug >= 3 {print("adjust ptr ", hex(), " ", funcname(), "\n") }if { := (*unsafe.Pointer)(unsafe.Pointer())if !atomic.Casp1(, unsafe.Pointer(), unsafe.Pointer(+)) {goto } } else { * = + } } } }}// Note: the argument/return area is adjusted by the callee.func adjustframe( *stkframe, *adjustinfo) {if .continpc == 0 {// Frame is dead.return } := .fnifstackDebug >= 2 {print(" adjusting ", funcname(), " frame=[", hex(.sp), ",", hex(.fp), "] pc=", hex(.pc), " continpc=", hex(.continpc), "\n") }// Adjust saved frame pointer if there is one.if (goarch.ArchFamily == goarch.AMD64 || goarch.ArchFamily == goarch.ARM64) && .argp-.varp == 2*goarch.PtrSize {ifstackDebug >= 3 {print(" saved bp\n") }ifdebugCheckBP {// Frame pointers should always point to the next higher frame on // the Go stack (or be nil, for the top frame on the stack). := *(*uintptr)(unsafe.Pointer(.varp))if != 0 && ( < .old.lo || >= .old.hi) {println("runtime: found invalid frame pointer")print("bp=", hex(), " min=", hex(.old.lo), " max=", hex(.old.hi), "\n")throw("bad frame pointer") } }// On AMD64, this is the caller's frame pointer saved in the current // frame. // On ARM64, this is the frame pointer of the caller's caller saved // by the caller in its frame (one word below its SP).adjustpointer(, unsafe.Pointer(.varp)) } , , := .getStackMap(true)// Adjust local variables if stack frame has been allocated.if .n > 0 { := uintptr(.n) * goarch.PtrSizeadjustpointers(unsafe.Pointer(.varp-), &, , ) }// Adjust arguments.if .n > 0 {ifstackDebug >= 3 {print(" args\n") }adjustpointers(unsafe.Pointer(.argp), &, , funcInfo{}) }// Adjust pointers in all stack objects (whether they are live or not). // See comments in mgcmark.go:scanframeworker.if .varp != 0 {for := range { := &[] := .off := .varp// locals base pointerif >= 0 { = .argp// arguments and return values base pointer } := + uintptr()if < .sp {// Object hasn't been allocated in the frame yet. // (Happens when the stack bounds check fails and // we call into morestack.)continue } := .ptrdata() := .gcdata()var *mspanif .useGCProg() {// See comments in mgcmark.go:scanstack = materializeGCProg(, ) = (*byte)(unsafe.Pointer(.startAddr)) }for := uintptr(0); < ; += goarch.PtrSize {if *addb(, /(8*goarch.PtrSize))>>(/goarch.PtrSize&7)&1 != 0 {adjustpointer(, unsafe.Pointer(+)) } }if != nil {dematerializeGCProg() } } }}func adjustctxt( *g, *adjustinfo) {adjustpointer(, unsafe.Pointer(&.sched.ctxt))if !framepointer_enabled {return }ifdebugCheckBP { := .sched.bpif != 0 && ( < .old.lo || >= .old.hi) {println("runtime: found invalid top frame pointer")print("bp=", hex(), " min=", hex(.old.lo), " max=", hex(.old.hi), "\n")throw("bad top frame pointer") } } := .sched.bpadjustpointer(, unsafe.Pointer(&.sched.bp))ifGOARCH == "arm64" {// On ARM64, the frame pointer is saved one word *below* the SP, // which is not copied or adjusted in any frame. Do it explicitly // here.if == .sched.sp-goarch.PtrSize {memmove(unsafe.Pointer(.sched.bp), unsafe.Pointer(), goarch.PtrSize)adjustpointer(, unsafe.Pointer(.sched.bp)) } }}func adjustdefers( *g, *adjustinfo) {// Adjust pointers in the Defer structs. // We need to do this first because we need to adjust the // defer.link fields so we always work on the new stack.adjustpointer(, unsafe.Pointer(&._defer))for := ._defer; != nil; = .link {adjustpointer(, unsafe.Pointer(&.fn))adjustpointer(, unsafe.Pointer(&.sp))adjustpointer(, unsafe.Pointer(&.link)) }}func adjustpanics( *g, *adjustinfo) {// Panics are on stack and already adjusted. // Update pointer to head of list in G.adjustpointer(, unsafe.Pointer(&._panic))}func adjustsudogs( *g, *adjustinfo) {// the data elements pointed to by a SudoG structure // might be in the stack.for := .waiting; != nil; = .waitlink {adjustpointer(, unsafe.Pointer(&.elem)) }}func fillstack( stack, byte) {for := .lo; < .hi; ++ { *(*byte)(unsafe.Pointer()) = }}func findsghi( *g, stack) uintptr {varuintptrfor := .waiting; != nil; = .waitlink { := uintptr(.elem) + uintptr(.c.elemsize)if .lo <= && < .hi && > { = } }return}// syncadjustsudogs adjusts gp's sudogs and copies the part of gp's// stack they refer to while synchronizing with concurrent channel// operations. It returns the number of bytes of stack copied.func syncadjustsudogs( *g, uintptr, *adjustinfo) uintptr {if .waiting == nil {return0 }// Lock channels to prevent concurrent send/receive.var *hchanfor := .waiting; != nil; = .waitlink {if .c != {// There is a ranking cycle here between gscan bit and // hchan locks. Normally, we only allow acquiring hchan // locks and then getting a gscan bit. In this case, we // already have the gscan bit. We allow acquiring hchan // locks here as a special case, since a deadlock can't // happen because the G involved must already be // suspended. So, we get a special hchan lock rank here // that is lower than gscan, but doesn't allow acquiring // any other locks other than hchan.lockWithRank(&.c.lock, lockRankHchanLeaf) } = .c }// Adjust sudogs.adjustsudogs(, )// Copy the part of the stack the sudogs point in to // while holding the lock to prevent races on // send/receive slots.varuintptrif .sghi != 0 { := .old.hi - := + .delta = .sghi - memmove(unsafe.Pointer(), unsafe.Pointer(), ) }// Unlock channels. = nilfor := .waiting; != nil; = .waitlink {if .c != {unlock(&.c.lock) } = .c }return}// Copies gp's stack to a new stack of a different size.// Caller must have changed gp status to Gcopystack.func copystack( *g, uintptr) {if .syscallsp != 0 {throw("stack growth not allowed in system call") } := .stackif .lo == 0 {throw("nil stackbase") } := .hi - .sched.sp// Add just the difference to gcController.addScannableStack. // g0 stacks never move, so this will never account for them. // It's also fine if we have no P, addScannableStack can deal with // that case.gcController.addScannableStack(getg().m.p.ptr(), int64()-int64(.hi-.lo))// allocate new stack := stackalloc(uint32())ifstackPoisonCopy != 0 {fillstack(, 0xfd) }ifstackDebug >= 1 {print("copystack gp=", , " [", hex(.lo), " ", hex(.hi-), " ", hex(.hi), "]", " -> [", hex(.lo), " ", hex(.hi-), " ", hex(.hi), "]/", , "\n") }// Compute adjustment.varadjustinfo .old = .delta = .hi - .hi// Adjust sudogs, synchronizing with channel ops if necessary. := if !.activeStackChans {if < .hi-.lo && .parkingOnChan.Load() {// It's not safe for someone to shrink this stack while we're actively // parking on a channel, but it is safe to grow since we do that // ourselves and explicitly don't want to synchronize with channels // since we could self-deadlock.throw("racy sudog adjustment due to parking on channel") }adjustsudogs(, &) } else {// sudogs may be pointing in to the stack and gp has // released channel locks, so other goroutines could // be writing to gp's stack. Find the highest such // pointer so we can handle everything there and below // carefully. (This shouldn't be far from the bottom // of the stack, so there's little cost in handling // everything below it carefully.) .sghi = findsghi(, )// Synchronize with channel ops and copy the part of // the stack they may interact with. -= syncadjustsudogs(, , &) }// Copy the stack (or the rest of it) to the new locationmemmove(unsafe.Pointer(.hi-), unsafe.Pointer(.hi-), )// Adjust remaining structures that have pointers into stacks. // We have to do most of these before we traceback the new // stack because gentraceback uses them.adjustctxt(, &)adjustdefers(, &)adjustpanics(, &)if .sghi != 0 { .sghi += .delta }// Swap out old stack for new one .stack = .stackguard0 = .lo + stackGuard// NOTE: might clobber a preempt request .sched.sp = .hi - .stktopsp += .delta// Adjust pointers in the new stack.varunwinderfor .init(, 0); .valid(); .next() {adjustframe(&.frame, &) }// free old stackifstackPoisonCopy != 0 {fillstack(, 0xfc) }stackfree()}// round x up to a power of 2.func round2( int32) int32 { := uint(0)for1<< < { ++ }return1 << }// Called from runtime·morestack when more stack is needed.// Allocate larger stack and relocate to new stack.// Stack growth is multiplicative, for constant amortized cost.//// g->atomicstatus will be Grunning or Gscanrunning upon entry.// If the scheduler is trying to stop this g, then it will set preemptStop.//// This must be nowritebarrierrec because it can be called as part of// stack growth from other nowritebarrierrec functions, but the// compiler doesn't check this.////go:nowritebarrierrecfunc newstack() { := getg()// TODO: double check all gp. shouldn't be getg().if .m.morebuf.g.ptr().stackguard0 == stackFork {throw("stack growth after fork") }if .m.morebuf.g.ptr() != .m.curg {print("runtime: newstack called from g=", hex(.m.morebuf.g), "\n"+"\tm=", .m, " m->curg=", .m.curg, " m->g0=", .m.g0, " m->gsignal=", .m.gsignal, "\n") := .m.morebuftraceback(.pc, .sp, .lr, .g.ptr())throw("runtime: wrong goroutine in newstack") } := .m.curgif .m.curg.throwsplit {// Update syscallsp, syscallpc in case traceback uses them. := .m.morebuf .syscallsp = .sp .syscallpc = .pc , := "(unknown)", uintptr(0) := findfunc(.sched.pc)if .valid() { = funcname() = .sched.pc - .entry() }print("runtime: newstack at ", , "+", hex()," sp=", hex(.sched.sp), " stack=[", hex(.stack.lo), ", ", hex(.stack.hi), "]\n","\tmorebuf={pc:", hex(.pc), " sp:", hex(.sp), " lr:", hex(.lr), "}\n","\tsched={pc:", hex(.sched.pc), " sp:", hex(.sched.sp), " lr:", hex(.sched.lr), " ctxt:", .sched.ctxt, "}\n") .m.traceback = 2// Include runtime framestraceback(.pc, .sp, .lr, )throw("runtime: stack split at bad time") } := .m.morebuf .m.morebuf.pc = 0 .m.morebuf.lr = 0 .m.morebuf.sp = 0 .m.morebuf.g = 0// NOTE: stackguard0 may change underfoot, if another thread // is about to try to preempt gp. Read it just once and use that same // value now and below. := atomic.Loaduintptr(&.stackguard0)// Be conservative about where we preempt. // We are interested in preempting user Go code, not runtime code. // If we're holding locks, mallocing, or preemption is disabled, don't // preempt. // This check is very early in newstack so that even the status change // from Grunning to Gwaiting and back doesn't happen in this case. // That status change by itself can be viewed as a small preemption, // because the GC might change Gwaiting to Gscanwaiting, and then // this goroutine has to wait for the GC to finish before continuing. // If the GC is in some way dependent on this goroutine (for example, // it needs a lock held by the goroutine), that small preemption turns // into a real deadlock. := == stackPreemptif {if !canPreemptM(.m) {// Let the goroutine keep running for now. // gp->preempt is set, so it will be preempted next time. .stackguard0 = .stack.lo + stackGuardgogo(&.sched) // never return } }if .stack.lo == 0 {throw("missing stack in newstack") } := .sched.spifgoarch.ArchFamily == goarch.AMD64 || goarch.ArchFamily == goarch.I386 || goarch.ArchFamily == goarch.WASM {// The call to morestack cost a word. -= goarch.PtrSize }ifstackDebug >= 1 || < .stack.lo {print("runtime: newstack sp=", hex(), " stack=[", hex(.stack.lo), ", ", hex(.stack.hi), "]\n","\tmorebuf={pc:", hex(.pc), " sp:", hex(.sp), " lr:", hex(.lr), "}\n","\tsched={pc:", hex(.sched.pc), " sp:", hex(.sched.sp), " lr:", hex(.sched.lr), " ctxt:", .sched.ctxt, "}\n") }if < .stack.lo {print("runtime: gp=", , ", goid=", .goid, ", gp->status=", hex(readgstatus()), "\n ")print("runtime: split stack overflow: ", hex(), " < ", hex(.stack.lo), "\n")throw("runtime: split stack overflow") }if {if == .m.g0 {throw("runtime: preempt g0") }if .m.p == 0 && .m.locks == 0 {throw("runtime: g is running but p is not") }if .preemptShrink {// We're at a synchronous safe point now, so // do the pending stack shrink. .preemptShrink = falseshrinkstack() }if .preemptStop {preemptPark() // never returns }// Act like goroutine called runtime.Gosched.gopreempt_m() // never return }// Allocate a bigger segment and move the stack. := .stack.hi - .stack.lo := * 2// Make sure we grow at least as much as needed to fit the new frame. // (This is just an optimization - the caller of morestack will // recheck the bounds on return.)if := findfunc(.sched.pc); .valid() { := uintptr(funcMaxSPDelta()) := + stackGuard := .stack.hi - .sched.spfor - < { *= 2 } }if == stackForceMove {// Forced stack movement used for debugging. // Don't double the stack (or we may quickly run out // if this is done repeatedly). = }if > maxstacksize || > maxstackceiling {ifmaxstacksize < maxstackceiling {print("runtime: goroutine stack exceeds ", maxstacksize, "-byte limit\n") } else {print("runtime: goroutine stack exceeds ", maxstackceiling, "-byte limit\n") }print("runtime: sp=", hex(), " stack=[", hex(.stack.lo), ", ", hex(.stack.hi), "]\n")throw("stack overflow") }// The goroutine must be executing in order to call newstack, // so it must be Grunning (or Gscanrunning).casgstatus(, _Grunning, _Gcopystack)// The concurrent GC will not scan the stack while we are doing the copy since // the gp is in a Gcopystack status.copystack(, )ifstackDebug >= 1 {print("stack grow done\n") }casgstatus(, _Gcopystack, _Grunning)gogo(&.sched)}//go:nosplitfunc nilfunc() { *(*uint8)(nil) = 0}// adjust Gobuf as if it executed a call to fn// and then stopped before the first instruction in fn.func gostartcallfn( *gobuf, *funcval) {varunsafe.Pointerif != nil { = unsafe.Pointer(.fn) } else { = unsafe.Pointer(abi.FuncPCABIInternal(nilfunc)) }gostartcall(, , unsafe.Pointer())}// isShrinkStackSafe returns whether it's safe to attempt to shrink// gp's stack. Shrinking the stack is only safe when we have precise// pointer maps for all frames on the stack. The caller must hold the// _Gscan bit for gp or must be running gp itself.func isShrinkStackSafe( *g) bool {// We can't copy the stack if we're in a syscall. // The syscall might have pointers into the stack and // often we don't have precise pointer maps for the innermost // frames.if .syscallsp != 0 {returnfalse }// We also can't copy the stack if we're at an asynchronous // safe-point because we don't have precise pointer maps for // all frames.if .asyncSafePoint {returnfalse }// We also can't *shrink* the stack in the window between the // goroutine calling gopark to park on a channel and // gp.activeStackChans being set.if .parkingOnChan.Load() {returnfalse }// We also can't copy the stack while tracing is enabled, and // gp is in _Gwaiting solely to make itself available to the GC. // In these cases, the G is actually executing on the system // stack, and the execution tracer may want to take a stack trace // of the G's stack. Note: it's safe to access gp.waitreason here. // We're only checking if this is true if we took ownership of the // G with the _Gscan bit. This prevents the goroutine from transitioning, // which prevents gp.waitreason from changing.iftraceEnabled() && readgstatus()&^_Gscan == _Gwaiting && .waitreason.isWaitingForGC() {returnfalse }returntrue}// Maybe shrink the stack being used by gp.//// gp must be stopped and we must own its stack. It may be in// _Grunning, but only if this is our own user G.func shrinkstack( *g) {if .stack.lo == 0 {throw("missing stack in shrinkstack") }if := readgstatus(); &_Gscan == 0 {// We don't own the stack via _Gscan. We could still // own it if this is our own user G and we're on the // system stack.if !( == getg().m.curg && getg() != getg().m.curg && == _Grunning) {// We don't own the stack.throw("bad status in shrinkstack") } }if !isShrinkStackSafe() {throw("shrinkstack at bad time") }// Check for self-shrinks while in a libcall. These may have // pointers into the stack disguised as uintptrs, but these // code paths should all be nosplit.if == getg().m.curg && .m.libcallsp != 0 {throw("shrinking stack in libcall") }ifdebug.gcshrinkstackoff > 0 {return } := findfunc(.startpc)if .valid() && .funcID == abi.FuncID_gcBgMarkWorker {// We're not allowed to shrink the gcBgMarkWorker // stack (see gcBgMarkWorker for explanation).return } := .stack.hi - .stack.lo := / 2// Don't shrink the allocation below the minimum-sized stack // allocation.if < fixedStack {return }// Compute how much of the stack is currently in use and only // shrink the stack if gp is using less than a quarter of its // current stack. The currently used stack includes everything // down to the SP plus the stack guard space that ensures // there's room for nosplit functions. := .stack.hi - .stack.loif := .stack.hi - .sched.sp + stackNosplit; >= /4 {return }ifstackDebug > 0 {print("shrinking stack ", , "->", , "\n") }copystack(, )}// freeStackSpans frees unused stack spans at the end of GC.func freeStackSpans() {// Scan stack pools for empty stack spans.for := rangestackpool {lock(&stackpool[].item.mu) := &stackpool[].item.spanfor := .first; != nil; { := .nextif .allocCount == 0 { .remove() .manualFreeList = 0osStackFree()mheap_.freeManual(, spanAllocStack) } = }unlock(&stackpool[].item.mu) }// Free large stack spans.lock(&stackLarge.lock)for := rangestackLarge.free {for := stackLarge.free[].first; != nil; { := .nextstackLarge.free[].remove()osStackFree()mheap_.freeManual(, spanAllocStack) = } }unlock(&stackLarge.lock)}// A stackObjectRecord is generated by the compiler for each stack object in a stack frame.// This record must match the generator code in cmd/compile/internal/liveness/plive.go:emitStackObjects.type stackObjectRecord struct {// offset in frame // if negative, offset from varp // if non-negative, offset from argp off int32 size int32 _ptrdata int32// ptrdata, or -ptrdata is GC prog is used gcdataoff uint32// offset to gcdata from moduledata.rodata}func ( *stackObjectRecord) () bool {return ._ptrdata < 0}func ( *stackObjectRecord) () uintptr { := ._ptrdataif < 0 {returnuintptr(-) }returnuintptr()}// gcdata returns pointer map or GC prog of the type.func ( *stackObjectRecord) () *byte { := uintptr(unsafe.Pointer())var *moduledatafor := &firstmoduledata; != nil; = .next {if .gofunc <= && < .end { = break } }// If you get a panic here due to a nil mod, // you may have made a copy of a stackObjectRecord. // You must use the original pointer. := .rodata + uintptr(.gcdataoff)return (*byte)(unsafe.Pointer())}// This is exported as ABI0 via linkname so obj can call it.////go:nosplit//go:linkname morestackcfunc morestackc() {throw("attempt to execute system stack code on user stack")}// startingStackSize is the amount of stack that new goroutines start with.// It is a power of 2, and between _FixedStack and maxstacksize, inclusive.// startingStackSize is updated every GC by tracking the average size of// stacks scanned during the GC.var startingStackSize uint32 = fixedStackfunc gcComputeStartingStackSize() {ifdebug.adaptivestackstart == 0 {return }// For details, see the design doc at // https://docs.google.com/document/d/1YDlGIdVTPnmUiTAavlZxBI1d9pwGQgZT7IKFKlIXohQ/edit?usp=sharing // The basic algorithm is to track the average size of stacks // and start goroutines with stack equal to that average size. // Starting at the average size uses at most 2x the space that // an ideal algorithm would have used. // This is just a heuristic to avoid excessive stack growth work // early in a goroutine's lifetime. See issue 18138. Stacks that // are allocated too small can still grow, and stacks allocated // too large can still shrink.varuint64varuint64for , := rangeallp { += .scannedStackSize += .scannedStacks// Reset for next time .scannedStackSize = 0 .scannedStacks = 0 }if == 0 {startingStackSize = fixedStackreturn } := / + stackGuard// Note: we add stackGuard to ensure that a goroutine that // uses the average space will not trigger a growth.if > uint64(maxstacksize) { = uint64(maxstacksize) }if < fixedStack { = fixedStack }// Note: maxstacksize fits in 30 bits, so avg also does.startingStackSize = uint32(round2(int32()))}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.