← Writing

Go on Windows: Where the Stacks Come From

37 min readSystemsGORuntimeWindowsMemoryStack
Contents

Run the same Go program on Linux and on Windows and its goroutines are not the same size. On Windows every goroutine starts with an 8 KB stack, four times what it gets on Linux, because Windows writes the record of a processor exception onto whatever stack the fault happened on. A gigabyte that a Go program allocates and never touches costs a full gigabyte of Windows’ commit charge, and on a machine with 4 GB of memory the ninth such gigabyte stops the program, where Linux let the same program reach 64 GB on a 31 GB machine. And a C function, called from Go, that runs out of stack leaves, nine times in ten, a process that prints its crash report and then never exits.

This post is about the Go runtime on Windows: where its memory and its stacks come from, and what that costs. It starts with the way Windows hands out memory, in two steps where Linux uses one, and what the runtime does with them. Then come the stacks: a goroutine’s, which the runtime allocates itself, and a thread’s, which on Windows it does not. The same thousand threads are measured in C, Rust, .NET and Java, and each runtime is made to run out of stack, which on Windows is a matter for the exception dispatcher. The post ends with the exception handler that turns a Windows access violation into a Go panic, the one case where it hangs instead, and the few things Go 1.15 changed.

This is Part 7 of a series on how Go manages the stack and the heap. Part 1 took the goroutine stack apart, Part 3 the heap arenas, and Part 5 the memory the runtime hands back, all on Linux. Everything here ran on Go 1.15.1, released on 1 September, under Windows Server 2019, with C, Rust 1.46, .NET Core 3.1 and Java 11 for the comparisons. The note at the end says what was measured and how.

The test bed

The machine is a Hyper-V virtual machine with four virtual processors and 4 GB of memory, running Windows Server 2019 Standard, version 1809, build 17763.737. Windows Server 2019 is the server release of Windows 10 1809, the same kernel and the same memory manager, and nothing here depends on the parts of Windows that differ between the two. The page file is the one Windows manages itself, 1,408 MB when the machine starts. The VM has no network.

The Go programs are cross-compiled on Linux with Go 1.15.1, GOOS=windows GOARCH=amd64, which is why the file paths in their stack traces are Linux paths. The C programs and the cgo program are built with Ubuntu 18.04’s mingw-w64 cross compiler, gcc 7.3. Rust 1.46.0, .NET Core SDK 3.1.401 with runtime 3.1.7, and AdoptOpenJDK 11.0.8 are installed in the VM from their release archives, and their programs are built there.

Two Windows counters appear throughout. A process’s commit charge (Task Manager calls it “Commit size”, the API PrivateUsage) is the private memory Windows has promised to the process. Its working set is the part of the process’s memory that is resident right now, which is what Linux calls RSS. A small file, wincounters.go, reads both from Go through psapi:

func countersOf(h syscall.Handle) memCounters {
	var c memCounters
	c.cb = uint32(unsafe.Sizeof(c))
	getPMI.Call(uintptr(h), uintptr(unsafe.Pointer(&c)), uintptr(c.cb))
	return c
}

Two steps where Linux has one

On Linux, as Part 3 showed, the Go runtime gets address space with mmap, and the kernel finds physical memory for a page the first time the page is touched. Nothing is promised in between. By default Linux does not count what it has handed out against what it has, so a program can map far more than the machine holds, as long as it does not touch it all.

Windows splits the same thing into two calls, both spelled VirtualAlloc. MEM_RESERVE claims a range of addresses and nothing else: no memory backs it, and touching it is an access violation. MEM_COMMIT turns reserved addresses into memory the process may use, and that is the step Windows accounts for. Every committed private page is added to the system’s commit charge, and the total may not exceed the commit limit, which is roughly physical memory plus the page files. Windows does not overcommit. When it commits a page it guarantees that the page will have somewhere to live, in memory or in the page file, whether or not the program ever touches it. The physical page itself is still found only on the first touch; what is decided up front is the promise.

The runtime’s Windows layer, mem_windows.go, maps its own vocabulary onto that. Reserving address space for the heap is MEM_RESERVE:

func sysReserve(v unsafe.Pointer, n uintptr) unsafe.Pointer {
	// v is just a hint.
	// First try at v.
	// This will fail if any of [v, v+n) is already reserved.
	v = unsafe.Pointer(stdcall4(_VirtualAlloc, uintptr(v), n, _MEM_RESERVE, _PAGE_READWRITE))
	if v != nil {
		return v
	}

	// Next let the kernel choose the address.
	return unsafe.Pointer(stdcall4(_VirtualAlloc, 0, n, _MEM_RESERVE, _PAGE_READWRITE))
}

On Linux the next step, sysMap, makes a reserved range readable and writable. On Windows it does nothing but count:

func sysMap(v unsafe.Pointer, n uintptr, sysStat *uint64) {
	mSysStatInc(sysStat, n)
}

The commit happens later, in sysUsed, when the page allocator hands out pages that are not backed:

func sysUsed(v unsafe.Pointer, n uintptr) {
	p := stdcall4(_VirtualAlloc, uintptr(v), n, _MEM_COMMIT, _PAGE_READWRITE)
	if p == uintptr(v) {
		return
	}

and the scavenger of Part 5, which on Linux calls madvise, decommits with VirtualFree(MEM_DECOMMIT). The page allocator decides when to call sysUsed from its scavenged bitmap, and a page the heap has just grown into counts as scavenged; mpagealloc.go says so in as many words: “Newly-grown memory is always considered scavenged.” So the heap is committed span by span, at the moment a span is allocated.

Here is what that looks like from outside. winmem.go allocates a gigabyte in 1 MB slices without writing to it, then writes one byte in every page, then drops it, then asks the runtime to return it:

package main

import (
	"fmt"
	"runtime"
	"runtime/debug"
)

var keep [][]byte

func report(step string) {
	c := counters()
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%-30s commit %5d MB  working set %5d MB  HeapSys %5d  HeapReleased %5d MB\n",
		step, c.PrivateUsage>>20, c.WorkingSetSize>>20, m.HeapSys>>20, m.HeapReleased>>20)
}

