1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5/*
6Package runtime contains operations that interact with Go's runtime system,
7such as functions to control goroutines. It also includes the low-level type information
8used by the reflect package; see [reflect]'s documentation for the programmable
9interface to the run-time type system.
10
11# Environment Variables
12
13The following environment variables ($name or %name%, depending on the host
14operating system) control the run-time behavior of Go programs. The meanings
15and use may change from release to release.
16
17The GOGC variable sets the initial garbage collection target percentage.
18A collection is triggered when the ratio of freshly allocated data to live data
19remaining after the previous collection reaches this percentage. The default
20is GOGC=100. Setting GOGC=off disables the garbage collector entirely.
21[runtime/debug.SetGCPercent] allows changing this percentage at run time.
22
23The GOMEMLIMIT variable sets a soft memory limit for the runtime. This memory limit
24includes the Go heap and all other memory managed by the runtime, and excludes
25external memory sources such as mappings of the binary itself, memory managed in
26other languages, and memory held by the operating system on behalf of the Go
27program. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix.
28The supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes
29represent quantities of bytes as defined by the IEC 80000-13 standard. That is,
30they are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes,
31and so on. The default setting is [math.MaxInt64], which effectively disables the
32memory limit. [runtime/debug.SetMemoryLimit] allows changing this limit at run
33time.
34
35The GODEBUG variable controls debugging variables within the runtime.
36It is a comma-separated list of name=val pairs setting these named variables:
37
38	clobberfree: setting clobberfree=1 causes the garbage collector to
39	clobber the memory content of an object with bad content when it frees
40	the object.
41
42	cpu.*: cpu.all=off disables the use of all optional instruction set extensions.
43	cpu.extension=off disables use of instructions from the specified instruction set extension.
44	extension is the lower case name for the instruction set extension such as sse41 or avx
45	as listed in internal/cpu package. As an example cpu.avx=off disables runtime detection
46	and thereby use of AVX instructions.
47
48	cgocheck: setting cgocheck=0 disables all checks for packages
49	using cgo to incorrectly pass Go pointers to non-Go code.
50	Setting cgocheck=1 (the default) enables relatively cheap
51	checks that may miss some errors. A more complete, but slow,
52	cgocheck mode can be enabled using GOEXPERIMENT (which
53	requires a rebuild), see https://pkg.go.dev/internal/goexperiment for details.
54
55	disablethp: setting disablethp=1 on Linux disables transparent huge pages for the heap.
56	It has no effect on other platforms. disablethp is meant for compatibility with versions
57	of Go before 1.21, which stopped working around a Linux kernel default that can result
58	in significant memory overuse. See https://go.dev/issue/64332. This setting will be
59	removed in a future release, so operators should tweak their Linux configuration to suit
60	their needs before then. See https://go.dev/doc/gc-guide#Linux_transparent_huge_pages.
61
62	dontfreezetheworld: by default, the start of a fatal panic or throw
63	"freezes the world", preempting all threads to stop all running
64	goroutines, which makes it possible to traceback all goroutines, and
65	keeps their state close to the point of panic. Setting
66	dontfreezetheworld=1 disables this preemption, allowing goroutines to
67	continue executing during panic processing. Note that goroutines that
68	naturally enter the scheduler will still stop. This can be useful when
69	debugging the runtime scheduler, as freezetheworld perturbs scheduler
70	state and thus may hide problems.
71
72	efence: setting efence=1 causes the allocator to run in a mode
73	where each object is allocated on a unique page and addresses are
74	never recycled.
75
76	gccheckmark: setting gccheckmark=1 enables verification of the
77	garbage collector's concurrent mark phase by performing a
78	second mark pass while the world is stopped.  If the second
79	pass finds a reachable object that was not found by concurrent
80	mark, the garbage collector will panic.
81
82	gcpacertrace: setting gcpacertrace=1 causes the garbage collector to
83	print information about the internal state of the concurrent pacer.
84
85	gcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines
86	onto smaller stacks. In this mode, a goroutine's stack can only grow.
87
88	gcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,
89	making every garbage collection a stop-the-world event. Setting gcstoptheworld=2
90	also disables concurrent sweeping after the garbage collection finishes.
91
92	gctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard
93	error at each collection, summarizing the amount of memory collected and the
94	length of the pause. The format of this line is subject to change. Included in
95	the explanation below is also the relevant runtime/metrics metric for each field.
96	Currently, it is:
97		gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # MB stacks, #MB globals, # P
98	where the fields are as follows:
99		gc #         the GC number, incremented at each GC
100		@#s          time in seconds since program start
101		#%           percentage of time spent in GC since program start
102		#+...+#      wall-clock/CPU times for the phases of the GC
103		#->#-># MB   heap size at GC start, at GC end, and live heap, or /gc/scan/heap:bytes
104		# MB goal    goal heap size, or /gc/heap/goal:bytes
105		# MB stacks  estimated scannable stack size, or /gc/scan/stack:bytes
106		# MB globals scannable global size, or /gc/scan/globals:bytes
107		# P          number of processors used, or /sched/gomaxprocs:threads
108	The phases are stop-the-world (STW) sweep termination, concurrent
109	mark and scan, and STW mark termination. The CPU times
110	for mark/scan are broken down in to assist time (GC performed in
111	line with allocation), background GC time, and idle GC time.
112	If the line ends with "(forced)", this GC was forced by a
113	runtime.GC() call.
114
115	harddecommit: setting harddecommit=1 causes memory that is returned to the OS to
116	also have protections removed on it. This is the only mode of operation on Windows,
117	but is helpful in debugging scavenger-related issues on other platforms. Currently,
118	only supported on Linux.
119
120	inittrace: setting inittrace=1 causes the runtime to emit a single line to standard
121	error for each package with init work, summarizing the execution time and memory
122	allocation. No information is printed for inits executed as part of plugin loading
123	and for packages without both user defined and compiler generated init work.
124	The format of this line is subject to change. Currently, it is:
125		init # @#ms, # ms clock, # bytes, # allocs
126	where the fields are as follows:
127		init #      the package name
128		@# ms       time in milliseconds when the init started since program start
129		# clock     wall-clock time for package initialization work
130		# bytes     memory allocated on the heap
131		# allocs    number of heap allocations
132
133	madvdontneed: setting madvdontneed=0 will use MADV_FREE
134	instead of MADV_DONTNEED on Linux when returning memory to the
135	kernel. This is more efficient, but means RSS numbers will
136	drop only when the OS is under memory pressure. On the BSDs and
137	Illumos/Solaris, setting madvdontneed=1 will use MADV_DONTNEED instead
138	of MADV_FREE. This is less efficient, but causes RSS numbers to drop
139	more quickly.
140
141	memprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.
142	When set to 0 memory profiling is disabled.  Refer to the description of
143	MemProfileRate for the default value.
144
145	profstackdepth: profstackdepth=128 (the default) will set the maximum stack
146	depth used by all pprof profilers except for the CPU profiler to 128 frames.
147	Stack traces that exceed this limit will be truncated to the limit starting
148	from the leaf frame. Setting profstackdepth to any value above 1024 will
149	silently default to 1024. Future versions of Go may remove this limitation
150	and extend profstackdepth to apply to the CPU profiler and execution tracer.
151
152	pagetrace: setting pagetrace=/path/to/file will write out a trace of page events
153	that can be viewed, analyzed, and visualized using the x/debug/cmd/pagetrace tool.
154	Build your program with GOEXPERIMENT=pagetrace to enable this functionality. Do not
155	enable this functionality if your program is a setuid binary as it introduces a security
156	risk in that scenario. Currently not supported on Windows, plan9 or js/wasm. Setting this
157	option for some applications can produce large traces, so use with care.
158
159	panicnil: setting panicnil=1 disables the runtime error when calling panic with nil
160	interface value or an untyped nil.
161
162	runtimecontentionstacks: setting runtimecontentionstacks=1 enables inclusion of call stacks
163	related to contention on runtime-internal locks in the "mutex" profile, subject to the
164	MutexProfileFraction setting. When runtimecontentionstacks=0, contention on
165	runtime-internal locks will report as "runtime._LostContendedRuntimeLock". When
166	runtimecontentionstacks=1, the call stacks will correspond to the unlock call that released
167	the lock. But instead of the value corresponding to the amount of contention that call
168	stack caused, it corresponds to the amount of time the caller of unlock had to wait in its
169	original call to lock. A future release is expected to align those and remove this setting.
170
171	invalidptr: invalidptr=1 (the default) causes the garbage collector and stack
172	copier to crash the program if an invalid pointer value (for example, 1)
173	is found in a pointer-typed location. Setting invalidptr=0 disables this check.
174	This should only be used as a temporary workaround to diagnose buggy code.
175	The real fix is to not store integers in pointer-typed locations.
176
177	sbrk: setting sbrk=1 replaces the memory allocator and garbage collector
178	with a trivial allocator that obtains memory from the operating system and
179	never reclaims any memory.
180
181	scavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard
182	error, roughly once per GC cycle, summarizing the amount of work done by the
183	scavenger as well as the total amount of memory returned to the operating system
184	and an estimate of physical memory utilization. The format of this line is subject
185	to change, but currently it is:
186		scav # KiB work (bg), # KiB work (eager), # KiB total, #% util
187	where the fields are as follows:
188		# KiB work (bg)    the amount of memory returned to the OS in the background since
189		                   the last line
190		# KiB work (eager) the amount of memory returned to the OS eagerly since the last line
191		# KiB now          the amount of address space currently returned to the OS
192		#% util            the fraction of all unscavenged heap memory which is in-use
193	If the line ends with "(forced)", then scavenging was forced by a
194	debug.FreeOSMemory() call.
195
196	scheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit
197	detailed multiline info every X milliseconds, describing state of the scheduler,
198	processors, threads and goroutines.
199
200	schedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard
201	error every X milliseconds, summarizing the scheduler state.
202
203	tracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at
204	which goroutines were created, where N limits the number of ancestor goroutines to
205	report. This also extends the information returned by runtime.Stack.
206	Setting N to 0 will report no ancestry information.
207
208	tracefpunwindoff: setting tracefpunwindoff=1 forces the execution tracer to
209	use the runtime's default stack unwinder instead of frame pointer unwinding.
210	This increases tracer overhead, but could be helpful as a workaround or for
211	debugging unexpected regressions caused by frame pointer unwinding.
212
213	traceadvanceperiod: the approximate period in nanoseconds between trace generations. Only
214	applies if a program is built with GOEXPERIMENT=exectracer2. Used primarily for testing
215	and debugging the execution tracer.
216
217	tracecheckstackownership: setting tracecheckstackownership=1 enables a debug check in the
218	execution tracer to double-check stack ownership before taking a stack trace.
219
220	asyncpreemptoff: asyncpreemptoff=1 disables signal-based
221	asynchronous goroutine preemption. This makes some loops
222	non-preemptible for long periods, which may delay GC and
223	goroutine scheduling. This is useful for debugging GC issues
224	because it also disables the conservative stack scanning used
225	for asynchronously preempted goroutines.
226
227The [net] and [net/http] packages also refer to debugging variables in GODEBUG.
228See the documentation for those packages for details.
229
230The GOMAXPROCS variable limits the number of operating system threads that
231can execute user-level Go code simultaneously. There is no limit to the number of threads
232that can be blocked in system calls on behalf of Go code; those do not count against
233the GOMAXPROCS limit. This package's [GOMAXPROCS] function queries and changes
234the limit.
235
236The GORACE variable configures the race detector, for programs built using -race.
237See the [Race Detector article] for details.
238
239The GOTRACEBACK variable controls the amount of output generated when a Go
240program fails due to an unrecovered panic or an unexpected runtime condition.
241By default, a failure prints a stack trace for the current goroutine,
242eliding functions internal to the run-time system, and then exits with exit code 2.
243The failure prints stack traces for all goroutines if there is no current goroutine
244or the failure is internal to the run-time.
245GOTRACEBACK=none omits the goroutine stack traces entirely.
246GOTRACEBACK=single (the default) behaves as described above.
247GOTRACEBACK=all adds stack traces for all user-created goroutines.
248GOTRACEBACK=system is like “all” but adds stack frames for run-time functions
249and shows goroutines created internally by the run-time.
250GOTRACEBACK=crash is like “system” but crashes in an operating system-specific
251manner instead of exiting. For example, on Unix systems, the crash raises
252SIGABRT to trigger a core dump.
253GOTRACEBACK=wer is like “crash” but doesn't disable Windows Error Reporting (WER).
254For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for
255none, all, and system, respectively.
256The [runtime/debug.SetTraceback] function allows increasing the
257amount of output at run time, but it cannot reduce the amount below that
258specified by the environment variable.
259
260The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete
261the set of Go environment variables. They influence the building of Go programs
262(see [cmd/go] and [go/build]).
263GOARCH, GOOS, and GOROOT are recorded at compile time and made available by
264constants or functions in this package, but they do not influence the execution
265of the run-time system.
266
267# Security
268
269On Unix platforms, Go's runtime system behaves slightly differently when a
270binary is setuid/setgid or executed with setuid/setgid-like properties, in order
271to prevent dangerous behaviors. On Linux this is determined by checking for the
272AT_SECURE flag in the auxiliary vector, on the BSDs and Solaris/Illumos it is
273determined by checking the issetugid syscall, and on AIX it is determined by
274checking if the uid/gid match the effective uid/gid.
275
276When the runtime determines the binary is setuid/setgid-like, it does three main
277things:
278  - The standard input/output file descriptors (0, 1, 2) are checked to be open.
279    If any of them are closed, they are opened pointing at /dev/null.
280  - The value of the GOTRACEBACK environment variable is set to 'none'.
281  - When a signal is received that terminates the program, or the program
282    encounters an unrecoverable panic that would otherwise override the value
283    of GOTRACEBACK, the goroutine stack, registers, and other memory related
284    information are omitted.
285
286[Race Detector article]: https://go.dev/doc/articles/race_detector
287*/
288package runtime
289
290import (
291	"internal/goarch"
292	"internal/goos"
293)
294
295// Caller reports file and line number information about function invocations on
296// the calling goroutine's stack. The argument skip is the number of stack frames
297// to ascend, with 0 identifying the caller of Caller.  (For historical reasons the
298// meaning of skip differs between Caller and [Callers].) The return values report the
299// program counter, file name, and line number within the file of the corresponding
300// call. The boolean ok is false if it was not possible to recover the information.
301func Caller(skip int) (pc uintptr, file string, line int, ok bool) {
302	rpc := make([]uintptr, 1)
303	n := callers(skip+1, rpc)
304	if n < 1 {
305		return
306	}
307	frame, _ := CallersFrames(rpc).Next()
308	return frame.PC, frame.File, frame.Line, frame.PC != 0
309}
310
311// Callers fills the slice pc with the return program counters of function invocations
312// on the calling goroutine's stack. The argument skip is the number of stack frames
313// to skip before recording in pc, with 0 identifying the frame for Callers itself and
314// 1 identifying the caller of Callers.
315// It returns the number of entries written to pc.
316//
317// To translate these PCs into symbolic information such as function
318// names and line numbers, use [CallersFrames]. CallersFrames accounts
319// for inlined functions and adjusts the return program counters into
320// call program counters. Iterating over the returned slice of PCs
321// directly is discouraged, as is using [FuncForPC] on any of the
322// returned PCs, since these cannot account for inlining or return
323// program counter adjustment.
324func Callers(skip int, pc []uintptr) int {
325	// runtime.callers uses pc.array==nil as a signal
326	// to print a stack trace. Pick off 0-length pc here
327	// so that we don't let a nil pc slice get to it.
328	if len(pc) == 0 {
329		return 0
330	}
331	return callers(skip, pc)
332}
333
334var defaultGOROOT string // set by cmd/link
335
336// GOROOT returns the root of the Go tree. It uses the
337// GOROOT environment variable, if set at process start,
338// or else the root used during the Go build.
339func GOROOT() string {
340	s := gogetenv("GOROOT")
341	if s != "" {
342		return s
343	}
344	return defaultGOROOT
345}
346
347// buildVersion is the Go tree's version string at build time.
348//
349// If any GOEXPERIMENTs are set to non-default values, it will include
350// "X:<GOEXPERIMENT>".
351//
352// This is set by the linker.
353//
354// This is accessed by "go version <binary>".
355var buildVersion string
356
357// Version returns the Go tree's version string.
358// It is either the commit hash and date at the time of the build or,
359// when possible, a release tag like "go1.3".
360func Version() string {
361	return buildVersion
362}
363
364// GOOS is the running program's operating system target:
365// one of darwin, freebsd, linux, and so on.
366// To view possible combinations of GOOS and GOARCH, run "go tool dist list".
367const GOOS string = goos.GOOS
368
369// GOARCH is the running program's architecture target:
370// one of 386, amd64, arm, s390x, and so on.
371const GOARCH string = goarch.GOARCH
372