hostmem

package
v0.33.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package hostmem is the memory the Go host gives the C engine. It is mapped from the OS outside the Go heap, so the garbage collector neither scans nor moves it, and every VM has its own:

  • the chunks of its heap, which the engine's allocator asks for and manages. The engine counts the blocks it uses itself. Memory counts what the VM holds from the OS, its footprint.
  • its shadow stack, a fixed region for the C locals whose address is taken, with a guard page at the end it grows to.

The callbacks of the engine map onto it:

host_memory_grow(vm, size)       m.Grow(size), 0 when it fails
host_call, release a chunk       m.Free(base, size)
host_call, grow a chunk          m.Remap(base, size, newSize), on linux (CanRemap)
VM.ReleaseMemory                 JS_ReleaseStart, then m.Release with
                                 JS_ReleaseNextChunk and JS_ReleaseNextRange
VM.Close                         JS_FreeRuntime, then m.Close

None of these runs javascript or calls into the engine. A Memory is used by one goroutine at a time, as its VM is, and needs no lock. Nothing is shared between Memories but the page size. Apart from them, MapReadOnly maps bytes that several VMs read at once (readonly.go), and Take maps a block for a Go function javascript called to hold a long input or output in (block.go).

The errors are what the OS refused, with what was asked, and three more:

  • New refuses a shadow stack too large for the address space before it asks the OS.
  • Remap matches errors.ErrUnsupported where the OS cannot resize a mapping (CanRemap is false).
  • On windows, New fails when other threads took the aligned address of the stack 16 times in a row. The error wraps the last ERROR_INVALID_ADDRESS.

What only a bug of the engine or the host does panics: a size the engine does not ask for, a chunk or range the VM does not hold, a call after Close or after a Release that did not return. New panics too when the OS refuses to give back what the setup of a stack mapped itself.

Index

Constants

View Source
const (
	// Unit is what chunks are a multiple of: the engine asks for 64 KiB at a
	// time, the allocation granularity of windows.
	Unit = 64 << 10

	// DefaultStackSize is the size of a shadow stack unless the VM asks for
	// another.
	DefaultStackSize = 32 << 20

	// StackKeep is how much of the shadow stack, from its base, Release
	// leaves in memory: about what a render uses.
	StackKeep = 256 << 10
)
View Source
const BlockMin = 1 << 20

BlockMin is the least size Take maps from the OS. A shorter one is a Go allocation, which Go clears in less time than a piece of the work.

View Source
const CanRemap = true

CanRemap tells whether Remap can resize a chunk: linux has mremap.

View Source
const KeptMax = 64 << 20

KeptMax is the most bytes the Keeps of the process keep together.

Variables

This section is empty.

Functions

func Blocks

func Blocks() int64

Blocks returns how many blocks Take mapped that are not given back.

func Kept

func Kept() int64

Kept returns how many bytes the Keeps of the process keep.

func MapReadOnly

func MapReadOnly(b []byte) (uintptr, error)

MapReadOnly maps a copy of b that can only be read, and returns its address. When the OS refuses to make the pages read-only, MapReadOnly gives them back and returns the error. When it refuses that too, it panics with both errors.

func Mapped

func Mapped[T Elem](n int) bool

Mapped reports whether Take maps n elements of T from the OS: from BlockMin bytes. It panics, as Take does, on a negative n, and on one whose size overflows.

func ReadOnlySize

func ReadOnlySize(n int) uintptr

ReadOnlySize is how many bytes MapReadOnly maps for n bytes: whole pages, at least one.

func Take

func Take[T Elem](n int) (s []T, give func(), err error)

Take returns n zero elements of T, for the length of a call, and the function that gives them back, which must be called once nothing uses them any more, on every path: deferred, or by the owner of the slice when it keeps it past the call. Calling it again does nothing. Fewer than BlockMin bytes are a Go allocation, and give back nothing. A larger slice is a block mapped from the OS; err is what the OS refused, and the caller stops the call with the out of memory error.

func TakeKept

func TakeKept[T Elem](k *Keep, n int, stop func() bool) (s []T, give func(), stopped bool, err error)