func main() {
	fmt.Println(runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH)
	report("start")
	for i := 0; i < 1024; i++ {
		keep = append(keep, make([]byte, 1<<20)) // allocated, never written
	}
	report("1 GB allocated, not written")
	for _, b := range keep {
		for j := 0; j < len(b); j += 4096 {
			b[j] = 1
		}
	}
	report("the same 1 GB written")
	keep = nil
	runtime.GC()
	report("dropped and collected")
	debug.FreeOSMemory()
	report("after debug.FreeOSMemory")
}
C:\work2>winmem.exe
go1.15.1 windows/amd64
start                          commit    12 MB  working set     4 MB  HeapSys     3  HeapReleased     3 MB
1 GB allocated, not written    commit  1074 MB  working set    40 MB  HeapSys  1027  HeapReleased     2 MB
the same 1 GB written          commit  1074 MB  working set  1064 MB  HeapSys  1027  HeapReleased     2 MB
dropped and collected          commit  1074 MB  working set  1064 MB  HeapSys  1027  HeapReleased     2 MB
after debug.FreeOSMemory       commit    50 MB  working set    39 MB  HeapSys  1027  HeapReleased  1027 MB

The second line is the Windows story in one row. The program has written nothing, its working set has grown by 36 MB, and its commit charge has grown by the whole gigabyte. Writing the gigabyte changes the working set and not the commit charge, because the promise was made at allocation. Dropping the slices and collecting them changes neither: the memory is free inside the heap, HeapReleased is still 2 MB, and the runtime keeps it committed for the next allocation. Only when the runtime hands the pages back, here forced by debug.FreeOSMemory, does the commit charge fall, to 50 MB.

Left alone, the background scavenger from Part 5 does the same thing slowly. scav.go writes and drops a gigabyte, collects it, and then just watches:

C:\work2>scav.exe
go1.15.1 windows/amd64
   0s  commit  1074 MB  working set  1064 MB  HeapReleased     3 MB
  15s  commit  1074 MB  working set  1064 MB  HeapReleased     3 MB
  30s  commit  1022 MB  working set  1012 MB  HeapReleased    54 MB
  45s  commit   970 MB  working set   960 MB  HeapReleased   106 MB
  60s  commit   918 MB  working set   908 MB  HeapReleased   158 MB
  75s  commit   866 MB  working set   856 MB  HeapReleased   210 MB
  90s  commit   814 MB  working set   804 MB  HeapReleased   262 MB
 105s  commit   762 MB  working set   752 MB  HeapReleased   314 MB
 120s  commit   710 MB  working set   700 MB  HeapReleased   366 MB
 135s  commit   659 MB  working set   649 MB  HeapReleased   418 MB
 150s  commit   607 MB  working set   596 MB  HeapReleased   470 MB
 165s  commit   555 MB  working set   544 MB  HeapReleased   522 MB
 180s  commit   503 MB  working set   493 MB  HeapReleased   574 MB
 195s  commit   452 MB  working set   441 MB  HeapReleased   625 MB
 210s  commit   401 MB  working set   391 MB  HeapReleased   676 MB
 225s  commit   349 MB  working set   339 MB  HeapReleased   727 MB
 240s  commit   298 MB  working set   287 MB  HeapReleased   779 MB
 255s  commit   246 MB  working set   236 MB  HeapReleased   830 MB
 270s  commit   194 MB  working set   184 MB  HeapReleased   882 MB
 285s  commit   142 MB  working set   132 MB  HeapReleased   934 MB
 300s  commit    90 MB  working set    80 MB  HeapReleased   986 MB

The commit charge falls by 52 MB every 15 seconds, about 3.5 MB a second, close to the rate Part 5 measured on Linux, and it takes five minutes to give the gigabyte back. On Windows the decommit does what MADV_DONTNEED does on Linux: the working set falls with the commit charge, step for step. There is no equivalent of Linux’s lazy MADV_FREE here, so the numbers in Task Manager agree with HeapReleased at every sample.

The 36 MB that nobody wrote

The second line of winmem has a puzzle in it, and it is one Part 5 left open. There, on Linux, a 1 GB ballast that was never written still added 34 MB to the process’s RSS, and I did not find where it went. Here the same thing appears as working set: 36 MB for a gigabyte nobody wrote. It is not the gigabyte. It is the heap’s bookkeeping for the gigabyte.

Every arena of the heap has a heapArena structure, and the biggest part of it is the heap bitmap, two bits for every 8-byte word of the arena, which is how the collector knows which words hold pointers. That makes it 1/32 of the arena’s size, by its own definition in malloc.go:

	heapArenaBitmapBytes = heapArenaBytes / (sys.PtrSize * 8 / 2)

When the runtime allocates a large object, largeAlloc initialises the bitmap for the object’s span:

	s.limit = s.base() + size
	heapBitsForAddr(s.base()).initSpan(s)

and for any span whose objects are not single pointers, which includes plain bytes, initSpan clears its part of the bitmap, one byte for every four words:

		} else {
			memclrNoHeapPointers(unsafe.Pointer(h.bitp), nbyte)
		}

Clearing memory is writing it. A gigabyte of []byte writes 32 MB of bitmap, which become resident whether or not anyone touches the gigabyte. The span table, one 8-byte pointer per 8 KB page, adds 1 MB more. That is 33 MB for every gigabyte, and the runs here agree: in limit.go below, every gigabyte adds 34 MB of working set, and in the Linux run every 16 GB adds 530 MB of RSS, 33 MB a gigabyte. The same call is in Go 1.13.1, so this is the 34 MB of Part 5’s ballast.

Running out of commit

Because Windows promises at commit time, it is also at commit time that it refuses. limit.go asks for a gigabyte at a time and writes nothing:

