A Goroutine Starts with Two Kilobytes

Contents
A C program that starts ten thousand threads on Linux reserves 80 gigabytes of address space for their stacks, 8 MB each, before any of them has done anything. A Go program that starts a hundred thousand goroutines spends about 2 KB of stack on each. Yet any one of those goroutines can recurse half a gigabyte deep before Go stops it. Both are true because a goroutine’s stack does not stay where it is: when it fills, the runtime allocates a new one twice the size, copies every frame across, and rewrites every pointer that pointed into the old one.
This post follows that mechanism from the top of a compiled function down to the runtime code that moves a stack. It shows the check the compiler puts at the start of almost every Go function, what happens when that check fails, how the runtime finds every pointer it has to fix, and what all of this costs. It then runs the scheme Go used before, segmented stacks, on an old release to show the problem that made Go give it up. And it sets Go beside C, Rust, Java, Python and Erlang, which answer the same question, “how big should a stack be?”, in five different ways.
This is Part 1 of a series on how Go manages the stack and the heap, how that machinery has changed between releases, and how other languages do the same jobs. It is written for Go programmers who have written a little C. Everything here ran on Go 1.10.2, released on 1 May, on an Ubuntu 18.04 userland. The comparisons use the gcc, OpenJDK, Erlang and Python that 18.04 shipped, and Rust 1.25 from the Rust project. The note at the end says what was measured and how.
What a stack is for
This section is for readers who have not thought about call stacks since a compilers course. If you know what a frame, a stack pointer and a guard page are, skip to the next one.
When a function is called, it needs somewhere to keep its local variables, the arguments it passes
to the functions it calls, and the address to return to when it finishes. These live in a
frame. Frames are created and destroyed in strict last-in, first-out order: a function’s frame
is created when it is called and dies when it returns, and every frame created after it dies first.
That order is what makes a stack the right structure. One machine register, the stack
pointer (SP, or rsp on x86-64), marks the top. Calling a function moves it down by the size
of the frame, and returning moves it back up. Allocating a frame is a subtraction and freeing it is
an addition, which is why memory on the stack is the cheapest memory a program has.
The cost of that cheapness is a question the stack itself cannot answer: how much room to leave. The stack grows down into whatever lies below it. If the memory below belongs to something else, a deep enough recursion overwrites it. So every system that gives a thread a stack has to decide its size up front, and has to decide what happens at the edge.
The usual answer, the one C uses on Linux, is to reserve a large block of address space and put a
guard page below it, a page the program is not allowed to touch. Reserving address space costs
almost nothing: the kernel hands out physical pages only when they are first touched. So a thread’s
stack is 8 MB of addresses but only as many kilobytes of memory as it has actually used. When a
recursion runs off the end, it touches the guard page, the processor faults, and the kernel sends
the process SIGSEGV. The program dies, but it dies instead of corrupting its neighbour.
That works when a program has a handful of threads. Go was designed for programs with a goroutine per connection, per request or per item of work, hundreds of thousands at once. That needs a different answer.
Ten thousand threads, a hundred thousand goroutines
Here is the C side. The program starts ten thousand POSIX threads, each of which immediately waits
on a condition variable, and compares the process’s virtual size (VmSize) and resident memory
(VmRSS) before and after:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
/* Start N threads that each block on one condition variable, then
report how the process's virtual size and resident set changed. */
#define N 10000
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
static int started, go_on;
static void *worker(void *arg) {
(void)arg;
pthread_mutex_lock(&mu);
started++;
while (!go_on) pthread_cond_wait(&cv, &mu);
pthread_mutex_unlock(&mu);
return NULL;
}
static void status(const char *when) {
char line[256];
FILE *f = fopen("/proc/self/status", "r");
while (fgets(line, sizeof line, f))
if (!strncmp(line, "VmSize:", 7) || !strncmp(line, "VmRSS:", 6))
printf("%s %s", when, line);
fclose(f);
}
int main(void) {
static pthread_t t[N];
size_t sz;
pthread_attr_t a;
pthread_getattr_default_np(&a);
pthread_attr_getstacksize(&a, &sz);
printf("default thread stack: %zu bytes\n", sz);
status("before");
for (int i = 0; i < N; i++)
if (pthread_create(&t[i], NULL, worker, NULL)) { printf("failed at %d\n", i); return 1; }
for (;;) { pthread_mutex_lock(&mu); int s = started; pthread_mutex_unlock(&mu); if (s == N) break; }
status("after ");
pthread_mutex_lock(&mu); go_on = 1; pthread_cond_broadcast(&cv); pthread_mutex_unlock(&mu);
for (int i = 0; i < N; i++) pthread_join(t[i], NULL);
return 0;
}
$ gcc -O2 -pthread -o threads threads.c && ./threads
default thread stack: 8388608 bytes
before VmSize: 6784 kB
before VmRSS: 1652 kB
after VmSize: 81969556 kB
after VmRSS: 84540 kB
(gcc 7.3 also warns that pthread_getattr_default_np is not declared without _GNU_SOURCE; the
call links and works.) glibc gives each thread a stack the size of the shell’s stack limit,
ulimit -s, which is 8,192 KB here as on most Linux systems. Ten thousand threads grew the virtual
size by 81,962,772 kB, which is 8,196 kB each: 8 MB of stack and a 4 KB guard page. Resident memory
grew by 82.9 MB, or 8.3 KB per thread. The pages a thread has never touched cost nothing physical,
but every thread holds 8 MB of address space whether it needs it or not, and it can never use more.
Now Go. A hundred thousand goroutines, each blocked on a channel, measured with the runtime’s own counters as well as the kernel’s:
package main
import (
"fmt"
"io/ioutil"
"runtime"
"strings"
)
// rss returns the VmRSS line from /proc/self/status, in kB.
func rss() string {
b, _ := ioutil.ReadFile("/proc/self/status")
for _, l := range strings.Split(string(b), "\n") {
if strings.HasPrefix(l, "VmRSS:") {
return strings.TrimSpace(l[6:])
}
}
return "?"
}
func main() {
const n = 100000
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
fmt.Println("RSS before:", rss())
block := make(chan struct{})
started := make(chan struct{})
for i := 0; i < n; i++ {
go func() {
started <- struct{}{}
<-block
}()
}
for i := 0; i < n; i++ {
<-started
}
runtime.GC()
runtime.ReadMemStats(&after)
fmt.Println("RSS after: ", rss())
fmt.Println("goroutines:", runtime.NumGoroutine())
stk := after.StackInuse - before.StackInuse
sys := after.Sys - before.Sys
fmt.Printf("StackInuse: +%d bytes, %d per goroutine\n", stk, stk/n)
fmt.Printf("Sys: +%d bytes, %d per goroutine\n", sys, sys/n)
close(block)
}
$ go build goroutines.go && ./goroutines
RSS before: 2008 kB
RSS after: 266180 kB
goroutines: 100001
StackInuse: +205651968 bytes, 2056 per goroutine
Sys: +275683576 bytes, 2756 per goroutine
StackInuse is the memory the runtime has handed out as goroutine stacks: 2,056 bytes per
goroutine, of which 2,048 is the stack itself. Sys is everything the runtime got from the
operating system, including the goroutine descriptors, the channel bookkeeping and the free space
the allocator keeps. It comes to 2,756 bytes per goroutine, and resident memory says the same:
264 MB for a hundred thousand goroutines, about 2.6 KB each.
The resident cost per goroutine is a third of a thread’s, which is a real saving but not a dramatic one. The dramatic difference is elsewhere. A thread’s 8 MB is a ceiling fixed when the thread is created. A goroutine’s 2 KB is only a starting point: the same goroutine can later need a megabyte, get it, and give it back. A thread cannot do that, because its stack cannot move. A goroutine’s stack can.
Where a goroutine keeps its stack
Every goroutine is described by a g struct in the runtime. Its first three fields are about the
stack. From src/runtime/runtime2.go in Go 1.10.2:
type stack struct {
lo uintptr
hi uintptr
}
type g struct {
// Stack parameters.
// stack describes the actual stack memory: [stack.lo, stack.hi).
// stackguard0 is the stack pointer compared in the Go stack growth prologue.
// It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
// stackguard1 is the stack pointer compared in the C stack growth prologue.
// It is stack.lo+StackGuard on g0 and gsignal stacks.
// It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
stack stack // offset known to runtime/cgo
stackguard0 uintptr // offset known to liblink
stackguard1 uintptr // offset known to liblink
stack.lo and stack.hi bound the memory. The stack grows down from hi towards lo.
stackguard0 is a line drawn a little above lo: the point past which a function may not start
without asking for more room. The comments say these offsets are “known to liblink”, the linker
library, because compiled code reads them directly. On amd64, stack takes 16 bytes, so
stackguard0 sits at offset 16 (0x10) in every g.
The memory itself comes from the runtime, not from the kernel’s thread machinery. stackalloc in
src/runtime/stack.go hands out small stacks (2, 4, 8 and 16 KB on Linux, _NumStackOrders = 4)
from a per-processor cache of up to 32 KB per size, refilled 16 KB at a time, and larger ones as
whole spans of pages from
the same heap that new and make allocate from. A goroutine stack’s address looks like a heap
address (0xc420… in the runs below) because it is one: the stack lives in memory the garbage
collector’s heap owns. The sizes are set by a few constants at the top of stack.go:
// The minimum size of stack used by Go code
_StackMin = 2048
...
// Functions that need frames bigger than this use an extra
// instruction to do the stack split check, to avoid overflow
// in case SP - framesize wraps below zero.
// This value can be no bigger than the size of the unmapped
// space at zero.
_StackBig = 4096
// The stack guard is a pointer this many bytes above the
// bottom of the stack.
_StackGuard = 880*sys.StackGuardMultiplier + _StackSystem
// After a stack split check the SP is allowed to be this
// many bytes below the stack guard. This saves an instruction
// in the checking sequence for tiny frames.
_StackSmall = 128
// The maximum number of bytes that a chain of NOSPLIT
// functions can use.
_StackLimit = _StackGuard - _StackSystem - _StackSmall
_StackSystem is zero on Linux, and StackGuardMultiplier is 1 in a normal build, so the guard
line is 880 bytes above the bottom of the stack. Those 880 bytes are a reserve. A function with a
small frame may dip up to 128 bytes into it before checking, and the remaining 752, _StackLimit,
are for code that never checks at all: the linker verifies that no chain of such functions can use
more. That includes the code that grows the stack.
Not every piece of Go code runs on a goroutine stack like this. Each operating-system thread the
runtime uses (an m, in the runtime’s vocabulary) has a scheduler goroutine, g0, with an
ordinary fixed stack. On Linux without cgo, allocm in proc.go makes it 8 KB
(malg(8192 * sys.StackGuardMultiplier)). When cgo is in use, pthread_create makes the
thread’s stack and g0 uses that. The runtime switches to g0 to do work that must not itself
trigger stack growth, and growing a stack is one of those jobs.
The question at the top of every function
A thread’s stack is protected by hardware: a guard page and a fault. A goroutine’s stack cannot use that, because the runtime wants to do something gentler than die when it reaches the edge. So the compiler inserts the check in software, at the top of almost every function. Here are four functions with four frame sizes:
package main
// leaf makes no calls and has a tiny frame: the compiler marks it NOSPLIT.
//go:noinline
func leaf(a, b int) int { return a*b + a }
// small has a frame under 128 bytes (StackSmall): one compare.
//go:noinline
func small(n int) int {
if n == 0 {
return 0
}
return small(n-1) + 1
}
// medium has a 512-byte frame: compare SP minus the frame.
//go:noinline
func medium(n int) int {
var buf [64]int
buf[n&63] = n
if n == 0 {
return buf[0]
}
return medium(n-1) + buf[(n+1)&63]
}
// big has an 8 KB frame, bigger than StackBig: a guarded subtraction.
//go:noinline
func big(n int) int {
var buf [1024]int
buf[n&1023] = n
if n == 0 {
return buf[0]
}
return big(n-1) + buf[(n+1)&1023]
}
func main() {
println(leaf(2, 3), small(10), medium(10), big(10))
}
go tool objdump shows what the compiler made of small, the common case, trimmed to the
prologue and the two instructions at the very end of the function:
$ go build prologue.go && go tool objdump -s 'main\.small$' prologue
TEXT main.small(SB) /work/go-p1/prologue.go
prologue.go:9 0x44c170 64488b0c25f8ffffff MOVQ FS:0xfffffff8, CX
prologue.go:9 0x44c179 483b6110 CMPQ 0x10(CX), SP
prologue.go:9 0x44c17d 764e JBE 0x44c1cd
prologue.go:9 0x44c17f 4883ec18 SUBQ $0x18, SP
...
prologue.go:9 0x44c1cd e89e83ffff CALL runtime.morestack_noctxt(SB)
prologue.go:9 0x44c1d2 eb9c JMP main.small(SB)
Read it line by line:
MOVQ FS:0xfffffff8, CXloads the current goroutine’sgpointer. Go keeps it in thread-local storage, at a fixed offset from theFSsegment register, so any function can find its own goroutine in one instruction.CMPQ 0x10(CX), SPcompares the stack pointer withg.stackguard0, at offset 16 as above.JBEjumps ifSPis at or below the guard: there is not enough room to go on.- Otherwise
SUBQ $0x18, SPallocates the 24-byte frame, and the function runs.
The jump target is at the end of the function: a call to runtime.morestack_noctxt, and then a
JMP back to the first instruction of small. If the stack is too small, the function gets a
bigger one and starts again from the beginning, as if it had just been called. Nothing in it has
run yet, so there is nothing to undo. That is three instructions on the fast path: a load, a
compare and a branch that is almost never taken, which the processor predicts correctly almost every
time.
small’s frame is under 128 bytes, _StackSmall, and the guard leaves 880 bytes of slack, so the
function only needs to know that SP is above the guard line. medium needs 536 bytes (0x218: its 512-byte array and 24 more), so
it checks the stack pointer it is about to have:
prologue.go:18 0x44c1e0 64488b0c25f8ffffff MOVQ FS:0xfffffff8, CX
prologue.go:18 0x44c1e9 488d842468feffff LEAQ 0xfffffe68(SP), AX
prologue.go:18 0x44c1f1 483b4110 CMPQ 0x10(CX), AX
prologue.go:18 0x44c1f5 0f86aa000000 JBE 0x44c2a5
prologue.go:18 0x44c1fb 4881ec18020000 SUBQ $0x218, SP
LEAQ 0xfffffe68(SP), AX computes SP − 408: the frame size minus the 128 bytes of _StackSmall
that every function is allowed to dip below the guard. big needs more than _StackBig (4,096
bytes), and the comment above explains why it gets another instruction: subtracting a large frame
from SP could wrap below zero. So it subtracts the other way round:
prologue.go:29 0x44c2b0 64488b0c25f8ffffff MOVQ FS:0xfffffff8, CX
prologue.go:29 0x44c2b9 488b7110 MOVQ 0x10(CX), SI
prologue.go:29 0x44c2bd 4881fedefaffff CMPQ $-0x522, SI
prologue.go:29 0x44c2c4 0f84ba000000 JE 0x44c384
prologue.go:29 0x44c2ca 488d842470030000 LEAQ 0x370(SP), AX
prologue.go:29 0x44c2d2 4829f0 SUBQ SI, AX
prologue.go:29 0x44c2d5 483d08230000 CMPQ $0x2308, AX
prologue.go:29 0x44c2db 0f86a3000000 JBE 0x44c384
The first comparison is against −0x522, which is −1314. That number is stackPreempt, defined in
stack.go:
// Goroutine preemption request.
// Stored into g->stackguard0 to cause split stack check failure.
// Must be greater than any real sp.
// 0xfffffade in hex.
stackPreempt = uintptrMask & -1314
This is the other job the prologue does. When the scheduler wants a goroutine to stop and let
another one run, it cannot interrupt it in the middle of arbitrary code. Instead it sets the
goroutine’s stackguard0 to a value higher than any real stack pointer. The next function call then
“fails” its stack check and ends up in the runtime, which notices that the stack was not the problem
and switches goroutines. Preemption in Go 1.10 rides on the stack check. A goroutine stuck in a loop
that calls no functions never reaches a prologue, so it can never be preempted. big tests for the
preempt value first because its subtraction would otherwise compute nonsense from it.
And leaf has no check at all:
TEXT main.leaf(SB) /work/go-p1/prologue.go
prologue.go:5 0x44c150 488b442408 MOVQ 0x8(SP), AX
prologue.go:5 0x44c155 488b4c2410 MOVQ 0x10(SP), CX
prologue.go:5 0x44c15a 480fafc8 IMULQ AX, CX
prologue.go:5 0x44c15e 4801c8 ADDQ CX, AX
prologue.go:5 0x44c161 4889442418 MOVQ AX, 0x18(SP)
prologue.go:5 0x44c166 c3 RET
The assembler back end in src/cmd/internal/obj/x86/obj6.go marks a function NOSPLIT, meaning
“never check, never grow”, when it calls nothing and its frame is under _StackSmall, 128 bytes.
(The limit is 120 if the function uses one of a few runtime helpers, such as the routines that copy
or zero memory in bulk.) A function like that always fits in the reserve below the guard line, so
checking would be wasted work.
The name is a fossil of the scheme Go used before 1.3, when a stack grew by being split into
linked segments. The runtime still calls stack growth a “split”.
When the check fails: copy everything
morestack, in src/runtime/asm_amd64.s, saves where the function was (its program counter and
stack pointer, into g.sched), switches to the thread’s g0 stack, and calls newstack. After the
preemption checks and some sanity tests, the heart of newstack is this:
// Allocate a bigger segment and move the stack.
oldsize := gp.stack.hi - gp.stack.lo
newsize := oldsize * 2
if newsize > maxstacksize {
print("runtime: goroutine stack exceeds ", maxstacksize, "-byte limit\n")
throw("stack overflow")
}
// The goroutine must be executing in order to call newstack,
// so it must be Grunning (or Gscanrunning).
casgstatus(gp, _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(gp, newsize, true)
(The comment still says “segment”, from the old scheme.) The new stack is always twice the old one.
copystack allocates it, copies the part in use, and swaps it in:
used := old.hi - gp.sched.sp
// allocate new stack
new := stackalloc(uint32(newsize))
...
// Compute adjustment.
var adjinfo adjustinfo
adjinfo.old = old
adjinfo.delta = new.hi - old.hi
...
// Copy the stack (or the rest of it) to the new location
memmove(unsafe.Pointer(new.hi-ncopy), unsafe.Pointer(old.hi-ncopy), ncopy)
...
// Swap out old stack for new one
gp.stack = new
gp.stackguard0 = new.lo + _StackGuard // NOTE: might clobber a preempt request
gp.sched.sp = new.hi - used
gp.stktopsp += adjinfo.delta
// Adjust pointers in the new stack.
gentraceback(^uintptr(0), ^uintptr(0), 0, gp, 0, nil, 0x7fffffff, adjustframe, noescape(unsafe.Pointer(&adjinfo)), 0)
// free old stack
...
stackfree(old)
The stack is copied so that its top lines up with the top of the new block, because stacks grow
down. Every frame therefore moves by the same distance, delta, the difference between the two
hi addresses.
Copying the bytes is the easy half. The frames contain pointers, and some of them point into the
stack itself: a local variable whose address was taken and passed down, a frame pointer, the saved
BP register, a defer record. After the copy those pointers still name addresses in the old stack,
which is about to be freed. Every one of them has to be found and moved by delta. That is the job
of gentraceback, which walks the new stack frame by frame and calls adjustframe on each. The
work ends in adjustpointer:
// 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(adjinfo *adjustinfo, vpp unsafe.Pointer) {
pp := (*uintptr)(vpp)
p := *pp
...
if adjinfo.old.lo <= p && p < adjinfo.old.hi {
*pp = p + adjinfo.delta
...
}
}
The interesting question is how adjustframe knows which words of a frame are pointers. An
integer that happens to hold a value between old.lo and old.hi must not be changed, and a pointer
must not be missed. The answer is a stack map. For every function, the compiler records, at every
point where the function can call out, a bitmap with one bit per word of the frame: 1 for a pointer,
0 for anything else. adjustframe looks up the program counter at which the frame is paused, finds
the map that applies there (pcdatavalue(f, _PCDATA_StackMapIndex, targetpc, ...) and
funcdata(f, _FUNCDATA_LocalsPointerMaps)), and adjustpointers visits only the words whose bit is
set. The same maps tell the garbage collector which stack words to follow. Go 1.3’s release notes
announced them in one sentence: the collector had long been precise about the heap, and “the Go 1.3
release adds equivalent precision to values on the stack.”
Watching a stack move
This can be seen from ordinary Go. The program below takes the address of a local variable x
twice: once as a real pointer, p, and once as a plain integer, u, which holds the same number.
It then recurses 20,000 levels deep, passing p down. At every level it checks whether p still
holds the address it held one level up. Each time it changes, the stack has just been copied, and
the runtime has rewritten p.
package main
import (
"fmt"
"unsafe"
)
type move struct {
depth int
from, to uintptr
}
var moves []move
// deep recurses n levels. At every level it looks at where p points:
// p is main's &x, and when the stack is copied, the runtime rewrites it.
//go:noinline
func deep(n int, p *int, last *uintptr) int {
var pad [8]int
pad[n&7] = n
if a := uintptr(unsafe.Pointer(p)); a != *last {
moves = append(moves, move{n, *last, a})
*last = a
}
if n == 0 {
return pad[0]
}
return deep(n-1, p, last) + pad[(n+1)&7]
}
func run() {
x := 42
p := &x
u := uintptr(unsafe.Pointer(&x)) // the same address, as a plain integer
last := u
// println is a builtin: unlike fmt, it does not make x escape to the heap.
println("before: p =", p, " u =", unsafe.Pointer(u))
deep(20000, p, &last)
println("after: p =", p, " u =", unsafe.Pointer(u))
for _, m := range moves {
fmt.Printf("depth %5d: %#x -> %#x\n", 20000-m.depth, m.from, m.to)
}
x = 7
println("*p =", *p, " *u =", *(*int)(unsafe.Pointer(u)))
}
// main runs the same experiment on a brand-new goroutine, whose stack
// starts at 2 KB; main's own goroutine has already grown during init.
func main() {
done := make(chan bool)
go func() {
run()
done <- true
}()
<-done
}
The comment on println is there because the first version of this program printed the addresses
with fmt.Printf, and the experiment quietly stopped working. Passing a value derived from &x to
fmt made the compiler decide that x might outlive run, so it put x on the heap, where nothing
ever moves. The printed addresses never changed. Whether a variable lives on the stack or on the heap
is a decision the compiler makes, invisibly, and it is the subject the next part of this series
takes up. For now, the compiler’s own report confirms that this version keeps x on the stack:
$ go build -gcflags=-m movesg.go 2>&1 | grep -E 'moved to heap|&x'
./movesg.go:33:7: run &x does not escape
./movesg.go:34:30: run &x does not escape
$ ./movesg
before: p = 0xc420057f20 u = 0xc420057f20
after: p = 0xc4208b1f20 u = 0xc420057f20
depth 6: 0xc420057f20 -> 0xc420070f20
depth 19: 0xc420070f20 -> 0xc420097f20
depth 44: 0xc420097f20 -> 0xc4200b7f20
depth 95: 0xc4200b7f20 -> 0xc4200bff20
depth 198: 0xc4200bff20 -> 0xc4200cff20
depth 403: 0xc4200cff20 -> 0xc4200eff20
depth 812: 0xc4200eff20 -> 0xc42012ff20
depth 1631: 0xc42012ff20 -> 0xc4201aff20
depth 3270: 0xc4201aff20 -> 0xc4202aff20
depth 6547: 0xc4202aff20 -> 0xc4204b1f20
depth 13100: 0xc4204b1f20 -> 0xc4208b1f20
*p = 7 *u = 42
The variable x lived at twelve different addresses during one call. Each line is one copy. The
depths at which they happen roughly double, because each new stack is twice the last. deep’s
frame is 160 bytes (its prologue subtracts 0x98, plus 8 for the return address), so the last copy,
at depth 13,100, is the move from a 2 MB stack to a 4 MB one. Counting back eleven doublings from
4 MB lands on 2 KB, the size a new goroutine starts with.
The first copy comes at depth 6, not at depth 12 as 2,048 ÷ 160 would suggest. The goroutine’s
first frames (run, the closure that calls it, and the guard reserve) use part of the 2 KB before
deep is ever called. Running the same code on the program’s main goroutine instead (movesg.go
moves it into a fresh goroutine on purpose) gives a first copy only at depth 44, because the main
goroutine’s stack has already grown to 8 KB while the packages were being initialised, before
main.main began.
One goroutine, twelve stacks
Stack size against call depth for one recursion to depth 20,000 on a fresh goroutine. Each dot is a copy.
The eleven copies as a table
| depth | stack | p before | p after |
|---|---|---|---|
| 6 | 2 → 4 KB | 0xc420057f20 | 0xc420070f20 |
| 19 | 4 → 8 KB | 0xc420070f20 | 0xc420097f20 |
| 44 | 8 → 16 KB | 0xc420097f20 | 0xc4200b7f20 |
| 95 | 16 → 32 KB | 0xc4200b7f20 | 0xc4200bff20 |
| 198 | 32 → 64 KB | 0xc4200bff20 | 0xc4200cff20 |
| 403 | 64 → 128 KB | 0xc4200cff20 | 0xc4200eff20 |
| 812 | 128 → 256 KB | 0xc4200eff20 | 0xc42012ff20 |
| 1631 | 256 → 512 KB | 0xc42012ff20 | 0xc4201aff20 |
| 3270 | 512 → 1024 KB | 0xc4201aff20 | 0xc4202aff20 |
| 6547 | 1024 → 2048 KB | 0xc4202aff20 | 0xc4204b1f20 |
| 13100 | 2048 → 4096 KB | 0xc4204b1f20 | 0xc4208b1f20 |
Measured with Go 1.10.2. The integer copy u of the same address stayed at 0xc420057f20 throughout, and after x = 7 it still read 42.
The last line of the output is the leak. After x = 7, the pointer p reads 7, because the runtime
rewrote it at each of the eleven moves. The integer u reads 42. It still holds x’s first
address, in the stack that was freed at the first of the eleven copies. The memory is still mapped, because the runtime
keeps freed stacks for reuse, so reading it did not crash. It returned a value that has not been
true since the first copy. The stack map knew p was a pointer. To the runtime, u was a number
like any other.
Go 1.3’s release notes warned about exactly this when stacks started to move: “Programs that use package unsafe to store pointers in integer-typed values are also illegal but more difficult to diagnose during execution. Because the pointers are hidden from the runtime, a stack expansion or garbage collection may reclaim the memory they point at, creating dangling pointers.” It is also why cgo has rules about passing Go pointers to C. C code is not covered by stack maps. If it kept a pointer into a goroutine’s stack, the next move would leave it dangling, and no Go code would notice.
What growing costs
Doubling keeps the total amount of copying in proportion to the stack’s final size. A stack that
ends at 4 MB has been copied at 2 MB, 1 MB, 512 KB and so on: at most 4 MB of copying in all, spread
over every call that got it there. That is the same argument as for append on a slice. But the
cost is real, and it falls on the first deep call. This program times a recursion to depths from
100 to a million in a fresh goroutine, three times: once on a new stack, once more on the same
goroutine (whose stack is now big enough), and once after two garbage collections:
package main
import (
"fmt"
"runtime"
"sort"
"time"
)
//go:noinline
func rec(n int) int {
var pad [8]int
pad[n&7] = n
if n == 0 {
return pad[0]
}
return rec(n-1) + pad[(n+1)&7]
}
func timeit(n int) float64 {
t := time.Now()
rec(n)
return float64(time.Since(t).Nanoseconds()) / float64(n)
}
func median(v []float64) float64 {
sort.Float64s(v)
return v[len(v)/2]
}
func main() {
const runs = 21
fmt.Println("depth first second afterGC (ns per call, median of", runs, "fresh goroutines)")
for _, n := range []int{100, 1000, 10000, 100000, 1000000} {
var a, b, c []float64
for r := 0; r < runs; r++ {
done := make(chan [3]float64)
go func() {
var res [3]float64
res[0] = timeit(n) // pays for growing the stack
res[1] = timeit(n) // the stack is already big
runtime.GC() // GC halves a stack that uses under a quarter
runtime.GC()
res[2] = timeit(n)
done <- res
}()
res := <-done
a, b, c = append(a, res[0]), append(b, res[1]), append(c, res[2])
}
fmt.Printf("%7d %7.2f %7.2f %7.2f\n", n, median(a), median(b), median(c))
}
}
$ go build depthcost.go && ./depthcost
depth first second afterGC (ns per call, median of 21 fresh goroutines)
100 46.93 2.51 56.43
1000 38.74 2.56 33.03
10000 30.33 3.46 26.49
100000 54.77 6.36 44.69
1000000 51.00 12.00 41.79
A call costs about 2.5 nanoseconds on a stack that is already big enough. On a fresh goroutine it costs 30 to 55 nanoseconds once the growing is spread over every call. The first deep call pays for allocating each new stack, copying into it, walking every frame to adjust its pointers, and touching memory that has never been touched before. The second call, made on a stack that is now big enough, pays none of that. (The second column rises at the largest depths because a 100 MB stack no longer fits in any cache.)
The third column shows that growth is not paid only once. Stacks shrink too. When the garbage
collector scans a goroutine’s stack, it calls shrinkstack, which halves the stack if the goroutine
is using less than a quarter of it:
oldsize := gp.stack.hi - gp.stack.lo
newsize := oldsize / 2
// Don't shrink the allocation below the minimum-sized stack
// allocation.
if newsize < _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.
avail := gp.stack.hi - gp.stack.lo
if used := gp.stack.hi - gp.sched.sp + _StackLimit; used >= avail/4 {
return
}
After two collections the goroutine’s stack is a quarter of its peak, and the next deep call has to grow it again. Most of the copying is in the last, largest doublings, which is probably why the third column is close to the first. The same function, with the same arguments, costs 2.5 ns or 50 ns per call depending on what the goroutine did before and on whether a collection ran in between. That is the price of not having to choose a stack size.
Nanoseconds per call, by depth of recursion
Median of 21 fresh goroutines per depth, Go 1.10.2.
Hover or focus a bar for details.
The same function costs about 2.5 ns a call on a stack that fits, and 30–55 ns while the stack is being grown under it.
Before Go 1.3: segmented stacks and the hot split
Go did not always move stacks. Up to Go 1.2 it split them. When a function’s check failed, the
runtime allocated a new, separate block (a segment), linked it to the old one, and ran the function
there. When the function returned, it fell off the end of the segment back into the old one, and the
new segment was released. No frame ever moved, so no pointer ever needed fixing. gcc offers the same
scheme for C as -fsplit-stack.
Segmented stacks have one pathological case. Suppose a loop runs right at the end of a segment and calls a function whose frame does not fit. Every call allocates a segment, and every return frees it. One unlucky stack depth turns an ordinary call into a trip through the allocator. This was called the hot split. Go 1.2’s release notes describe the first attempt at managing it: “In Go 1.2, the minimum size of the stack when a goroutine is created has been lifted from 4KB to 8KB. Many programs were suffering performance problems with the old size, which had a tendency to introduce expensive stack-segment switching in performance-critical sections.” Bigger segments made the hot split rarer. They could not make it impossible.
Go 1.2.2 still downloads and runs. This program descends d frames and then calls a small function
200,000 times from the bottom. It times every depth from 0 to 120, taking the best of five runs, each
in a fresh goroutine:
package main
import (
"fmt"
"os"
"strconv"
"time"
)
var sink int
// leaf needs a 256-byte frame. Loops keep both functions from being inlined
// on every Go version tried here.
func leaf(i int) int {
var buf [32]int
for j := range buf {
buf[j] = i + j
}
return buf[i&31]
}
// pad descends d frames and then calls leaf iters times from the bottom.
func pad(d, iters int) time.Duration {
var buf [8]int
for j := range buf {
buf[j] = d
}
if d > 0 {
return pad(d-1, iters) + time.Duration(buf[d&7]&0)
}
start := time.Now()
s := 0
for i := 0; i < iters; i++ {
s += leaf(i)
}
sink += s
return time.Since(start)
}
// grow recurses n frames and returns, leaving a copying stack grown.
func grow(n int) int {
var buf [8]int
for j := range buf {
buf[j] = n
}
if n == 0 {
return 0
}
return grow(n-1) + buf[n&7]
}
func main() {
maxd, _ := strconv.Atoi(os.Args[1])
pregrow := len(os.Args) > 2
const iters = 200000
for d := 0; d <= maxd; d++ {
best := time.Duration(1 << 62)
for r := 0; r < 5; r++ {
ch := make(chan time.Duration)
go func() {
if pregrow {
grow(2000)
}
ch <- pad(d, iters)
}()
if el := <-ch; el < best {
best = el
}
}
fmt.Printf("%d %.1f\n", d, float64(best.Nanoseconds())/iters)
}
}
On Go 1.2.2 a call to leaf costs about 13.5 nanoseconds at almost every depth. At depth 53 it
costs 63, and again at 107 and 108:
$ GOROOT=/opt/go/1.2.2 /opt/go/1.2.2/bin/go build -o hot122 hotsplit.go && ./hot122 120
...
51 13.7
52 13.5
53 63.5
54 13.5
55 13.4
...
105 13.4
106 13.5
107 63.7
108 64.4
109 13.5
110 13.6
...
That is the hot split, measured: about 50 nanoseconds per call spent creating and freeing a segment.
The slow depths come back every 54 frames. pad’s frame on 1.2.2 is 144 bytes (sub $0x88,%rsp
plus the return address), and 54 frames of 144 bytes is 7,776 bytes: one 8 KB segment, less its own
bookkeeping. Running the program with the extra argument, which first recurses 2,000 frames deep and
returns before descending, changes nothing: 63.4 nanoseconds at depth 53, and 65.2 and 65.1 at 107 and
108. A segmented stack gives its segments back as soon as the calls return, so there is no such thing
as a pre-grown stack.
The same source on Go 1.10.2 costs 7.5 nanoseconds per call at almost every depth. (The lower baseline is the newer compiler, not the stack.) At depths 43 and 89 it costs 11.9 and 11.7. That is once every 46 frames of 88 bytes, so once every 4 KB of stack. On a goroutine whose stack was grown in advance the bumps are in the same places (12.1 and 11.6), which shows they are not stack growth: in this program the stack grows once, during the first descent, and never during the 200,000 calls being timed. Something else about those addresses is slower, and I did not find what. The bumps are a twelfth the size of the hot split, and they do not depend on the stack’s history. (One fresh run was also slow at depth 29, 9.5 nanoseconds, and that did not repeat on the pre-grown stack.)
A call to leaf at each stack depth
Nanoseconds per call, best of 5 goroutines × 200,000 calls.
Hover or focus the chart, then use the arrow keys.
The copper spikes are the hot split: the depths that recur every 54 frames (one 8 KB segment of 144-byte frames), where each call allocates and frees a segment. Pre-growing does not help, because a segment is released when its call returns. The small teal bumps are there on a pre-grown stack too, so they are not stack growth.
Keith Randall proposed replacing segments with copying in a design document sent to the golang-dev
list in May 2013, with benchmarks against segmented stacks. Go 1.3, released in June 2014, made the
switch: “When a goroutine needs more stack than is available, its stack is transferred to a larger
single block of memory. The overhead of this transfer operation amortizes well and eliminates the
old ‘hot spot’ problem when a calculation repeatedly steps across a segment boundary.” Six months
later Go 1.4 used the freedom this gave: “The use of contiguous stacks means that stacks can start
smaller without triggering performance issues, so the default starting size for a goroutine’s stack
in 1.4 has been reduced from 8192 bytes to 2048 bytes.” That 2,048 is the _StackMin in today’s
stack.go.
Go was not the only language to try segments and give them up. Rust used segmented stacks in its early runtime. In November 2013 the announcement that removed them from the rust-dev list said the experience had convinced the team “that the performance tradeoffs required are not compatible with Rust’s goals as a high performance systems language.” Rust went back to C’s answer: fixed stacks, guard pages. It could not take Go’s way out, and the reason is the subject of the next section.
Why Go can move a stack and C cannot
Moving a stack requires knowing every pointer into it. Go knows because its compiler records a stack
map for every function, the language forbids pointer arithmetic outside unsafe, and the runtime can
find every goroutine’s frames. The u in the experiment above is the one gap, and it is an illegal
use of unsafe.
C knows none of this. A pointer into the stack can be stored anywhere: in a global, in a heap
object, in a long, in a register of another thread, in a buffer handed to the kernel for a read
that has not finished. No compiler records which words are pointers, so nothing could find them all,
and a C stack must never move. Hence the big up-front reservation: once a thread’s stack is placed,
it stays there until the thread exits, and it must be big enough for the deepest call the thread
will ever make. Rust has the same constraint for the same reason: raw pointers, foreign calls into C,
and no runtime that could walk the stack. That is why its segmented-stack experiment ended in fixed
stacks rather than copying ones.
Java is in between. The JVM knows exactly where every reference is, for its garbage collector, so in
principle it could move stacks. But a Java thread runs on an operating-system thread, and its stack
is that thread’s stack, with native frames from JNI and from the JVM’s own C++ interleaved with
Java ones. It is fixed at thread creation with -Xss.
The closest relative to Go’s design is Erlang, which also runs hundreds of thousands of lightweight processes. Each Erlang process gets one block of memory holding both its heap and its stack, growing towards each other. When they meet, the process’s garbage collector allocates a bigger block and copies everything into it, stack included. Like Go, it can do that because it knows where every pointer is. Erlang’s stack is not a separate thing that can overflow at all: it is part of the process’s heap.
CPython, the last of the six, does something else again. Its Python frames are heap objects linked into a list, so a deep Python recursion costs heap rather than stack. But every Python call also nests a call of the C interpreter loop on the thread’s real C stack, so CPython guards that stack the only way it can, by counting.
Running out
Every one of these designs has to do something when a recursion never ends. Here is the same function, recursing forever with 64 bytes of locals per level, in each language, run on the same machine.
Go. throw is not a panic: the program cannot recover from it.
package main
var depth int
//go:noinline
func f(n int) int {
var pad [8]int // the same 64 bytes of locals as the C, Rust and Java versions
pad[n&7] = n
depth = n
return f(n+1) + pad[(n+1)&7]
}
func main() {
f(0)
}
$ go build overflow.go && /usr/bin/time -f 'elapsed %e s, max RSS %M kB, exit %x' ./overflow
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
runtime stack:
runtime.throw(0x46a994, 0xe)
/opt/go/1.10.2/src/runtime/panic.go:616 +0x81
runtime.newstack()
/opt/go/1.10.2/src/runtime/stack.go:1054 +0x71f
runtime.morestack()
/opt/go/1.10.2/src/runtime/asm_amd64.s:480 +0x89
goroutine 1 [running]:
main.f(0x4ec4e3, 0x0)
/work/go-p1/overflow.go:6 +0x89 fp=0xc4400a0330 sp=0xc4400a0328 pc=0x44c1d9
main.f(0x4ec4e2, 0x0)
/work/go-p1/overflow.go:10 +0x62 fp=0xc4400a0398 sp=0xc4400a0330 pc=0x44c1b2
...
...additional frames elided...
elapsed 0.65 s, max RSS 1050696 kB, exit 2
The limit is maxstacksize, set in runtime.main: “Max stack size is 1 GB on 64-bit, 250 MB on
32-bit. Using decimal instead of binary GB and MB because they look nicer in the stack overflow
failure message.” It can be changed with runtime/debug.SetMaxStack, added in Go 1.2 because
“before Go 1.2, it was too easy for a runaway recursion to consume all the memory on a machine.”
The traceback prints each frame’s arguments, so it gives the depth: main.f(0x4ec4e3) is level
5,162,211. The frames are 104 bytes apart (0x398 − 0x330), and 5,162,211 × 104 is 536,869,944 bytes:
512 MiB, less the 880-byte guard and a few frames. The goroutine did not die at a gigabyte. It died
at 512 MiB, because the next stack would have been 1 GiB, 1,073,741,824 bytes, which is over the
1,000,000,000 limit. With doubling, a “1 GB” limit means a 512 MiB stack.
The process’s peak resident memory was 1.0 GB: the 512 MiB stack plus every stack before it. Each copy needs the old and the new stack at once, and freed stacks go back to the runtime’s heap rather than to the operating system. In 0.65 seconds a single runaway goroutine took a gigabyte of real memory before Go noticed, which is the price of a limit that high.
C. The C version installs a SIGSEGV handler so it can report the depth. The handler has to
run on a separate, small stack (sigaltstack), because the thread’s own stack is the thing that has
just run out. Go and Rust both install handlers the same way:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static volatile long depth;
/* Runs on its own small stack: the thread's stack is the thing that overflowed. */
static void on_segv(int sig) {
char msg[96];
int n = snprintf(msg, sizeof msg, "SIGSEGV at depth %ld\n", depth);
write(2, msg, n);
_exit(128 + sig);
}
__attribute__((noinline)) long f(long n) {
volatile long pad[8];
pad[n & 7] = n;
depth = n;
return f(n + 1) + pad[(n + 1) & 7];
}
int main(void) {
static char alt[64 * 1024];
stack_t ss = { .ss_sp = alt, .ss_size = sizeof alt };
sigaltstack(&ss, NULL);
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = on_segv;
sa.sa_flags = SA_ONSTACK;
sigaction(SIGSEGV, &sa, NULL);
return (int)f(0);
}
$ gcc -O1 -o ovc overflow.c && /usr/bin/time -f 'elapsed %e s, max RSS %M kB, exit %x' ./ovc
SIGSEGV at depth 87340
Command exited with non-zero status 139
elapsed 0.00 s, max RSS 9508 kB, exit 139
87,340 frames of 96 bytes fill 8 MiB: ulimit -s again, now as a hard wall. (gcc also warns that
the handler ignores write’s return value.) The process used 9.5 MB and died at once.
Rust 1.25. The first version of the Rust program, compiled with -O, exited at once with status
0: the optimiser had removed the endless recursion. This one reads each frame’s array back through a
volatile read after the recursive call, which forces every level to keep its frame:
use std::ptr::read_volatile;
// pad is read back after the recursive call, through a volatile read, so
// every level keeps its 64 bytes on the stack and the optimiser cannot
// turn the recursion into a loop.
#[inline(never)]
fn f(n: usize) -> usize {
let mut pad = [0usize; 8];
pad[n & 7] = n;
let r = f(n + 1);
r + unsafe { read_volatile(&pad[(n + 1) & 7]) }
}
fn main() {
if std::env::args().nth(1).as_ref().map(|s| s.as_str()) == Some("thread") {
let _ = std::thread::spawn(|| f(0)).join();
} else {
f(0);
}
}
$ rustc -O -o ovrs overflow.rs && /usr/bin/time -f 'elapsed %e s, max RSS %M kB, exit %x' ./ovrs
thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Command terminated by signal 6
elapsed 0.00 s, max RSS 10416 kB, exit 0
$ /usr/bin/time -f 'elapsed %e s, max RSS %M kB, exit %x' ./ovrs thread
thread '<unknown>' has overflowed its stack
fatal runtime error: stack overflow
Command terminated by signal 6
elapsed 0.00 s, max RSS 4272 kB, exit 0
(rustc also warns, correctly, that f cannot return without recursing.) Rust’s runtime catches the
fault on the guard page, prints a message instead of a bare segfault, and aborts. The main thread has
the process’s 8 MB stack. A spawned thread gets Rust’s default of 2 MiB, which is why that process
peaked at 4.3 MB rather than 10.4.
Java 8. The overflow is an exception, StackOverflowError, and it can be caught:
public class Overflow {
static long depth;
static long f(long n) {
long a = n, b = n + 1, c = n + 2, d = n + 3;
depth = n;
return f(n + 1) + a + b + c + d;
}
public static void main(String[] args) {
for (int run = 0; run < 3; run++) {
try {
f(0);
} catch (StackOverflowError e) {
System.out.println("StackOverflowError at depth " + depth + ", caught; still running");
}
}
}
}
$ javac Overflow.java && java Overflow && java -Xss8m Overflow
StackOverflowError at depth 9119, caught; still running
StackOverflowError at depth 19761, caught; still running
StackOverflowError at depth 19761, caught; still running
StackOverflowError at depth 153958, caught; still running
StackOverflowError at depth 172679, caught; still running
StackOverflowError at depth 172679, caught; still running
(Java has no arrays on the stack, so this version keeps four longs in locals instead.) The
default thread stack in OpenJDK 8 on 64-bit Linux is 1,024 KB (-XX:ThreadStackSize). The depth it
allows is not even a fixed number. The first attempt ran out at 9,119 frames. It started in the
interpreter, and the JIT compiler compiled f partway down: run with -XX:+PrintCompilation, the
JVM reports Overflow::f compiled twice, at tier 3 and then tier 4, before the first error. But the
frames already on the stack kept the interpreter’s larger layout. By the second attempt every frame
was compiled machine code with a much smaller frame, and the same stack held 19,761. With -Xss8m the same thing happened, at 153,958
and then 172,679. In Java, how deep you can recurse depends on how warm the JIT is.
Python 3.6. CPython does not wait for the C stack to run out. It counts:
import sys
depth = 0
def f(n):
global depth
depth = n
return f(n + 1) + 1
print("recursion limit:", sys.getrecursionlimit())
try:
f(0)
except RecursionError as e:
print("RecursionError at depth", depth, "-", e)
$ python3 overflow.py
recursion limit: 1000
RecursionError at depth 998 - maximum recursion depth exceeded
A thousand Python frames is a limit on nesting, not on bytes. It is set far below what the 8 MB C stack could hold, because the interpreter cannot tell how much C stack each Python call will take.
Erlang/OTP 20. This version asks each process to report on itself at the bottom of a recursion of a given depth:
-module(overflow).
-export([main/0]).
%% Not tail recursive: every level leaves a frame on the process's stack.
%% At the bottom, the process reports its own stack and heap.
f(0) -> {process_info(self(), [stack_size, heap_size, total_heap_size]), 0};
f(N) -> {Info, C} = f(N - 1), {Info, C + 1}.
main() ->
{_, Min} = erlang:system_info(min_heap_size),
io:format("min_heap_size: ~p words~n", [Min]),
Self = self(),
[begin
spawn(fun() -> {Info, _} = f(N), Self ! {N, Info} end),
receive {N, Info} -> io:format("depth ~8w: ~p~n", [N, Info]) end
end || N <- [0, 100, 1000, 10000, 100000, 1000000]],
%% A process with a 10 M-word ceiling on heap + stack: the VM kills it.
{Pid, Ref} = spawn_opt(fun() -> f(100000000) end,
[monitor, {max_heap_size, #{size => 10000000, kill => true, error_logger => true}}]),
receive {'DOWN', Ref, process, Pid, Why} -> io:format("process ended: ~p~n", [Why]) end,
init:stop().
$ erlc overflow.erl && erl -noshell -s overflow main
min_heap_size: 233 words
depth 0: [{stack_size,4},{heap_size,233},{total_heap_size,233}]
depth 100: [{stack_size,104},{heap_size,233},{total_heap_size,233}]
depth 1000: [{stack_size,1004},{heap_size,1598},{total_heap_size,1598}]
depth 10000: [{stack_size,10004},{heap_size,10958},{total_heap_size,10958}]
depth 100000: [{stack_size,100004},
{heap_size,121536},
{total_heap_size,121536}]
depth 1000000: [{stack_size,1000004},
{heap_size,1199557},
{total_heap_size,1199557}]
process ended: killed
An Erlang process starts with 233 words, about 1.8 KB, for its heap and stack together: almost
exactly a goroutine’s starting size. Each level of this recursion leaves one
word on the stack, and as the stack grows the reported heap grows with it. They are one block, and
the process’s garbage collector enlarges it by copying, as Go’s runtime does. There is no stack limit
at all. A runaway recursion keeps growing until the whole node runs out of memory, unless the process
was given a max_heap_size, a limit added to Erlang in 2016. The last process here had one, of ten million
words, and the VM’s report of its death shows where the memory had gone: {stack_size,5157868} in a
block of 11,347,307 words. Over five million words of the “heap” were stack.
The six answers, side by side:
| Runtime | Stack | At the edge | Depth here |
|---|---|---|---|
| Go 1.10.2 | starts at 2 KB, doubles by copying | fatal error: stack overflow, not recoverable | 5,162,211 (512 MiB) |
| C, gcc 7.3 | 8 MB fixed, guard page | SIGSEGV | 87,340 |
| Rust 1.25 | 8 MB main, 2 MiB threads, guard page | message, then abort | (not counted) |
| Java 8u162 | 1 MB fixed (-Xss) | StackOverflowError, catchable | 9,119, then 19,761 once compiled |
| CPython 3.6.5 | frames on the heap; the C stack guarded by a count | RecursionError | 998 |
| Erlang/OTP 20.2 | shares one growing block with the process heap | no limit unless max_heap_size | killed at 5,157,868 words of stack |
What this means for Go code
Three practical things follow.
Goroutines are cheap to create but not free to deepen. A goroutine costs a couple of kilobytes until it calls deeply. The first deep call on a fresh goroutine pays for every doubling, at 30 to 55 ns a call here instead of 2.5. A long-lived goroutine that does deep work repeatedly keeps its big stack between calls, unless a garbage collection finds it idle and halves it. Goroutines that are started per item of work start at 2 KB each time.
Addresses on the stack are not stable. A pointer to a local variable is rewritten when the stack
moves, so ordinary Go code never notices. An address converted to uintptr and kept, or handed to C
and kept there, silently goes stale at the next growth. This is the stack half of the rule that
unsafe code must not hide pointers in integers.
The overflow limit is far away, and that cuts both ways. A goroutine can recurse five million frames deep before Go stops it, which is why Go programmers rarely see a stack overflow. When one does happen, the program has already used a gigabyte of memory, and it cannot be caught.
A note on the evidence
What ran. Go 1.10.2 (go1.10.2.linux-amd64.tar.gz from dl.google.com, checked against its
published SHA-256), released on 1 May 2018, on an Ubuntu 18.04 userland as released (glibc 2.27,
gcc 7.3.0, OpenJDK 8u162, Erlang/OTP 20.2.2, Python 3.6.5). Rust 1.25.0 is the release tarball from
static.rust-lang.org (checksum verified). Go 1.2.2, used only for the hot-split section, came from
the same Go archive over HTTPS; its listing in Go’s release index carries no SHA-256, so it is
identified by its SHA-1, 6bd151ca49c435462c8bf019477a6244b958ebb5. The programs ran in a chroot on
a 24-thread x86-64 machine, under the host’s Linux kernel; nothing here depends on the kernel version
beyond ulimit -s being 8,192 KB and the kernel’s lazy allocation of stack pages.
What was measured. Every console block is the program’s output as it ran, apart from cuts marked
... and the hot-split listing, which shows the rows around the slow depths from a 121-row run. The
timings come from a single sitting with nothing else running, and the statistic is stated with each:
the median of 21 fresh goroutines for the depth costs, the best of five for the hot split. Frame
sizes were read from the disassembly (go tool objdump, objdump -d), not assumed. The goroutine’s
depth at overflow was read from the traceback’s argument. The pre-grown hot-split runs, mentioned in
the text but not listed, are in the data behind the figure. Every program was then extracted from
this page and compared byte for byte with the code that ran; the hot-split numbers come from the
extracted copy itself. The programs whose output is not a timing were run again from the extracted
copies. Apart from addresses, the results repeated with small drift: 2,759 instead of 2,756 bytes of
Sys per goroutine, a few kilobytes of resident memory either way, C’s overflow depth moved by a
few frames (87,355 instead of 87,340) because the environment and arguments at the top of the main
stack were a different size, and Java’s partly interpreted depths moved too (9,085 instead of
9,119, and 151,899 instead of 153,958). The fully compiled depths, 19,761 and 172,679, were exactly
the same.
What is quoted. All runtime source is from the go1.10.2 tag of the Go repository
(src/runtime/stack.go, runtime2.go, proc.go, asm_amd64.s, malloc.go,
src/cmd/internal/obj/x86/obj6.go). The history is quoted from the release notes for Go 1.2, 1.3 and
1.4 at their tags. Keith Randall’s design document and the Rust announcement are cited from the
golang-dev and rust-dev lists.
What is not explained. The 4-nanosecond bumps at one depth per 4 KB on Go 1.10.2 are reported
as observed. They are not stack growth, because they appear on a pre-grown stack, but I have not
identified their cause. The resident-memory comparison between threads and goroutines counts only
user-space memory. A thread also costs the kernel a task structure and a kernel stack, which VmRSS
does not show, so the real gap is somewhat larger than measured here.
What changed in the writing. The first version of the moving-stack experiment printed with
fmt and moved its variable to the heap, so it showed nothing. The first Rust version was optimised
into an immediate exit. Both are described above because both are part of the subject. And the first
“pre-grown” hot-split runs were not pre-grown: the edit that added the grow call never reached the
file that was compiled, so they repeated the fresh runs. Extracting the program from this page and
comparing it with what had run caught the difference. Every hot-split number here comes from a
rerun of the program exactly as printed, all four series in one sitting.
A Goroutine Starts with Two Kilobytes