TakeKept is Take for a call of the VM of k: the block k keeps when it holds n elements of T, else a block mapped from the OS, and give hands the block to k. Clearing a kept block reads stop between pieces, and stopped is true, with the block kept, when it says the call is to end. Fewer than BlockMin bytes are a Go allocation, as for Take.

func UnmapReadOnly

func UnmapReadOnly(addr uintptr, n int) error

UnmapReadOnly unmaps the mapping of MapReadOnly at addr, of n bytes.

Types

type Elem

type Elem interface {
	~bool | ~uint8 | ~uint16 | ~int32 | ~uint32 | ~int | ~uint64
}

Elem are the types a block holds: those with no pointer, which the garbage collector does not look for in it.

type Keep

type Keep struct {
	// Max is the largest block the Keep keeps.
	Max uintptr
	// Allow reports whether the Keep may keep a block of size bytes now.
	Allow func(size uintptr) bool
	// Hold, when set, is told the size of the block the Keep keeps each
	// time it changes, for the memory limit of the VM to count it.
	Hold func(size uintptr)
	// contains filtered or unexported fields
}

A Keep is the one block a VM keeps for its next call, so that a call that takes a block again finds its pages in memory: a block the OS maps anew hands over each page at its first write, about 6 µs a page of 4 KiB on a slow virtual machine, at every call. A block given back goes to the Keep when it is at most Max bytes and Allow lets it, the larger of two when the Keep has one already, and the other goes back to the OS. The block kept goes back to the OS after Idle has been called idle times with no block taken from it or kept in it, and at Close. All the Keeps of the process keep at most KeptMax bytes together, so that a pool of many VMs idle between calls holds no more.

A block from a Keep is cleared, over what the call asks of it, a piece at a time with a read of the call's stop between two. A Keep is used by the goroutine running its VM, as the VM is, and needs no lock.

func (*Keep) Close

func (k *Keep) Close()

Close gives the block k keeps back to the OS, and each block given to k from now on.

func (*Keep) Held

func (k *Keep) Held() uintptr

Held is the size of the block k holds: the one it keeps, or the one it is clearing for a call, which TryRelease cannot give back.

func (*Keep) Idle

func (k *Keep) Idle(idle int)

Idle counts a call of the VM that ended, and gives the block k keeps back to the OS when idle calls have ended since it was last kept or taken.

func (*Keep) Release

func (k *Keep) Release()

Release gives the block k keeps back to the OS. It panics when the OS refuses, with the block still kept, for a Release called again.

func (*Keep) Size

func (k *Keep) Size() uintptr

Size is the size of the block k keeps, 0 for none.

func (*Keep) TryRelease

func (k *Keep) TryRelease() error

TryRelease is Release returning the error of the OS refusing the block, for a caller that must not panic.

type Memory

type Memory struct {
	// contains filtered or unexported fields
}

Memory is the memory of one VM: the chunks of its heap and its shadow stack.

func New

func New(stackSize uintptr) (*Memory, error)

New reserves a shadow stack of stackSize bytes for a VM and starts with no chunk. stackSize is a power of two of at least Unit, and the stack is aligned to it, so that the engine finds the base and the space left from a pointer into the stack alone. The stack grows up, and the page right above it is a guard page, which faults when touched: the engine checks the space left before it uses it, so a fault there is a bug in the engine.

Only the pages of the stack the engine touches take memory. On windows the whole stack is committed at once, so it counts against the commit limit from the start.

When a step of the setup fails, New gives back what it still holds and returns the error. When the OS refuses that too, for a range New mapped itself, New panics with both errors: it offers no way to recover that range, and a caller that recovered from the panic may leak the mapping.

func (*Memory) Close

func (m *Memory) Close() error

Close unmaps every chunk and the shadow stack, after the engine freed its runtime. From then on only Usage, Stack and Close may be called. When the OS refuses some, Close returns the errors and keeps those counted, so Usage tells what is left, and Close again tries them again. Once all is unmapped, Close again does nothing.

func (*Memory) Free