package main

import (
	"fmt"
	"runtime"
)

var keep [][]byte

// Allocate 1 GB at a time without ever writing to it, until the
// runtime cannot get any more from the operating system.
func main() {
	p := perf()
	fmt.Printf("%s: RAM %d MB, commit limit %d MB, committed %d MB\n", runtime.Version(),
		p.PhysicalTotal*p.PageSize>>20, p.CommitLimit*p.PageSize>>20, p.CommitTotal*p.PageSize>>20)
	for i := 1; ; i++ {
		keep = append(keep, make([]byte, 1<<30))
		p = perf()
		fmt.Printf("%3d GB allocated: process commit %6d MB, working set %4d MB, system committed %6d of %6d MB\n",
			i, counters().PrivateUsage>>20, counters().WorkingSetSize>>20, p.CommitTotal*p.PageSize>>20, p.CommitLimit*p.PageSize>>20)
	}
}
C:\work2>limit.exe
go1.15.1: RAM 4094 MB, commit limit 5502 MB, committed 554 MB
  1 GB allocated: process commit   1074 MB, working set   39 MB, system committed   1616 of   5502 MB
  2 GB allocated: process commit   2134 MB, working set   73 MB, system committed   2651 of   5502 MB
  3 GB allocated: process commit   3194 MB, working set  107 MB, system committed   3684 of   5502 MB
  4 GB allocated: process commit   4254 MB, working set  141 MB, system committed   4744 of   5502 MB
  5 GB allocated: process commit   5315 MB, working set  175 MB, system committed   5804 of   7057 MB
  6 GB allocated: process commit   6375 MB, working set  209 MB, system committed   6864 of   7779 MB
  7 GB allocated: process commit   7435 MB, working set  243 MB, system committed   7924 of   8727 MB
  8 GB allocated: process commit   8495 MB, working set  277 MB, system committed   8984 of   9149 MB
runtime: VirtualAlloc of 1073741824 bytes failed with errno=1455
fatal error: out of memory
...

The commit limit starts at 5,502 MB: 4 GB of memory and a 1,408 MB page file. At the fifth gigabyte the program passes it, and Windows does what it does when a system-managed page file is too small: it grows the page file, and says so in the System event log (“Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file”). The limit climbs to 9,149 MB, and the ninth gigabyte does not fit. The runtime’s sysUsed gets error 1455, ERROR_COMMITMENT_LIMIT, and Go has nothing to do but stop. Through all of it the working set never passed 277 MB.

The same program for Linux reads /proc/self/status instead, and stops at 64 GB because I told it to:

$ cat /proc/sys/vm/overcommit_memory; free -m | head -2; go run overcommit.go
0
              total        used        free      shared  buff/cache   available
Mem:          31724         945       29574           4        1205       30455
go1.15.1 linux
 16 GB allocated: VmSize 18024564 kB, VmRSS 545116 kB
 32 GB allocated: VmSize 35344756 kB, VmRSS 1087544 kB
 48 GB allocated: VmSize 52663668 kB, VmRSS 1629824 kB
 64 GB allocated: VmSize 69984372 kB, VmRSS 2172400 kB

Sixty-four gigabytes on a 31 GB machine, with 2 GB resident. Mode 0, Linux’s default, refuses only a single request that could obviously never be met, and none of these is. Linux settles the bill when the pages are touched, and if they are touched past what the machine has, it is the OOM killer that settles it, later and somewhere else.

Allocating memory that is never written

One gigabyte at a time with make([]byte, 1<<30), nothing stored in it, on Go 1.15.1.

promised to the processresident (working set, RSS)the system's limit

Windows Server 2019, 4 GB of memory: commit charge, MB

1 GB
1,074 / 39 of 5,502
2 GB
2,134 / 73 of 5,502
3 GB
3,194 / 107 of 5,502
4 GB
4,254 / 141 of 5,502
5 GB
5,315 / 175 of 7,057
6 GB
6,375 / 209 of 7,779
7 GB
7,435 / 243 of 8,727
8 GB
8,495 / 277 of 9,149

9 GB: VirtualAlloc failed with errno=1455, fatal error: out of memory

Linux, 31 GB of memory: address space and RSS, MB

16 GB
17,602 / 532 of 31,724
32 GB
34,516 / 1,062 of 31,724
48 GB
51,429 / 1,592 of 31,724
64 GB
68,344 / 2,121 of 31,724

On Windows the line is the commit limit, which rose from 5,502 MB as the page file grew. On Linux the line is physical memory, which the process passed without complaint: in its default mode Linux does not add up what it has promised.

Windows can also put a commit limit on a single process, through a job object, which is how a service manager or a container runtime caps a process’s memory there. jobrun.go starts a program inside a job with JOB_OBJECT_LIMIT_PROCESS_MEMORY set; with a 3 GB limit:

C:\work2>jobrun.exe 3072 .\limit.exe
go1.15.1: RAM 4094 MB, commit limit 5502 MB, committed 576 MB
  1 GB allocated: process commit   1073 MB, working set   39 MB, system committed   1639 of   5502 MB
  2 GB allocated: process commit   2134 MB, working set   73 MB, system committed   2699 of   5502 MB
runtime: VirtualAlloc of 1073741824 bytes failed with errno=1455
fatal error: out of memory
...
jobrun: .\limit.exe exited with code 2 under a 3072 MB per-process limit

The third gigabyte fails, with the same error, at the same line of the runtime:

runtime.sysUsed(0xc080190000, 0x40000000)
	/opt/go/1.15.1/src/runtime/mem_windows.go:83 +0x22e

The practical difference is where a Go program finds out. On Linux, a program that sizes a buffer generously and uses a fraction of it pays for the fraction; on Windows it pays for the whole buffer, in commit, and an out-of-memory failure arrives at the make, as a fatal error that cannot be recovered, while the machine still has free memory.

