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