1// Copyright 2013 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
5package debug
6
7import (
8	"runtime"
9	"slices"
10	"time"
11)
12
13// GCStats collect information about recent garbage collections.
14type GCStats struct {
15	LastGC         time.Time       // time of last collection
16	NumGC          int64           // number of garbage collections
17	PauseTotal     time.Duration   // total pause for all collections
18	Pause          []time.Duration // pause history, most recent first
19	PauseEnd       []time.Time     // pause end times history, most recent first
20	PauseQuantiles []time.Duration
21}
22
23// ReadGCStats reads statistics about garbage collection into stats.
24// The number of entries in the pause history is system-dependent;
25// stats.Pause slice will be reused if large enough, reallocated otherwise.
26// ReadGCStats may use the full capacity of the stats.Pause slice.
27// If stats.PauseQuantiles is non-empty, ReadGCStats fills it with quantiles
28// summarizing the distribution of pause time. For example, if
29// len(stats.PauseQuantiles) is 5, it will be filled with the minimum,
30// 25%, 50%, 75%, and maximum pause times.
31func ReadGCStats(stats *GCStats) {
32	// Create a buffer with space for at least two copies of the
33	// pause history tracked by the runtime. One will be returned
34	// to the caller and the other will be used as transfer buffer
35	// for end times history and as a temporary buffer for
36	// computing quantiles.
37	const maxPause = len(((*runtime.MemStats)(nil)).PauseNs)
38	if cap(stats.Pause) < 2*maxPause+3 {
39		stats.Pause = make([]time.Duration, 2*maxPause+3)
40	}
41
42	// readGCStats fills in the pause and end times histories (up to
43	// maxPause entries) and then three more: Unix ns time of last GC,
44	// number of GC, and total pause time in nanoseconds. Here we
45	// depend on the fact that time.Duration's native unit is
46	// nanoseconds, so the pauses and the total pause time do not need
47	// any conversion.
48	readGCStats(&stats.Pause)
49	n := len(stats.Pause) - 3
50	stats.LastGC = time.Unix(0, int64(stats.Pause[n]))
51	stats.NumGC = int64(stats.Pause[n+1])
52	stats.PauseTotal = stats.Pause[n+2]
53	n /= 2 // buffer holds pauses and end times
54	stats.Pause = stats.Pause[:n]
55
56	if cap(stats.PauseEnd) < maxPause {
57		stats.PauseEnd = make([]time.Time, 0, maxPause)
58	}
59	stats.PauseEnd = stats.PauseEnd[:0]
60	for _, ns := range stats.Pause[n : n+n] {
61		stats.PauseEnd = append(stats.PauseEnd, time.Unix(0, int64(ns)))
62	}
63
64	if len(stats.PauseQuantiles) > 0 {
65		if n == 0 {
66			clear(stats.PauseQuantiles)
67		} else {
68			// There's room for a second copy of the data in stats.Pause.
69			// See the allocation at the top of the function.
70			sorted := stats.Pause[n : n+n]
71			copy(sorted, stats.Pause)
72			slices.Sort(sorted)
73			nq := len(stats.PauseQuantiles) - 1
74			for i := 0; i < nq; i++ {
75				stats.PauseQuantiles[i] = sorted[len(sorted)*i/nq]
76			}
77			stats.PauseQuantiles[nq] = sorted[len(sorted)-1]
78		}
79	}
80}
81
82// SetGCPercent sets the garbage collection target percentage:
83// a collection is triggered when the ratio of freshly allocated data
84// to live data remaining after the previous collection reaches this percentage.
85// SetGCPercent returns the previous setting.
86// The initial setting is the value of the GOGC environment variable
87// at startup, or 100 if the variable is not set.
88// This setting may be effectively reduced in order to maintain a memory
89// limit.
90// A negative percentage effectively disables garbage collection, unless
91// the memory limit is reached.
92// See SetMemoryLimit for more details.
93func SetGCPercent(percent int) int {
94	return int(setGCPercent(int32(percent)))
95}
96
97// FreeOSMemory forces a garbage collection followed by an
98// attempt to return as much memory to the operating system
99// as possible. (Even if this is not called, the runtime gradually
100// returns memory to the operating system in a background task.)
101func FreeOSMemory() {
102	freeOSMemory()
103}
104
105// SetMaxStack sets the maximum amount of memory that
106// can be used by a single goroutine stack.
107// If any goroutine exceeds this limit while growing its stack,
108// the program crashes.
109// SetMaxStack returns the previous setting.
110// The initial setting is 1 GB on 64-bit systems, 250 MB on 32-bit systems.
111// There may be a system-imposed maximum stack limit regardless
112// of the value provided to SetMaxStack.
113//
114// SetMaxStack is useful mainly for limiting the damage done by
115// goroutines that enter an infinite recursion. It only limits future
116// stack growth.
117func SetMaxStack(bytes int) int {
118	return setMaxStack(bytes)
119}
120
121// SetMaxThreads sets the maximum number of operating system
122// threads that the Go program can use. If it attempts to use more than
123// this many, the program crashes.
124// SetMaxThreads returns the previous setting.
125// The initial setting is 10,000 threads.
126//
127// The limit controls the number of operating system threads, not the number
128// of goroutines. A Go program creates a new thread only when a goroutine
129// is ready to run but all the existing threads are blocked in system calls, cgo calls,
130// or are locked to other goroutines due to use of runtime.LockOSThread.
131//
132// SetMaxThreads is useful mainly for limiting the damage done by
133// programs that create an unbounded number of threads. The idea is
134// to take down the program before it takes down the operating system.
135func SetMaxThreads(threads int) int {
136	return setMaxThreads(threads)
137}
138
139// SetPanicOnFault controls the runtime's behavior when a program faults
140// at an unexpected (non-nil) address. Such faults are typically caused by
141// bugs such as runtime memory corruption, so the default response is to crash
142// the program. Programs working with memory-mapped files or unsafe
143// manipulation of memory may cause faults at non-nil addresses in less
144// dramatic situations; SetPanicOnFault allows such programs to request
145// that the runtime trigger only a panic, not a crash.
146// The runtime.Error that the runtime panics with may have an additional method:
147//
148//	Addr() uintptr
149//
150// If that method exists, it returns the memory address which triggered the fault.
151// The results of Addr are best-effort and the veracity of the result
152// may depend on the platform.
153// SetPanicOnFault applies only to the current goroutine.
154// It returns the previous setting.
155func SetPanicOnFault(enabled bool) bool {
156	return setPanicOnFault(enabled)
157}
158
159// WriteHeapDump writes a description of the heap and the objects in
160// it to the given file descriptor.
161//
162// WriteHeapDump suspends the execution of all goroutines until the heap
163// dump is completely written.  Thus, the file descriptor must not be
164// connected to a pipe or socket whose other end is in the same Go
165// process; instead, use a temporary file or network socket.
166//
167// The heap dump format is defined at https://golang.org/s/go15heapdump.
168func WriteHeapDump(fd uintptr)
169
170// SetTraceback sets the amount of detail printed by the runtime in
171// the traceback it prints before exiting due to an unrecovered panic
172// or an internal runtime error.
173// The level argument takes the same values as the GOTRACEBACK
174// environment variable. For example, SetTraceback("all") ensure
175// that the program prints all goroutines when it crashes.
176// See the package runtime documentation for details.
177// If SetTraceback is called with a level lower than that of the
178// environment variable, the call is ignored.
179func SetTraceback(level string)
180
181// SetMemoryLimit provides the runtime with a soft memory limit.
182//
183// The runtime undertakes several processes to try to respect this
184// memory limit, including adjustments to the frequency of garbage
185// collections and returning memory to the underlying system more
186// aggressively. This limit will be respected even if GOGC=off (or,
187// if SetGCPercent(-1) is executed).
188//
189// The input limit is provided as bytes, and includes all memory
190// mapped, managed, and not released by the Go runtime. Notably, it
191// does not account for space used by the Go binary and memory
192// external to Go, such as memory managed by the underlying system
193// on behalf of the process, or memory managed by non-Go code inside
194// the same process. Examples of excluded memory sources include: OS
195// kernel memory held on behalf of the process, memory allocated by
196// C code, and memory mapped by syscall.Mmap (because it is not
197// managed by the Go runtime).
198//
199// More specifically, the following expression accurately reflects
200// the value the runtime attempts to maintain as the limit:
201//
202//	runtime.MemStats.Sys - runtime.MemStats.HeapReleased
203//
204// or in terms of the runtime/metrics package:
205//
206//	/memory/classes/total:bytes - /memory/classes/heap/released:bytes
207//
208// A zero limit or a limit that's lower than the amount of memory
209// used by the Go runtime may cause the garbage collector to run
210// nearly continuously. However, the application may still make
211// progress.
212//
213// The memory limit is always respected by the Go runtime, so to
214// effectively disable this behavior, set the limit very high.
215// [math.MaxInt64] is the canonical value for disabling the limit,
216// but values much greater than the available memory on the underlying
217// system work just as well.
218//
219// See https://go.dev/doc/gc-guide for a detailed guide explaining
220// the soft memory limit in more detail, as well as a variety of common
221// use-cases and scenarios.
222//
223// The initial setting is math.MaxInt64 unless the GOMEMLIMIT
224// environment variable is set, in which case it provides the initial
225// setting. GOMEMLIMIT is a numeric value in bytes with an optional
226// unit suffix. The supported suffixes include B, KiB, MiB, GiB, and
227// TiB. These suffixes represent quantities of bytes as defined by
228// the IEC 80000-13 standard. That is, they are based on powers of
229// two: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on.
230//
231// SetMemoryLimit returns the previously set memory limit.
232// A negative input does not adjust the limit, and allows for
233// retrieval of the currently set memory limit.
234func SetMemoryLimit(limit int64) int64 {
235	return setMemoryLimit(limit)
236}
237