Heap arenas are 4 MB here

Part 3 showed Go 1.11 replacing one huge heap reservation with 64 MB arenas, reserved as the heap grows. On Windows they are 4 MB, and malloc.go gives the reason:

	// This is currently 64MB on 64-bit non-Windows and 4MB on
	// 32-bit and on Windows. We use smaller arenas on Windows
	// because all committed memory is charged to the process,
	// even if it's not touched. Hence, for processes with small
	// heaps, the mapped arena space needs to be commensurate.
	// This is particularly important with the race detector,
	// since it significantly amplifies the cost of committed
	// memory.

In 1.15.1 the arena itself is no longer committed when it is mapped, as sysMap showed, but its heapArena metadata still is: the runtime allocates that with persistentalloc, which on Windows commits. For a 64 MB arena that would be a 2 MB bitmap and a 64 KB span table, committed for every arena from the first; for a 4 MB arena it is 128 KB and 4 KB. By that arithmetic, small arenas are what keep a small Go program’s commit charge small: winmem started at 12 MB.

A program can see the arenas by walking its own address space with VirtualQuery, which reports each region and the reservation it belongs to. arenas.go grows the heap to 64 MB and counts the reservations at Go’s heap address:

C:\work2>arenas.exe
go1.15.1 windows/amd64
heap reservations at 0xc000000000: 17, from 0xc000000000 to 0xc004400000
   17 of 4 MB

Seventeen separate reservations, each 4 MB, side by side. The runtime asks for them at consecutive addresses so the heap is contiguous, but to Windows they are seventeen allocations, and that has a consequence the runtime has to work around: VirtualFree only works within one reservation. The comment on sysUnused explains that the runtime tries successively smaller pieces when a decommit straddles two. Small arenas also mean many of them, so on 64-bit Windows the runtime keeps its arena index two levels deep (arenaL1Bits = 6 * (_64bit * sys.GoosWindows)), where Linux needs one.

Where a goroutine’s stack comes from

Part 1 measured a new goroutine’s stack at 2 KB. On Windows, the same measurement says 8 KB. gocost.go starts 100,000 goroutines that block on a channel, then 1,000 that each lock an operating-system thread for themselves, and divides what changed in MemStats.StackInuse, the commit charge and the reserved address space by the count:

	for i := 0; i < ng; i++ {
		go func() { started.Done(); <-block }()
	}
	started.Wait()
	report("100,000 goroutines", ng, a)

	// 1,000 goroutines that each hold an operating-system thread of their own.
	a = take()
	const nt = 1000
	started.Add(nt)
	for i := 0; i < nt; i++ {
		go func() { runtime.LockOSThread(); started.Done(); <-block }()
	}
	started.Wait()
	time.Sleep(100 * time.Millisecond)
	report("1,000 goroutines on own threads", nt, a)
	close(block)
}
C:\work2>gocost.exe
go1.15.1 windows/amd64
100,000 goroutines               each: goroutine stack  8192 B, commit   9105 B, reserved       -7 B; threads +1
1,000 goroutines on own threads  each: goroutine stack  8126 B, commit  47517 B, reserved  2081624 B; threads +1003

and the same program on Linux, measured with /proc/self/status:

$ go run threadslinux.go
go1.15.1 linux/amd64
100,000 goroutines               each: goroutine stack  2055 B, resident   2685 B, address space     2138 B; threads +19
1,000 goroutines on own threads  each: goroutine stack 43122 B, resident  19001 B, address space    70651 B; threads +1001

The first lines differ by a factor of four. The reason is a constant in stack.go:

	// 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 = sys.GoosWindows*512*sys.PtrSize + sys.GoosPlan9*512 + sys.GoosDarwin*sys.GoarchArm*1024 + sys.GoosDarwin*sys.GoarchArm64*1024

On Linux, the runtime gives each thread a separate signal stack, 32 KB, and a signal is delivered there, whatever the goroutine was doing. Windows has no such thing. A processor exception, a page fault on a nil pointer or the arithmetic fault of a division by zero, is dispatched on the stack of the thread that faulted, and the first thing the dispatcher does is write the processor’s context record and the exception record onto that stack, well over a kilobyte on x64 (the context record alone is 1,232 bytes), before it calls any handler. On a Go thread that stack is the goroutine’s. The runtime’s handler, sigtramp in sys_windows_amd64.s, moves to the thread’s system stack as soon as it can:

	// do we need to switch to the g0 stack?
	MOVQ	g_m(DX), BX
	MOVQ	m_g0(BX), BX
	CMPQ	DX, BX
	JEQ	g0

	// switch to g0 stack