func (m *Memory) Free(base, size uintptr) error

Free unmaps the chunk of size bytes at base at once: the engine emptied it and took it out of its heap, as it does with a chunk that held one large block. When the OS refuses, the chunk stays mapped and counted, for a later Free or Close.

func (*Memory) Grow

func (m *Memory) Grow(size uintptr) (uintptr, error)

Grow maps a chunk of size bytes for the heap, a multiple of Unit: it is host_memory_grow. When the OS refuses, it returns 0 and the error, and the engine runs out of memory. The engine checks its limit and its footprint budget before it asks.

func (*Memory) Release

func (m *Memory) Release(chunks, ranges func() (addr, size uintptr), stackUsed uintptr) (Released, error)

Release hands memory back to the OS, for VM.ReleaseMemory. chunks gives one by one the whole chunks the engine took out of its heap, and ranges the free memory inside the chunks it keeps, each until it returns a size of 0 (nil for none). Release unmaps the chunks, hands back the pages inside each range, and then the pages of the shadow stack above stackUsed bytes from its base, or above StackKeep when that is more. stackUsed is 0 when the VM is idle, or else where the innermost callback left the shadow stack.

Pages handed back read as zero when next touched on linux (MADV_DONTNEED), and the memory they took is free at once. On darwin (MADV_FREE) and on windows (MEM_RESET) the system takes them when it needs memory, and until then they may keep what they held. Pages that were not in memory count as handed back too.

An error of the OS on one chunk or range does not stop the others. Release returns them all, and a chunk the OS did not unmap stays mapped and counted.

chunks and ranges do not call the Memory. When one of them panics, or Release does on a range outside every chunk, the walk of the engine stops halfway, and the Memory takes only Close from then on. What was handed back until then is in the totals.

func (*Memory) Remap

func (m *Memory) Remap(base, size, newSize uintptr) (uintptr, error)

Remap resizes the chunk of size bytes at base to newSize, a multiple of Unit, and returns where it is now. The contents up to the smaller size stay, and the system moves the pages rather than copy them. The engine asks for it when the one large block of a chunk grows. Only linux can (CanRemap): the error elsewhere matches errors.ErrUnsupported, and the engine maps a new chunk, copies and frees the old one. When the OS refuses, the chunk stays as it was.

func (*Memory) Stack

func (m *Memory) Stack() (base, size uintptr)

Stack returns the base and the size of the shadow stack, 0 and 0 once Close unmapped it.

func (*Memory) Usage

func (m *Memory) Usage() Usage

Usage returns what the VM holds now. After a Close that unmapped all, it is zero but for the totals of Release.

type Released

type Released struct {
	Chunks uintptr // bytes of whole chunks unmapped: the footprint dropped by as much
	Pages  uintptr // bytes of free pages inside chunks, each range rounded inward to pages
	Stack  uintptr // bytes of pages of the shadow stack
}

Released is what Release handed back to the OS.

type Totals

type Totals struct {
	Memories int64 // Memories whose shadow stack is mapped
	Stacks   int64 // the bytes of those shadow stacks, the guard pages left out
	Chunks   int64 // chunks of the heaps of all Memories
	Heap     int64 // their bytes: the sum of the footprints
	ReadOnly int64 // bytes of the mappings of MapReadOnly not unmapped
}

Totals is what every Memory of the process and every read-only mapping hold from the OS together. Once every VM is closed and every shared copy freed, all of it is zero, unless the OS refused to unmap something, which then stays counted until a later Close unmaps it. A long run reads it to see that what the VMs hold stays bounded, and that closing them all gives everything back.

func ProcessTotals

func ProcessTotals() Totals

ProcessTotals returns the Totals of the process now. Each count is read on its own, so while other goroutines map or unmap, they may not all be of the same instant.

type Usage

type Usage struct {
	Chunks    int      // chunks of the heap
	Footprint uintptr  // their bytes, which the engine counts as its footprint too
	Stack     uintptr  // bytes of the shadow stack, the guard page left out
	Released  Released // what Release handed back, in total
}

Usage is what a VM holds from the OS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL