package runtime

Import Path
	runtime (on

Dependency Relation
	imports 13 packages, and imported by 28 packages

Involved Source Files alg.go arena.go asan0.go atomic_pointer.go cgo.go cgo_mmap.go cgo_sigaction.go cgocall.go cgocallback.go cgocheck.go chan.go checkptr.go compiler.go complex.go covercounter.go covermeta.go cpuflags.go cpuflags_amd64.go cpuprof.go cputicks.go create_file_unix.go debug.go debugcall.go debuglog.go debuglog_off.go defs_linux_amd64.go env_posix.go error.go exithook.go Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines. It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system. # Environment Variables The following environment variables ($name or %name%, depending on the host operating system) control the run-time behavior of Go programs. The meanings and use may change from release to release. The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. [runtime/debug.SetGCPercent] allows changing this percentage at run time. The GOMEMLIMIT variable sets a soft memory limit for the runtime. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix. The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes represent quantities of bytes as defined by the IEC 80000-13 standard. That is, they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on. The default setting is math.MaxInt64, which effectively disables the memory limit. [runtime/debug.SetMemoryLimit] allows changing this limit at run time. The GODEBUG variable controls debugging variables within the runtime. It is a comma-separated list of name=val pairs setting these named variables: allocfreetrace: setting allocfreetrace=1 causes every allocation to be profiled and a stack trace printed on each object's allocation and free. clobberfree: setting clobberfree=1 causes the garbage collector to clobber the memory content of an object with bad content when it frees the object. cpu.*: cpu.all=off disables the use of all optional instruction set extensions. cpu.extension=off disables use of instructions from the specified instruction set extension. extension is the lower case name for the instruction set extension such as sse41 or avx as listed in internal/cpu package. As an example cpu.avx=off disables runtime detection and thereby use of AVX instructions. cgocheck: setting cgocheck=0 disables all checks for packages using cgo to incorrectly pass Go pointers to non-Go code. Setting cgocheck=1 (the default) enables relatively cheap checks that may miss some errors. A more complete, but slow, cgocheck mode can be enabled using GOEXPERIMENT (which requires a rebuild), see for details. dontfreezetheworld: by default, the start of a fatal panic or throw "freezes the world", preempting all threads to stop all running goroutines, which makes it possible to traceback all goroutines, and keeps their state close to the point of panic. Setting dontfreezetheworld=1 disables this preemption, allowing goroutines to continue executing during panic processing. Note that goroutines that naturally enter the scheduler will still stop. This can be useful when debugging the runtime scheduler, as freezetheworld perturbs scheduler state and thus may hide problems. efence: setting efence=1 causes the allocator to run in a mode where each object is allocated on a unique page and addresses are never recycled. gccheckmark: setting gccheckmark=1 enables verification of the garbage collector's concurrent mark phase by performing a second mark pass while the world is stopped. If the second pass finds a reachable object that was not found by concurrent mark, the garbage collector will panic. gcpacertrace: setting gcpacertrace=1 causes the garbage collector to print information about the internal state of the concurrent pacer. gcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines onto smaller stacks. In this mode, a goroutine's stack can only grow. gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection, making every garbage collection a stop-the-world event. Setting gcstoptheworld=2 also disables concurrent sweeping after the garbage collection finishes. gctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard error at each collection, summarizing the amount of memory collected and the length of the pause. The format of this line is subject to change. Included in the explanation below is also the relevant runtime/metrics metric for each field. Currently, it is: gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # MB stacks, #MB globals, # P where the fields are as follows: gc # the GC number, incremented at each GC @#s time in seconds since program start #% percentage of time spent in GC since program start #+...+# wall-clock/CPU times for the phases of the GC #->#-># MB heap size at GC start, at GC end, and live heap, or /gc/scan/heap:bytes # MB goal goal heap size, or /gc/heap/goal:bytes # MB stacks estimated scannable stack size, or /gc/scan/stack:bytes # MB globals scannable global size, or /gc/scan/globals:bytes # P number of processors used, or /sched/gomaxprocs:threads The phases are stop-the-world (STW) sweep termination, concurrent mark and scan, and STW mark termination. The CPU times for mark/scan are broken down in to assist time (GC performed in line with allocation), background GC time, and idle GC time. If the line ends with "(forced)", this GC was forced by a runtime.GC() call. harddecommit: setting harddecommit=1 causes memory that is returned to the OS to also have protections removed on it. This is the only mode of operation on Windows, but is helpful in debugging scavenger-related issues on other platforms. Currently, only supported on Linux. inittrace: setting inittrace=1 causes the runtime to emit a single line to standard error for each package with init work, summarizing the execution time and memory allocation. No information is printed for inits executed as part of plugin loading and for packages without both user defined and compiler generated init work. The format of this line is subject to change. Currently, it is: init # @#ms, # ms clock, # bytes, # allocs where the fields are as follows: init # the package name @# ms time in milliseconds when the init started since program start # clock wall-clock time for package initialization work # bytes memory allocated on the heap # allocs number of heap allocations madvdontneed: setting madvdontneed=0 will use MADV_FREE instead of MADV_DONTNEED on Linux when returning memory to the kernel. This is more efficient, but means RSS numbers will drop only when the OS is under memory pressure. On the BSDs and Illumos/Solaris, setting madvdontneed=1 will use MADV_DONTNEED instead of MADV_FREE. This is less efficient, but causes RSS numbers to drop more quickly. memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate. When set to 0 memory profiling is disabled. Refer to the description of MemProfileRate for the default value. pagetrace: setting pagetrace=/path/to/file will write out a trace of page events that can be viewed, analyzed, and visualized using the x/debug/cmd/pagetrace tool. Build your program with GOEXPERIMENT=pagetrace to enable this functionality. Do not enable this functionality if your program is a setuid binary as it introduces a security risk in that scenario. Currently not supported on Windows, plan9 or js/wasm. Setting this option for some applications can produce large traces, so use with care. invalidptr: invalidptr=1 (the default) causes the garbage collector and stack copier to crash the program if an invalid pointer value (for example, 1) is found in a pointer-typed location. Setting invalidptr=0 disables this check. This should only be used as a temporary workaround to diagnose buggy code. The real fix is to not store integers in pointer-typed locations. sbrk: setting sbrk=1 replaces the memory allocator and garbage collector with a trivial allocator that obtains memory from the operating system and never reclaims any memory. scavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard error, roughly once per GC cycle, summarizing the amount of work done by the scavenger as well as the total amount of memory returned to the operating system and an estimate of physical memory utilization. The format of this line is subject to change, but currently it is: scav # KiB work (bg), # KiB work (eager), # KiB total, #% util where the fields are as follows: # KiB work (bg) the amount of memory returned to the OS in the background since the last line # KiB work (eager) the amount of memory returned to the OS eagerly since the last line # KiB now the amount of address space currently returned to the OS #% util the fraction of all unscavenged heap memory which is in-use If the line ends with "(forced)", then scavenging was forced by a debug.FreeOSMemory() call. scheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit detailed multiline info every X milliseconds, describing state of the scheduler, processors, threads and goroutines. schedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard error every X milliseconds, summarizing the scheduler state. tracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at which goroutines were created, where N limits the number of ancestor goroutines to report. This also extends the information returned by runtime.Stack. Ancestor's goroutine IDs will refer to the ID of the goroutine at the time of creation; it's possible for this ID to be reused for another goroutine. Setting N to 0 will report no ancestry information. tracefpunwindoff: setting tracefpunwindoff=1 forces the execution tracer to use the runtime's default stack unwinder instead of frame pointer unwinding. This increases tracer overhead, but could be helpful as a workaround or for debugging unexpected regressions caused by frame pointer unwinding. asyncpreemptoff: asyncpreemptoff=1 disables signal-based asynchronous goroutine preemption. This makes some loops non-preemptible for long periods, which may delay GC and goroutine scheduling. This is useful for debugging GC issues because it also disables the conservative stack scanning used for asynchronously preempted goroutines. The net and net/http packages also refer to debugging variables in GODEBUG. See the documentation for those packages for details. The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit. The GORACE variable configures the race detector, for programs built using -race. See for details. The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. GOTRACEBACK=wer is like “crash” but doesn't disable Windows Error Reporting (WER). For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug package's SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable. See The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see and GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system. # Security On Unix platforms, Go's runtime system behaves slightly differently when a binary is setuid/setgid or executed with setuid/setgid-like properties, in order to prevent dangerous behaviors. On Linux this is determined by checking for the AT_SECURE flag in the auxiliary vector, on the BSDs and Solaris/Illumos it is determined by checking the issetugid syscall, and on AIX it is determined by checking if the uid/gid match the effective uid/gid. When the runtime determines the binary is setuid/setgid-like, it does three main things: - The standard input/output file descriptors (0, 1, 2) are checked to be open. If any of them are closed, they are opened pointing at /dev/null. - The value of the GOTRACEBACK environment variable is set to 'none'. - When a signal is received that terminates the program, or the program encounters an unrecoverable panic that would otherwise override the value of GOTRACEBACK, the goroutine stack, registers, and other memory related information are omitted. fastlog2.go fastlog2table.go float.go hash64.go heapdump.go histogram.go iface.go lfstack.go lock_futex.go lockrank.go lockrank_off.go malloc.go map.go map_fast32.go map_fast64.go map_faststr.go mbarrier.go mbitmap.go mcache.go mcentral.go mcheckmark.go mem.go mem_linux.go metrics.go mfinal.go mfixalloc.go mgc.go mgclimit.go mgcmark.go mgcpacer.go mgcscavenge.go mgcstack.go mgcsweep.go mgcwork.go mheap.go minmax.go mpagealloc.go mpagealloc_64bit.go mpagecache.go mpallocbits.go mprof.go mranges.go msan0.go msize.go mspanset.go mstats.go mwbbuf.go nbpipe_pipe2.go netpoll.go netpoll_epoll.go nonwindows_stub.go os_linux.go os_linux_generic.go os_linux_noauxv.go os_linux_x86.go os_nonopenbsd.go os_unix.go pagetrace_off.go panic.go pinner.go plugin.go preempt.go preempt_nonwindows.go print.go proc.go profbuf.go proflabel.go race0.go rdebug.go retry.go runtime.go runtime1.go runtime2.go runtime_boring.go rwmutex.go security_linux.go security_unix.go select.go sema.go signal_amd64.go signal_linux_amd64.go signal_unix.go sigqueue.go sigqueue_note.go sigtab_linux_generic.go sizeclasses.go slice.go softfloat64.go stack.go stkframe.go string.go stubs.go stubs2.go stubs3.go stubs_amd64.go stubs_linux.go symtab.go symtabinl.go sys_nonppc64x.go sys_x86.go tagptr.go tagptr_64bit.go test_amd64.go time.go time_nofake.go timeasm.go tls_stub.go trace.go traceback.go type.go typekind.go unsafe.go utf8.go vdso_elf64.go vdso_linux.go vdso_linux_amd64.go write_err.go asm_amd64.h asm_ppc64x.h funcdata.h go_tls.h textflag.h asm.s asm_amd64.s duff_amd64.s memclr_amd64.s memmove_amd64.s preempt_amd64.s rt0_linux_amd64.s sys_linux_amd64.s test_amd64.s time_linux_amd64.s
Code Examples package main import ( "fmt" "runtime" "strings" ) func main() { c := func() { // Ask runtime.Callers for up to 10 PCs, including runtime.Callers itself. pc := make([]uintptr, 10) n := runtime.Callers(0, pc) if n == 0 { // No PCs available. This can happen if the first argument to // runtime.Callers is large. // // Return now to avoid processing the zero Frame that would // otherwise be returned by frames.Next below. return } pc = pc[:n] // pass only valid pcs to runtime.CallersFrames frames := runtime.CallersFrames(pc) // Loop to get frames. // A fixed number of PCs can expand to an indefinite number of Frames. for { frame, more := frames.Next() // Process this frame. // // To keep this example's output stable // even if there are changes in the testing package, // stop unwinding when we leave package runtime. if !strings.Contains(frame.File, "runtime/") { break } fmt.Printf("- more:%v | %s\n", more, frame.Function) // Check whether there are more frames to process after this one. if !more { break } } } b := func() { c() } a := func() { b() } a() }
Package-Level Type Names (total 328, in which 11 are exported)
/* sort exporteds by: | */
BlockProfileRecord describes blocking events originated at a particular call sequence (stack trace). Count int64 Cycles int64 StackRecord StackRecord // stack trace for this record; ends at first 0 entry Stack returns the stack trace associated with the record, a prefix of r.Stack0. func BlockProfile(p []BlockProfileRecord) (n int, ok bool) func MutexProfile(p []BlockProfileRecord) (n int, ok bool)
The Error interface identifies a run time error. ( Error) Error() builtin.string RuntimeError is a no-op function but serves to distinguish types that are run time errors from ordinary errors: a type is a run time error if it has a RuntimeError method. *PanicNilError *TypeAssertionError Error : error
Frame is the information returned by Frames for each call frame. Entry point program counter for the function; may be zero if not known. If Func is not nil then Entry == Func.Entry(). File and Line are the file name and line number of the location in this frame. For non-leaf frames, this will be the location of a call. These may be the empty string and zero, respectively, if not known. Func is the Func value of this call frame. This may be nil for non-Go code or fully inlined functions. Function is the package path-qualified function name of this call frame. If non-empty, this string uniquely identifies a single function in the program. This may be the empty string if not known. If Func is not nil then Function == Func.Name(). Line int PC is the program counter for the location in this frame. For a frame that calls another frame, this will be the program counter of a call instruction. Because of inlining, multiple frames may have the same PC value, but different symbolic information. func (*Frames).Next() (frame Frame, more bool) func*Stack).Next() (_ Frame, more bool) func*Formatter).FormatFrame(frame Frame)
Frames may be used to get function/file/line information for a slice of PC values returned by Callers. Next returns a Frame representing the next call frame in the slice of PC values. If it has already returned all call frames, Next returns a zero Frame. The more result indicates whether the next call to Next will return a valid Frame. It does not necessarily indicate whether this call returned one. See the Frames example for idiomatic usage. func CallersFrames(callers []uintptr) *Frames
A Func represents a Go function in the running binary. Entry returns the entry address of the function. FileLine returns the file name and line number of the source code corresponding to the program counter pc. The result will not be accurate if pc is not a program counter within f. Name returns the name of the function. func FuncForPC(pc uintptr) *Func
A MemProfileRecord describes the live objects allocated by a particular call sequence (stack trace). // number of bytes allocated, freed // number of objects allocated, freed // number of bytes allocated, freed // number of objects allocated, freed // stack trace for this record; ends at first 0 entry InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes). InUseObjects returns the number of objects in use (AllocObjects - FreeObjects). Stack returns the stack trace associated with the record, a prefix of r.Stack0. func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)
A MemStats records statistics about the memory allocator. Alloc is bytes of allocated heap objects. This is the same as HeapAlloc (see below). BuckHashSys is bytes of memory in profiling bucket hash tables. BySize reports per-size class allocation statistics. BySize[N] gives statistics for allocations of size S where BySize[N-1].Size < S ≤ BySize[N].Size. This does not report allocations larger than BySize[60].Size. DebugGC is currently unused. EnableGC indicates that GC is enabled. It is always true, even if GOGC=off. Frees is the cumulative count of heap objects freed. GCCPUFraction is the fraction of this program's available CPU time used by the GC since the program started. GCCPUFraction is expressed as a number between 0 and 1, where 0 means GC has consumed none of this program's CPU. A program's available CPU time is defined as the integral of GOMAXPROCS since the program started. That is, if GOMAXPROCS is 2 and a program has been running for 10 seconds, its "available CPU" is 20 seconds. GCCPUFraction does not include CPU time used for write barrier activity. This is the same as the fraction of CPU reported by GODEBUG=gctrace=1. GCSys is bytes of memory in garbage collection metadata. HeapAlloc is bytes of allocated heap objects. "Allocated" heap objects include all reachable objects, as well as unreachable objects that the garbage collector has not yet freed. Specifically, HeapAlloc increases as heap objects are allocated and decreases as the heap is swept and unreachable objects are freed. Sweeping occurs incrementally between GC cycles, so these two processes occur simultaneously, and as a result HeapAlloc tends to change smoothly (in contrast with the sawtooth that is typical of stop-the-world garbage collectors). HeapIdle is bytes in idle (unused) spans. Idle spans have no objects in them. These spans could be (and may already have been) returned to the OS, or they can be reused for heap allocations, or they can be reused as stack memory. HeapIdle minus HeapReleased estimates the amount of memory that could be returned to the OS, but is being retained by the runtime so it can grow the heap without requesting more memory from the OS. If this difference is significantly larger than the heap size, it indicates there was a recent transient spike in live heap size. HeapInuse is bytes in in-use spans. In-use spans have at least one object in them. These spans can only be used for other objects of roughly the same size. HeapInuse minus HeapAlloc estimates the amount of memory that has been dedicated to particular size classes, but is not currently being used. This is an upper bound on fragmentation, but in general this memory can be reused efficiently. HeapObjects is the number of allocated heap objects. Like HeapAlloc, this increases as objects are allocated and decreases as the heap is swept and unreachable objects are freed. HeapReleased is bytes of physical memory returned to the OS. This counts heap memory from idle spans that was returned to the OS and has not yet been reacquired for the heap. HeapSys is bytes of heap memory obtained from the OS. HeapSys measures the amount of virtual address space reserved for the heap. This includes virtual address space that has been reserved but not yet used, which consumes no physical memory, but tends to be small, as well as virtual address space for which the physical memory has been returned to the OS after it became unused (see HeapReleased for a measure of the latter). HeapSys estimates the largest size the heap has had. LastGC is the time the last garbage collection finished, as nanoseconds since 1970 (the UNIX epoch). Lookups is the number of pointer lookups performed by the runtime. This is primarily useful for debugging runtime internals. MCacheInuse is bytes of allocated mcache structures. MCacheSys is bytes of memory obtained from the OS for mcache structures. MSpanInuse is bytes of allocated mspan structures. MSpanSys is bytes of memory obtained from the OS for mspan structures. Mallocs is the cumulative count of heap objects allocated. The number of live objects is Mallocs - Frees. NextGC is the target heap size of the next GC cycle. The garbage collector's goal is to keep HeapAlloc ≤ NextGC. At the end of each GC cycle, the target for the next cycle is computed based on the amount of reachable data and the value of GOGC. NumForcedGC is the number of GC cycles that were forced by the application calling the GC function. NumGC is the number of completed GC cycles. OtherSys is bytes of memory in miscellaneous off-heap runtime allocations. PauseEnd is a circular buffer of recent GC pause end times, as nanoseconds since 1970 (the UNIX epoch). This buffer is filled the same way as PauseNs. There may be multiple pauses per GC cycle; this records the end of the last pause in a cycle. PauseNs is a circular buffer of recent GC stop-the-world pause times in nanoseconds. The most recent pause is at PauseNs[(NumGC+255)%256]. In general, PauseNs[N%256] records the time paused in the most recent N%256th GC cycle. There may be multiple pauses per GC cycle; this is the sum of all pauses during a cycle. PauseTotalNs is the cumulative nanoseconds in GC stop-the-world pauses since the program started. During a stop-the-world pause, all goroutines are paused and only the garbage collector can run. StackInuse is bytes in stack spans. In-use stack spans have at least one stack in them. These spans can only be used for other stacks of the same size. There is no StackIdle because unused stack spans are returned to the heap (and hence counted toward HeapIdle). StackSys is bytes of stack memory obtained from the OS. StackSys is StackInuse, plus any memory obtained directly from the OS for OS thread stacks. In non-cgo programs this metric is currently equal to StackInuse (but this should not be relied upon, and the value may change in the future). In cgo programs this metric includes OS thread stacks allocated directly from the OS. Currently, this only accounts for one stack in c-shared and c-archive build modes and other sources of stacks from the OS (notably, any allocated by C code) are not currently measured. Note this too may change in the future. Sys is the total bytes of memory obtained from the OS. Sys is the sum of the XSys fields below. Sys measures the virtual address space reserved by the Go runtime for the heap, stacks, and other internal data structures. It's likely that not all of the virtual address space is backed by physical memory at any given moment, though in general it all was at some point. TotalAlloc is cumulative bytes allocated for heap objects. TotalAlloc increases as heap objects are allocated, but unlike Alloc and HeapAlloc, it does not decrease when objects are freed. func ReadMemStats(m *MemStats)
A PanicNilError happens when code calls panic(nil). Before Go 1.21, programs that called panic(nil) observed recover returning nil. Starting in Go 1.21, programs that call panic(nil) observe recover returning a *PanicNilError. Programs can change back to the old behavior by setting GODEBUG=panicnil=1. (*PanicNilError) Error() string (*PanicNilError) RuntimeError() *PanicNilError : Error *PanicNilError : error
A Pinner is a set of pinned Go objects. An object can be pinned with the Pin method and all pinned objects of a Pinner can be unpinned with the Unpin method. Pin pins a Go object, preventing it from being moved or freed by the garbage collector until the Unpin method has been called. A pointer to a pinned object can be directly stored in C memory or can be contained in Go memory passed to C functions. If the pinned object itself contains pointers to Go objects, these objects must be pinned separately if they are going to be accessed from C code. The argument must be a pointer of any type or an unsafe.Pointer. It must be the result of calling new, taking the address of a composite literal, or taking the address of a local variable. If one of these conditions is not met, Pin will panic. Unpin unpins all pinned objects of the Pinner.
A StackRecord describes a single execution stack. // stack trace for this record; ends at first 0 entry Stack returns the stack trace associated with the record, a prefix of r.Stack0. func GoroutineProfile(p []StackRecord) (n int, ok bool) func ThreadCreateProfile(p []StackRecord) (n int, ok bool)
A TypeAssertionError explains a failed type assertion. (*TypeAssertionError) Error() string (*TypeAssertionError) RuntimeError() *TypeAssertionError : Error *TypeAssertionError : error