but by then Windows has already used the goroutine’s stack, and the goroutine’s stack check knows nothing about it. So on Windows every goroutine’s stack carries 512 extra words, 4 KB, below the point where the stack check would grow it. The guard moves up by the same amount (`_StackGuard = 928*sys.StackGuardMultiplier

  • _StackSystem), and the minimum stack, rounded up to a power of two, becomes 2048 + 4096`, rounded to 8,192 bytes. Every goroutine pays it, whether it ever faults or not. A hundred thousand idle goroutines are charged 9,105 bytes each on Windows, against 2,685 bytes each of resident memory on Linux.

Where a thread’s stack comes from

The second lines differ the other way round, and the reason is that on Linux the runtime makes a thread’s stacks itself, while on Windows it lets Windows do it. On Linux, allocm gives a new thread a system stack (g0) of 8 KB from the heap, and mpreinit a 32 KB signal stack, and then starts the thread with clone on Go’s own memory. That is the 43,122 bytes of stack per locked thread above: 8 KB, 32 KB and the goroutine’s 2 KB, all of it counted in StackInuse. proc.go says which systems are different:

	// In case of cgo or Solaris or illumos or Darwin, pthread_create will make us a stack.
	// Windows and Plan 9 will layout sched stack on OS stack.
	if iscgo || GOOS == "solaris" || GOOS == "illumos" || GOOS == "windows" || GOOS == "plan9" || GOOS == "darwin" {
		mp.g0 = malg(-1)
	} else {
		mp.g0 = malg(8192 * sys.StackGuardMultiplier)
	}

On Windows, newosproc calls CreateThread and asks for no particular stack size:

	// We pass 0 for the stack size to use the default for this binary.
	thandle := stdcall6(_CreateThread, 0, 0,
		funcPC(tstart_stdcall), uintptr(unsafe.Pointer(mp)),
		0, 0)

Zero means the default from the executable’s PE header, and the Go linker writes 2 MB of reserve and one 4 KB page of initial commit there (pe.go):

	oh64.SizeOfStackReserve = 0x00200000
	if !iscgo {
		oh64.SizeOfStackCommit = 0x00001000

When the thread starts, minit asks Windows where its stack is and adopts it as g0, keeping 16 KB clear at the bottom:

	// The system leaves an 8K PAGE_GUARD region at the bottom of
	// the stack (in theory VirtualQuery isn't supposed to include
	// that, but it does). Add an additional 8K of slop for
	// calling C functions that don't have stack checks and for
	// lastcontinuehandler. We shouldn't be anywhere near this
	// bound anyway.
	base := mbi.allocationBase + 16<<10

So a Go thread on Windows has a 2 MB stack that Windows reserves, commits a page at a time as it is used, and frees when the thread exits; the runtime only reads its bounds. That explains the Windows row: each locked thread adds just its goroutine’s 8 KB to StackInuse, because the thread’s own stack is not the runtime’s, and 2 MB of reserved address space, which is. It also adds 47 KB of commit, against 19 KB resident on Linux, for whatever Windows commits for a thread, presumably the first stack pages, the guard region and the thread environment block, and for the runtime’s own per-thread structures; I did not break it down.

The reserve costs no memory, only address space, of which 64-bit Windows gives a process 128 TB. It matters for what it says about a thread: Go code running on that stack is still checked, since minit sets the guard from the bounds it found, but C code called on it is not, and when C runs out of those 2 MB it is Windows that notices. More on that below.

A thousand threads, five runtimes

Every runtime here makes its threads through the same Windows API, so the same experiment can be run in each. Each program waits for a line on standard input, starts 1,000 threads that block, says so, and waits again. measure.go starts the program, opens it with OpenProcess, and reads its commit charge, working set and reserved address space from outside, before and after:

C:\work2>measure.exe "C, CreateThread" .\cthreads.exe
C, CreateThread              per thread: commit   30.6 KB  reserved  2029.8 KB  working set   14.5 KB  (threads +998)

The same for Go’s goroutines and locked threads, Rust’s std::thread::spawn, .NET’s new Thread and Java’s new Thread, all with their default stack sizes, three runs of each:

What one thread costs on Windows

Per thread, from 1,000 threads (or goroutines) blocked in each runtime. Median of three runs.

Commit charge, KB

Go goroutine
10.5 KB
Go locked thread
47.3 KB
C
30.6 KB
Rust 1.46
45.2 KB
.NET Core 3.1
54.2 KB
Java 11
87.2 KB

Address space reserved but not committed, KB

Go goroutine
0 KB
Go locked thread
2,027 KB
C
2,030 KB
Rust 1.46
2,021 KB
.NET Core 3.1
1,506 KB
Java 11
973 KB

Hover or focus a row for all three runs.

The reservations come from two places. Where a runtime passes 0 to CreateThread, as Go, C and .NET do, the size is the executable’s PE header; where it passes a size, it is that. peheader.go reads the headers with debug/pe:

C:\work2>peheader.exe .\winmem.exe .\cgostack.exe .\cthreads.exe .\rthreads.exe C:\tools\jdk-11.0.8+10\bin\java.exe C:\tools\dotnet\dotnet.exe C:\work2\cs\out\Threads.exe C:\Windows\System32\notepad.exe C:\Windows\System32\cmd.exe C:\Windows\System32\svchost.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
winmem.exe       stack reserve  2048 KB  commit     4 KB  linker 3.0  ASLR yes
cgostack.exe     stack reserve  2048 KB  commit     4 KB  linker 2.30  ASLR yes
cthreads.exe     stack reserve  2048 KB  commit     4 KB  linker 2.30  ASLR yes
rthreads.exe     stack reserve  2048 KB  commit     4 KB  linker 2.27  ASLR no
java.exe         stack reserve  1024 KB  commit     4 KB  linker 14.16  ASLR yes
dotnet.exe       stack reserve  1536 KB  commit     4 KB  linker 14.16  ASLR yes
Threads.exe      stack reserve  1536 KB  commit     4 KB  linker 14.16  ASLR yes
notepad.exe      stack reserve   512 KB  commit    68 KB  linker 14.13  ASLR yes
cmd.exe          stack reserve  1024 KB  commit  1008 KB  linker 14.13  ASLR yes
svchost.exe      stack reserve   512 KB  commit    16 KB  linker 14.13  ASLR yes
powershell.exe   stack reserve   512 KB  commit     8 KB  linker 14.13  ASLR yes

The “linker” column is the version the linker stamps into the header: 3.0 is Go’s own linker, 2.30 and 2.27 are GNU ld (mingw’s, and the one that came with Rust’s windows-gnu toolchain, the only linker in the VM), and 14.x is Microsoft’s, from Visual Studio 2017. Microsoft’s documentation for the /STACK linker option gives its default as 1 MB of reserve and 4 KB of commit, and that is what java.exe has. GNU ld’s default is 2 MB, and the Go linker writes 2 MB too, for a reason its comment gives: system calls, and C reached through the syscall package, “may need more stack than we think”. Microsoft’s .NET Core host is linked with 1.5 MB, and Windows’ own programs mostly set 512 KB; cmd.exe commits almost its whole megabyte up front.

What each runtime does with that:

  • C, with CreateThread(NULL, 0, ...), gets the header’s 2 MB and pays the least, 30.6 KB of commit and 14.5 KB resident per thread.
  • Rust 1.46 does not use the header: std::thread asks for RUST_MIN_STACK, by default 2 MiB, and passes STACK_SIZE_PARAM_IS_A_RESERVATION, so the number is a reservation and not a commit. It commits 15 KB more than C; some of that is probably the 20 KB every Rust thread asks Windows to keep back for its stack-overflow handler, which comes up again below.
  • .NET Core 3.1 passes 0 and inherits dotnet.exe’s 1.5 MB, so a .NET thread’s default stack on Windows is not the 1 MB it is often said to be. It commits 54 KB.
  • Java 11 reserves 1 MB per thread and commits the most of the six, 87 KB, with 63 KB resident.
  • Go, for a locked thread, sits between C and .NET, and a goroutine costs 10.5 KB with nothing reserved: its 8 KB stack and what else the runtime keeps for it. (This is slightly more than gocost measured, because the measurement here is from outside and includes the runtime’s own growth for 1,000 goroutines.)

On Linux the gap between a goroutine and a thread is the familiar one from Part 1. On Windows it is the same in kind and smaller in ratio, because the goroutine has grown to 8 KB. It is still a factor of three in commit against the cheapest thread here and eight against Java’s, and a goroutine reserves no address space at all.

When a stack runs out

Windows grows a thread’s stack with a guard page. The committed part of the stack ends in a page marked PAGE_GUARD; touching it raises an exception that the kernel handles itself, by committing that page and marking the next one down as the guard. That is why a thread’s commit starts small, one page by the header, 20 or 24 KB by the time C was running on Go’s threads above, and grows with use. It is also why code must not skip a page: a function whose frame is bigger than a page has to touch each page in order, or it will jump past the guard into reserved memory and fault. Microsoft’s x64 calling convention requires exactly that: a prologue that allocates a page or more calls __chkstk, which probes the new frame a page at a time. gcc on Windows does the same with ___chkstk_ms. When the guard reaches the bottom of the reservation, less one page, the exception becomes EXCEPTION_STACK_OVERFLOW, code 0xC00000FD.

A goroutine’s stack is none of this. It is ordinary heap memory, committed when the span was allocated, with no guard page, and the stack check in every function’s prologue is what stops a goroutine from running off its end, as Part 1 showed. A goroutine that recurses forever ends the way it does on Linux:

C:\work2>goover.exe
go1.15.1 windows/amd64
runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc0200e1378 stack=[0xc0200e0000, 0xc0400e0000]
fatal error: stack overflow
...

The other runtimes meet the Windows exception. Each recursed without limit on its main thread; for C and Rust each frame holds a 1 KB buffer:

RuntimeMain thread’s stackWhat the program printedExit code
Go 1.15.1, a goroutineGo’s, up to 1 GBfatal error: stack overflow2
C, mingw-w64 gcc 7.32 MB, from the PE headernothing after its depth, last 1,792 frames0xC00000FD
Rust 1.46.02 MB, from the PE headerthread 'main' has overflowed its stack0xC00000FD
.NET Core 3.1.71.5 MB, from the PE headerStack overflow.0xC00000FD
Java 11.0.81 MB, HotSpot’s defaultStackOverflowError at depth 21918, caught0

C does nothing about it, so Windows ends the process with the exception’s own code and no message; run from a console, it simply stops. Rust’s standard library, in sys/windows/stack_overflow.rs, installs a vectored exception handler that prints which thread overflowed and lets the process die, and it calls SetThreadStackGuarantee with 0x5000 bytes on every thread. That call asks Windows to keep 20 KB of the stack back for exception handling, so the handler has room to print. .NET prints and ends the process too; its documentation says plainly that a StackOverflowException cannot be caught with try/catch. Java is the only one where the program survives: HotSpot protects pages near the end of every Java thread’s stack itself, before Windows’ guard page, turns a fault on them into a StackOverflowError, and the program catches it.

Turning an exception into a panic

The Go runtime installs its own vectored exception handler at startup (signal_windows.go):

func initExceptionHandler() {
	stdcall2(_AddVectoredExceptionHandler, 1, funcPC(exceptiontramp))

Vectored handlers run before the frame-based handlers C and C++ code installs, and Go registers its own first in the list. When the faulting instruction is Go code, the handler does on Windows what the signal handler does on Linux: it rewrites the goroutine’s context so that it resumes in sigpanic, and an access violation becomes a Go panic. The panic message even keeps the Linux word:

C:\work2>nilderef.exe
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x10f020b]

goroutine 1 [running]:
main.main()
	/work/go-p7build/nilderef.go:6 +0x2b

0xc0000005 is EXCEPTION_ACCESS_VIOLATION, the Windows name for a SIGSEGV. When the faulting instruction is not Go code, because the program called into C, the handler cannot make it a panic. It lets the exception go on to any other handler, and if nothing else handles it, Go’s last-chance handler, lastcontinuehandler, prints what happened and exits. cgostack.go writes through a null pointer in C:

C:\work2>cgostack.exe nil
go1.15.1 windows/amd64
Exception 0xc0000005 0x1 0x0 0x355f20
PC=0x355f20
signal arrived during external code execution
...

followed by the Go stack, the registers, and exit code 2. The same happens for a stack overflow in C. But here, as the opening said, the process does not exit.

A stack overflow that does not end

C code called from Go runs on the thread’s system stack, the 2 MB that Windows reserved. cgostack.go reports that stack from C and can then recurse in C until it runs out, on the main thread or on another one:

package main

// #include "stackinfo.h"
// static void report(void) { stack_report("C called from Go"); }
// static int deep(void) { return stack_recurse(0); }
// static int guarded(void) {
//     ULONG keep = 64 << 10; /* stack held back for exception handling */
//     SetThreadStackGuarantee(&keep);
//     return stack_recurse(0);
// }
// static void nilwrite(void) { *(volatile int *)0 = 1; }
import "C"

import (
	"fmt"
	"os"
	"runtime"
)

func init() { runtime.LockOSThread() } // keep main on the process's first thread

// cgostack main|thread [deep|guarded]: report, and optionally exhaust, the stack
// C code gets when Go calls it from the main goroutine or from one on another
// thread; "guarded" first asks Windows to hold 64 KB back for exception handling.
// cgostack nil: write through a null pointer in C.
func main() {
	fmt.Println(runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH)
	run := func() {
		C.report()
		if len(os.Args) > 2 {
			if os.Args[2] == "guarded" {
				C.guarded()
			}
			C.deep()
		}
	}
	switch os.Args[1] {
	case "main":
		run()
	case "thread":
		done := make(chan bool)
		go func() { runtime.LockOSThread(); run(); done <- true }()
		<-done
	case "nil":
		C.nilwrite()
	}
}

stackinfo.h holds the two C helpers: stack_report finds the stack’s top in the thread environment block and its bottom with VirtualQuery, and stack_recurse recurses with a 1 KB frame, printing its depth every 256 frames with WriteFile. Both threads get the 2 MB:

C:\work2>cgostack.exe main
go1.15.1 windows/amd64
C called from Go: stack reserved 2048 KB, committed 24 KB
C:\work2>cgostack.exe thread
go1.15.1 windows/amd64
C called from Go: stack reserved 2048 KB, committed 20 KB

Then the overflow, on the second thread:

C:\work2>cgostack.exe thread deep
go1.15.1 windows/amd64
  0 KB deep
  256 KB deep
  512 KB deep
  768 KB deep
  1024 KB deep
  1280 KB deep
  1536 KB deep
  1792 KB deep
Exception 0xc00000fd 0x1 0xfbd2203c70 0x12f5f4e
PC=0x12f5f4e
signal arrived during external code execution

main._Cfunc_deep(0x0)
	_cgo_gotypes.go:43 +0x50
main.main.func1()
...

The handler caught the overflow, printed the exception, a Go stack and the registers, and then nothing happened. The process stayed, with one thread left. In the first run that hung, I looked: the thread was in a wait whose reason Windows gave as UserRequest, and taskkill /F refused to end the process, answering “There is no running instance of the task”. Every hung process stayed in the process list until the machine restarted. I ran each case five times, with a 20-second limit:

CasePrinted, then hungKilled by Windows, no Go outputPrinted, exit code 2
main thread410
another thread500
main thread, 64 KB guaranteed005
another thread, 64 KB guaranteed005

The last two rows call SetThreadStackGuarantee before recursing, asking Windows to keep 64 KB back for exception handling, as Rust’s standard library does with 20 KB. With that, every run printed its report and exited with code 2, as Go’s crashes normally do.

I had no debugger in the VM, so what follows is my reading of the source, not a trace. When a thread’s stack overflows, Windows lets the exception be handled on what is left of it, a few pages. Go’s handler switches to g0, which for C code is the same exhausted stack, and lastcontinuehandler knows this; it removes the stack’s lower bound so that it can print at all:

	// In case we're handling a g0 stack overflow, blow away the
	// g0 stack bounds so we have room to print the traceback. If
	// this somehow overflows the stack, the OS will trap it.
	_g_.stack.lo = 0

After the traceback it calls exit(2), which in os_windows.go takes a lock and calls ExitProcess:

func exit(code int32) {
	// Disallow thread suspension for preemption. Otherwise,
	// ExitProcess and SuspendThread can race: SuspendThread
	// queues a suspension request for this thread, ExitProcess
	// kills the suspending thread, and then this thread suspends.
	lock(&suspendLock)
	atomic.Store(&exiting, 1)
	stdcall1(_ExitProcess, uintptr(code))
}

ExitProcess ends every other thread and then runs the process’s shutdown in this one, on whatever stack is left. If that faults again, the exception comes back to the same handler, which has already printed, and after two checks that do not apply here it does:

	if panicking != 0 { // traceback already printed
		exit(2)
	}

and exit takes suspendLock, which this thread already holds. A thread waiting on a lock it holds waits for ever. The runtime’s lock on Windows sleeps in WaitForSingleObject, which fits the UserRequest wait, and a process already inside ExitProcess fits what taskkill said. Sixty-four kilobytes of guaranteed stack give the first exit room to finish, and the hang goes away, which is what the guarded rows show; the one run that died silently is probably the other way this can end, where the handler’s own printing ran out of stack and Windows ended the process without asking. Why a second fault on a nearly exhausted stack comes back to the handler at all, rather than ending the process as it did once, I cannot tell from here. What I can say with certainty is the measured part: on Go 1.15.1, a C stack overflow under Go usually hangs the process instead of ending it, and reserving stack for exception handling on the thread prevents it.

The 2 MB is generous for most C. The danger is C code that recurses on its input, a parser or a tree walker, called on input from outside. A Windows service built that way does not crash and restart on bad input; it stops responding, with a crash report in its log, and stays.

What Go 1.15 changed

Go 1.15 was released on 11 August. Three of its changes touch this series.

Small integers no longer allocate when converted to an interface. Part 2 showed fmt arguments escaping to the heap through interface{}. For integers from 0 to 255, Go 1.15 now points the interface at a static table (staticuint64s) instead of allocating. A test that converts four integers:

	for _, v := range []int{7, 255, 256, 1000} {
		allocs := testing.AllocsPerRun(1000, func() { sink = v })
		t.Logf("int %4d -> interface{}: %.0f allocs", v, allocs)
	}
$ /opt/go/1.14.1/bin/go test -v -run TestBox -count 1 . | grep allocs
    TestBox: box15_test.go:11: int    7 -> interface{}: 1 allocs
    TestBox: box15_test.go:11: int  255 -> interface{}: 1 allocs
    TestBox: box15_test.go:11: int  256 -> interface{}: 1 allocs
    TestBox: box15_test.go:11: int 1000 -> interface{}: 1 allocs
$ /opt/go/1.15.1/bin/go test -v -run TestBox -count 1 . | grep allocs
    box15_test.go:11: int    7 -> interface{}: 0 allocs
    box15_test.go:11: int  255 -> interface{}: 0 allocs
    box15_test.go:11: int  256 -> interface{}: 1 allocs
    box15_test.go:11: int 1000 -> interface{}: 1 allocs

Seven and 255 stop allocating; 256, one past the table, still does.

The central free lists were rewritten. The release notes say “Allocation of small objects now performs much better at high core counts, and has lower worst-case latency.” The change replaces each mcentral’s locked span lists with lock-free span sets (mspanset.go, behind the constant go115NewMCentralImpl). On this series’ 24-thread Linux machine, a parallel benchmark of 64-byte allocations with 24 processors ran 11.9 to 12.5 ns per allocation on 1.15.1 against 12.5 to 13.0 ns on 1.14.1, three runs each; with four processors 1.15.1 was slightly slower, 10.2 to 10.9 ns against 10.0 to 10.3. That is too close to call either way, and I did not find a benchmark here that shows the improvement.

Windows executables are now built with ASLR. The go command builds Windows programs with -buildmode=pie by default, and the linker marks them as relocatable: the “ASLR yes” on winmem.exe above. The heap still asks for its arenas at 0xc000000000, as the arena walk showed.

What this means for Go code on Windows

Commit is the number to watch. On Windows, a Go program’s memory limit is its commit charge, not its working set. Memory the program allocates and never uses still counts, a heap the collector has freed still counts until the scavenger decommits it, and the scavenger takes minutes to do that. A Go service on Windows should be sized by Task Manager’s “Commit size”, and debug.FreeOSMemory brings it down at once when that matters.

Goroutines are four times bigger, and still cheap. At about 9 KB of commit each, a million goroutines need some 9 GB of commit on Windows, where on Linux they are resident in under 3 GB. Programs that hold that many need to know it.

C on Go’s threads has 2 MB and no safety net. C called through cgo, or a DLL called through syscall, runs on a 2 MB Windows stack that the runtime does not check. If that code can recurse on its input, give its thread a stack guarantee or run it on a thread of its own with a bigger stack, because a stack overflow there may hang the process instead of crashing it.

A thread costs tens of kilobytes in every runtime. The PE header decides more of a Windows thread’s reservation than the language does, and commit per thread runs from 30 KB in C to 87 KB in Java, a factor of three. Go’s locked threads are in the middle, and a goroutine is well below all of them.

A note on the evidence

What ran. Go 1.15.1 (released 1 September 2020; the official linux-amd64 and windows-amd64 archives, checked against their published SHA-256), cross-compiling for windows/amd64. Windows Server 2019 Standard evaluation, version 1809, build 17763.737, installed unattended from Microsoft’s September 2019 refresh of the install image, in a Hyper-V virtual machine with four virtual processors, 4 GB of memory, a Windows-managed page file and no network. C and cgo with Ubuntu 18.04’s mingw-w64 gcc 7.3; Rust 1.46.0 for x86_64-pc-windows-gnu; .NET Core SDK 3.1.401 with runtime 3.1.7; AdoptOpenJDK 11.0.8+10; each from its release archive, checked against its published checksum. The Linux runs used Go 1.15.1 and 1.14.1 on an Ubuntu 18.04 userland, in a chroot on a 24-thread x86-64 machine with 31 GB of memory under the host’s Linux kernel.

What was measured. The per-thread costs are three runs of each runtime, all shown in the figure’s hover text; commit, working set and reserved address space were read from outside the process with GetProcessMemoryInfo and a VirtualQueryEx walk of its private memory. The overflow table is one run of each runtime. The cgo overflow cases are five runs each, in one sitting, each stopped after 20 seconds. Before them, four runs of the unguarded cases also hung, and one guarded run on the main thread was ended by Windows after printing its depth, with no Go output; the replay’s unguarded run hung too. Standard output and standard error were captured to separate files; they are shown here in the order the program printed them, and the cgo stack report, which C’s stdio buffers when its output is a file, is shown from the runs that did not overflow. The system-wide commit-limit run, scav and arenas are single runs; winmem ran five times and the 3 GB job limit three, with the same results to within a megabyte.

What changed in the writing. The first overflow runs printed their depth with fprintf, and when the first one hung I took the cause to be the C runtime’s lock on stderr. Printing with WriteFile instead made no difference to the hang, which is how it came to be investigated. Each hung process stayed in the process list, held its executable open, and was cleared only by restarting the VM; one rebuilt program silently failed to replace the copy a hung process held, and its first “guarded” runs ran the old program. Those runs were discarded. The Go version of gocost was briefly overwritten by the Rust program of the same name.

What is not explained. Where exactly the cgo overflow hang waits is my reading of the source, as the section says, not observed in a debugger, and the UserRequest wait and taskkill’s answer were seen on the first hung process only. The breakdown of the 30 to 87 KB of commit per thread, beyond the stack’s own pages, was not measured.

What is quoted. Runtime source is from the go1.15.1 tag: mem_windows.go, malloc.go, mbitmap.go, mpagealloc.go, stack.go, proc.go, os_windows.go, signal_windows.go, sys_windows_amd64.s and the linker’s pe.go; largeAlloc’s initSpan call was checked at go1.13.1 too. The page-file messages are Windows’ System event log entries from the commit-limit run. The release notes are doc/go1.15.html. Rust’s are src/libstd/sys/windows/stack_overflow.rs, thread.rs and sys_common/thread.rs at the 1.46.0 tag. Microsoft’s documentation is the pages for the /STACK linker option, “Thread Stack Size”, SetThreadStackGuarantee, and the x64 prolog and __chkstk.

More