runtime

package
v1.21.2 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2023 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

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 https://pkg.go.dev/internal/goexperiment 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 https://golang.org/doc/articles/race_detector.html 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 https://golang.org/pkg/runtime/debug/#SetTraceback.

The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see https://golang.org/cmd/go and https://golang.org/pkg/go/build). 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.

Index

Examples

Constants

View Source
const Compiler = "gc"

Compilerは、実行中のバイナリを構築したコンパイラツールチェーンの名前です。既知のツールチェーンは次のとおりです:

gc cmd/compileとしても知られています。 gccgo GCCコンパイラスイートの一部であるgccgoフロントエンドです。

View Source
const GOARCH string = goarch.GOARCH

GOARCH is the running program's architecture target: one of 386, amd64, arm, s390x, and so on.

View Source
const GOOS string = goos.GOOS

GOOS is the running program's operating system target: one of darwin, freebsd, linux, and so on. To view possible combinations of GOOS and GOARCH, run "go tool dist list".

Variables

View Source
var MemProfileRate int = 512 * 1024

MemProfileRateは、メモリプロファイルに記録および報告されるメモリ割り当ての割合を制御します。 プロファイラは、MemProfileRateバイトあたり平均1回の割り当てをサンプリングすることを目指しています。 プロファイルにすべての割り当てブロックを含めるには、MemProfileRateを1に設定します。 プロファイリングを完全にオフにするには、MemProfileRateを0に設定します。 メモリプロファイルを処理するツールは、プロファイルの割合がプログラムの生存期間全体で一定であり、現在の値と等しいと想定しています。 メモリプロファイリングの割合を変更するプログラムは、できるだけ早く(たとえば、mainの開始時などに)1度だけ行う必要があります。

Functions

func BlockProfile added in v1.1.0

func BlockProfile(p []BlockProfileRecord) (n int, ok bool)

BlockProfileは現在のブロッキングプロファイルのレコード数nを返します。 もしlen(p) >= nの場合、BlockProfileはプロファイルをpにコピーし、nとtrueを返します。 もしlen(p) < nの場合、BlockProfileはpを変更せずに、nとfalseを返します。

ほとんどのクライアントは、runtime/pprofパッケージや testingパッケージの-test.blockprofileフラグを使用して、 BlockProfileを直接呼び出す代わりに使用すべきです。

func Breakpoint

func Breakpoint()

ブレークポイントはブレークポイントトラップを実行します。

func CPUProfile

func CPUProfile() []byte

CPUProfileはパニックします。 以前はランタイムによって生成されたpprof形式のプロファイルの チャンクへの直接的なアクセスを提供していました。 その形式を生成する方法が変更されたため、 この機能は削除されました。

非推奨: runtime/pprofパッケージ、 またはnet/http/pprofパッケージのハンドラ、 またはtestingパッケージの-test.cpuprofileフラグを代わりに使用してください。

func Caller

func Caller(skip int) (pc uintptr, file string, line int, ok bool)

Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. (For historical reasons the meaning of skip differs between Caller and Callers.) The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

func Callers

func Callers(skip int, pc []uintptr) int

Callers fills the slice pc with the return program counters of function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to skip before recording in pc, with 0 identifying the frame for Callers itself and 1 identifying the caller of Callers. It returns the number of entries written to pc.

To translate these PCs into symbolic information such as function names and line numbers, use CallersFrames. CallersFrames accounts for inlined functions and adjusts the return program counters into call program counters. Iterating over the returned slice of PCs directly is discouraged, as is using FuncForPC on any of the returned PCs, since these cannot account for inlining or return program counter adjustment.

func GC

func GC()

GC runs a garbage collection and blocks the caller until the garbage collection is complete. It may also block the entire program.

func GOMAXPROCS

func GOMAXPROCS(n int) int

GOMAXPROCSは同時に実行できる最大CPU数を設定し、前の設定を返します。デフォルトはruntime.NumCPUの値です。nが1未満の場合、現在の設定は変更されません。スケジューラの改善が行われると、この呼び出しはなくなります。

func GOROOT

func GOROOT() string

GOROOT returns the root of the Go tree. It uses the GOROOT environment variable, if set at process start, or else the root used during the Go build.

func Goexit

func Goexit()

Goexitはそれを呼び出したゴルーチンを終了します。他のゴルーチンには影響を与えません。 Goexitは終了する前にすべての延期呼び出しを実行します。Goexitはパニックではないため、 これらの延期された関数内のrecover呼び出しはnilを返します。

メインゴルーチンからGoexitを呼び出すと、そのゴルーチンはfunc mainが戻らない状態で終了します。 func mainが戻っていないため、プログラムは他のゴルーチンの実行を継続します。 他のすべてのゴルーチンが終了すると、プログラムはクラッシュします。

func GoroutineProfile

func GoroutineProfile(p []StackRecord) (n int, ok bool)

GoroutineProfileはアクティブなゴルーチンスタックプロファイルのレコード数であるnを返します。 もしlen(p)がn以上であれば、GoroutineProfileはプロファイルをpにコピーしnとtrueを返します。 もしlen(p)がn未満であれば、GoroutineProfileはpを変更せずにnとfalseを返します。

ほとんどのクライアントは直接GoroutineProfileを呼び出す代わりにruntime/pprofパッケージを使用するべきです。

func Gosched

func Gosched()

Gosched はプロセッサを譲り、他のゴルーチンが実行されるようにします。現在のゴルーチンは一時停止されませんが、実行は自動的に再開されます。

func KeepAlive added in v1.7.0

func KeepAlive(x any)

KeepAlive marks its argument as currently reachable. This ensures that the object is not freed, and its finalizer is not run, before the point in the program where KeepAlive is called.

A very simplified example showing where KeepAlive is required:

type File struct { d int }
d, err := syscall.Open("/file/path", syscall.O_RDONLY, 0)
// ... do something if err != nil ...
p := &File{d}
runtime.SetFinalizer(p, func(p *File) { syscall.Close(p.d) })
var buf [10]byte
n, err := syscall.Read(p.d, buf[:])
// Ensure p is not finalized until Read returns.
runtime.KeepAlive(p)
// No more uses of p after this point.

Without the KeepAlive call, the finalizer could run at the start of syscall.Read, closing the file descriptor before syscall.Read makes the actual system call.

Note: KeepAlive should only be used to prevent finalizers from running prematurely. In particular, when used with unsafe.Pointer, the rules for valid uses of unsafe.Pointer still apply.

func LockOSThread

func LockOSThread()

LockOSThreadは呼び出し側のゴルーチンを現在のオペレーティングシステムスレッドに接続します。 呼び出し側のゴルーチンは常にそのスレッドで実行され、他のゴルーチンは実行されません。 それまでのLockOSThreadへの呼び出し回数と同じ数だけ、UnlockOSThreadへの呼び出しを行うまで、呼び出し側のゴルーチン以外は実行されません。 呼び出し側のゴルーチンがスレッドのロックを解除せずに終了すると、スレッドは終了します。

すべてのinit関数は起動時のスレッド上で実行されます。init関数からLockOSThreadを呼び出すと、main関数がそのスレッド上で呼び出されます。

ゴルーチンは、スレッドごとの状態に依存するOSサービスや非Goライブラリ関数を呼び出す前に、LockOSThreadを呼び出す必要があります。

func MemProfile

func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool)

MemProfileは、割り当てられたメモリと解放されたメモリのプロファイルを、割り当ての場所別に返します。 MemProfileは、現在のメモリプロファイルのレコード数であるnを返します。 もしlen(p) >= nであれば、MemProfileはプロファイルをpにコピーし、nとtrueを返します。 もしlen(p) < nであれば、MemProfileはpを変更せずに、nとfalseを返します。 inuseZeroがtrueの場合、プロファイルにはr.AllocBytes > 0 かつ r.AllocBytes == r.FreeBytesのアロケーションレコードが含まれます。 これは、メモリが割り当てられたがランタイムにすべて解放された場所です。 返されるプロファイルは、最大で2つのガベージコレクションサイクル前のものです。 これは、プロファイルがアロケーションに偏った結果にならないようにするためです。 アロケーションはリアルタイムで発生しますが、解放はガベージコレクタがスイーピングを実行するまで遅延されるため、 プロファイルはガベージコレクタによって解放されるチャンスを持ったアロケーションのみをカウントします。 多くのクライアントは、runtime/pprofパッケージまたはtestingパッケージの-test.memprofileフラグを直接呼び出す代わりに使用するべきです。

func MutexProfile added in v1.8.0

func MutexProfile(p []BlockProfileRecord) (n int, ok bool)

MutexProfileは現在のmutexプロファイルのレコード数であるnを返します。 もしlen(p) >= nならば、MutexProfileはプロファイルをpにコピーしてnとtrueを返します。 そうでなければ、MutexProfileはpを変更せずにnとfalseを返します。

ほとんどのクライアントは、MutexProfileを直接呼び出す代わりにruntime/pprofパッケージを使用するべきです。

func NumCPU

func NumCPU() int

NumCPUは現在のプロセスで使用可能な論理CPUの数を返します。

利用可能なCPUのセットはプロセスの起動時にオペレーティングシステムによって確認されます。 プロセスの起動後にオペレーティングシステムのCPU割り当てに変更があっても、それは反映されません。

func NumCgoCall

func NumCgoCall() int64

NumCgoCall は現在のプロセスによって行われた cgo 呼び出しの数を返します。

func NumGoroutine

func NumGoroutine() int

NumGoroutineは現在存在するゴルーチンの数を返します。

func ReadMemStats

func ReadMemStats(m *MemStats)

ReadMemStatsはメモリアロケータ統計情報をmに書き込みます。

返されるメモリアロケータ統計情報はReadMemStatsの呼び出し時点で最新のものです。 これは、ヒーププロファイルとは異なり、最新のガベージコレクションサイクルのスナップショットです。

func ReadTrace added in v1.5.0

func ReadTrace() []byte

ReadTrace はバイナリ追跡データの次のチャンクを返します。データが利用可能になるまでブロックされます。もし追跡がオフになっており、オンの間に蓄積されたデータがすべて返された場合、ReadTrace は nil を返します。呼び出し元は、再度 ReadTrace を呼び出す前に返されたデータをコピーする必要があります。 ReadTrace は一度に1つの goroutine から呼び出す必要があります。

func SetBlockProfileRate added in v1.1.0

func SetBlockProfileRate(rate int)

SetBlockProfileRateは、ブロッキングイベントの割合を制御します。 プロファイラは、ブロックされた時間がrateナノ秒ごとに平均1つのブロッキングイベントをサンプリングすることを目指しています。

プロファイルにすべてのブロッキングイベントを含めるには、rate = 1を渡します。 プロファイリングを完全にオフにするには、rate <= 0を渡します。

func SetCPUProfileRate

func SetCPUProfileRate(hz int)

SetCPUProfileRateはCPUプロファイリングのレートをhzサンプル/秒に設定します。 hz <= 0の場合、プロファイリングはオフになります。 プロファイラがオンの場合、レートを変更する前にオフにする必要があります。

ほとんどのクライアントは、runtime/pprofパッケージまたは テストパッケージの-test.cpuprofileフラグを直接呼び出す代わりに使用するべきです。

func SetCgoTraceback added in v1.7.0

func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer)

SetCgoTraceback records three C functions to use to gather traceback information from C code and to convert that traceback information into symbolic information. These are used when printing stack traces for a program that uses cgo.

The traceback and context functions may be called from a signal handler, and must therefore use only async-signal safe functions. The symbolizer function may be called while the program is crashing, and so must be cautious about using memory. None of the functions may call back into Go.

The context function will be called with a single argument, a pointer to a struct:

struct {
	Context uintptr
}

In C syntax, this struct will be

struct {
	uintptr_t Context;
};

If the Context field is 0, the context function is being called to record the current traceback context. It should record in the Context field whatever information is needed about the current point of execution to later produce a stack trace, probably the stack pointer and PC. In this case the context function will be called from C code.

If the Context field is not 0, then it is a value returned by a previous call to the context function. This case is called when the context is no longer needed; that is, when the Go code is returning to its C code caller. This permits the context function to release any associated resources.

While it would be correct for the context function to record a complete a stack trace whenever it is called, and simply copy that out in the traceback function, in a typical program the context function will be called many times without ever recording a traceback for that context. Recording a complete stack trace in a call to the context function is likely to be inefficient.

The traceback function will be called with a single argument, a pointer to a struct:

struct {
	Context    uintptr
	SigContext uintptr
	Buf        *uintptr
	Max        uintptr
}

In C syntax, this struct will be

struct {
	uintptr_t  Context;
	uintptr_t  SigContext;
	uintptr_t* Buf;
	uintptr_t  Max;
};

The Context field will be zero to gather a traceback from the current program execution point. In this case, the traceback function will be called from C code.

Otherwise Context will be a value previously returned by a call to the context function. The traceback function should gather a stack trace from that saved point in the program execution. The traceback function may be called from an execution thread other than the one that recorded the context, but only when the context is known to be valid and unchanging. The traceback function may also be called deeper in the call stack on the same thread that recorded the context. The traceback function may be called multiple times with the same Context value; it will usually be appropriate to cache the result, if possible, the first time this is called for a specific context value.

If the traceback function is called from a signal handler on a Unix system, SigContext will be the signal context argument passed to the signal handler (a C ucontext_t* cast to uintptr_t). This may be used to start tracing at the point where the signal occurred. If the traceback function is not called from a signal handler, SigContext will be zero.

Buf is where the traceback information should be stored. It should be PC values, such that Buf[0] is the PC of the caller, Buf[1] is the PC of that function's caller, and so on. Max is the maximum number of entries to store. The function should store a zero to indicate the top of the stack, or that the caller is on a different stack, presumably a Go stack.

Unlike runtime.Callers, the PC values returned should, when passed to the symbolizer function, return the file/line of the call instruction. No additional subtraction is required or appropriate.

On all platforms, the traceback function is invoked when a call from Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le, linux/arm64, and freebsd/amd64, the traceback function is also invoked when a signal is received by a thread that is executing a cgo call. The traceback function should not make assumptions about when it is called, as future versions of Go may make additional calls.

The symbolizer function will be called with a single argument, a pointer to a struct:

struct {
	PC      uintptr // program counter to fetch information for
	File    *byte   // file name (NUL terminated)
	Lineno  uintptr // line number
	Func    *byte   // function name (NUL terminated)
	Entry   uintptr // function entry point
	More    uintptr // set non-zero if more info for this PC
	Data    uintptr // unused by runtime, available for function
}

In C syntax, this struct will be

struct {
	uintptr_t PC;
	char*     File;
	uintptr_t Lineno;
	char*     Func;
	uintptr_t Entry;
	uintptr_t More;
	uintptr_t Data;
};

The PC field will be a value returned by a call to the traceback function.

The first time the function is called for a particular traceback, all the fields except PC will be 0. The function should fill in the other fields if possible, setting them to 0/nil if the information is not available. The Data field may be used to store any useful information across calls. The More field should be set to non-zero if there is more information for this PC, zero otherwise. If More is set non-zero, the function will be called again with the same PC, and may return different information (this is intended for use with inlined functions). If More is zero, the function will be called with the next PC value in the traceback. When the traceback is complete, the function will be called once more with PC set to zero; this may be used to free any information. Each call will leave the fields of the struct set to the same values they had upon return, except for the PC field when the More field is zero. The function must not keep a copy of the struct pointer between calls.

When calling SetCgoTraceback, the version argument is the version number of the structs that the functions expect to receive. Currently this must be zero.

The symbolizer function may be nil, in which case the results of the traceback function will be displayed as numbers. If the traceback function is nil, the symbolizer function will never be called. The context function may be nil, in which case the traceback function will only be called with the context field set to zero. If the context function is nil, then calls from Go to C to Go will not show a traceback for the C portion of the call stack.

SetCgoTraceback should be called only once, ideally from an init function.

func SetFinalizer

func SetFinalizer(obj any, finalizer any)

SetFinalizer sets the finalizer associated with obj to the provided finalizer function. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.

SetFinalizer(obj, nil) clears any finalizer associated with obj.

The argument obj must be a pointer to an object allocated by calling new, by taking the address of a composite literal, or by taking the address of a local variable. The argument finalizer must be a function that takes a single argument to which obj's type can be assigned, and can have arbitrary ignored return values. If either of these is not true, SetFinalizer may abort the program.

Finalizers are run in dependency order: if A points at B, both have finalizers, and they are otherwise unreachable, only the finalizer for A runs; once A is freed, the finalizer for B can run. If a cyclic structure includes a block with a finalizer, that cycle is not guaranteed to be garbage collected and the finalizer is not guaranteed to run, because there is no ordering that respects the dependencies.

The finalizer is scheduled to run at some arbitrary time after the program can no longer reach the object to which obj points. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program. For example, an os.File object could use a finalizer to close the associated operating system file descriptor when a program discards an os.File without calling Close, but it would be a mistake to depend on a finalizer to flush an in-memory I/O buffer such as a bufio.Writer, because the buffer would not be flushed at program exit.

It is not guaranteed that a finalizer will run if the size of *obj is zero bytes, because it may share same address with other zero-size objects in memory. See https://go.dev/ref/spec#Size_and_alignment_guarantees.

It is not guaranteed that a finalizer will run for objects allocated in initializers for package-level variables. Such objects may be linker-allocated, not heap-allocated.

Note that because finalizers may execute arbitrarily far into the future after an object is no longer referenced, the runtime is allowed to perform a space-saving optimization that batches objects together in a single allocation slot. The finalizer for an unreferenced object in such an allocation may never run if it always exists in the same batch as a referenced object. Typically, this batching only happens for tiny (on the order of 16 bytes or less) and pointer-free objects.

A finalizer may run as soon as an object becomes unreachable. In order to use finalizers correctly, the program must ensure that the object is reachable until it is no longer required. Objects stored in global variables, or that can be found by tracing pointers from a global variable, are reachable. For other objects, pass the object to a call of the KeepAlive function to mark the last point in the function where the object must be reachable.

For example, if p points to a struct, such as os.File, that contains a file descriptor d, and p has a finalizer that closes that file descriptor, and if the last use of p in a function is a call to syscall.Write(p.d, buf, size), then p may be unreachable as soon as the program enters syscall.Write. The finalizer may run at that moment, closing p.d, causing syscall.Write to fail because it is writing to a closed file descriptor (or, worse, to an entirely different file descriptor opened by a different goroutine). To avoid this problem, call KeepAlive(p) after the call to syscall.Write.

A single goroutine runs all finalizers for a program, sequentially. If a finalizer must run for a long time, it should do so by starting a new goroutine.

In the terminology of the Go memory model, a call SetFinalizer(x, f) “synchronizes before” the finalization call f(x). However, there is no guarantee that KeepAlive(x) or any other use of x “synchronizes before” f(x), so in general a finalizer should use a mutex or other synchronization mechanism if it needs to access mutable state in x. For example, consider a finalizer that inspects a mutable field in x that is modified from time to time in the main program before x becomes unreachable and the finalizer is invoked. The modifications in the main program and the inspection in the finalizer need to use appropriate synchronization, such as mutexes or atomic updates, to avoid read-write races.

func SetMutexProfileFraction added in v1.8.0

func SetMutexProfileFraction(rate int) int

SetMutexProfileFractionは、mutexの衝突イベントのうち、 プロファイルに報告される割合を制御します。平均して1/rateのイベントが報告されます。 以前のrateが返されます。

プロファイリングを完全に無効にするには、rateに0を渡します。 現在のrateだけを読み取るには、rateに0より小さい値を渡します。 (n>1の場合、サンプリングの詳細が変更される場合があります。)

func Stack

func Stack(buf []byte, all bool) int

Stackは呼び出し元のゴルーチンのスタックトレースをbufに書き込み、 bufに書き込まれたバイト数を返します。 allがtrueの場合、現在のゴルーチンのトレースの後に、 他のすべてのゴルーチンのスタックトレースをbufに書き込みます。

func StartTrace added in v1.5.0

func StartTrace() error

StartTraceは現在のプロセスのトレースを有効にします。 トレース中はデータがバッファされ、ReadTraceを介して利用可能です。 トレースが既に有効化されている場合、StartTraceはエラーを返します。 ほとんどのクライアントはruntime/traceパッケージやtestingパッケージの-test.traceフラグを直接呼び出す代わりに使用するべきです。

func StopTrace added in v1.5.0

func StopTrace()

StopTraceは、以前に有効にされていた場合にトレースを停止します。 StopTraceは、トレースのすべての読み取りが完了するまで戻りません。

func ThreadCreateProfile

func ThreadCreateProfile(p []StackRecord) (n int, ok bool)

ThreadCreateProfileはスレッド作成プロファイル内のレコード数であるnを返します。 もし、len(p) >= nならば、ThreadCreateProfileはプロファイルをpにコピーしてn, trueを返します。 もし、len(p) < nならば、ThreadCreateProfileはpを変更せずにn, falseを返します。

大抵のクライアントは直接ThreadCreateProfileを呼び出す代わりに、runtime/pprofパッケージを使用すべきです。

func UnlockOSThread

func UnlockOSThread()

UnlockOSThreadは、以前のLockOSThread呼び出しを取り消します。 呼び出し元のゴルーチンのアクティブなLockOSThread呼び出し数がゼロになると、 呼び出し元のゴルーチンは固定されたオペレーティングシステムスレッドからの接続が解除されます。 アクティブなLockOSThread呼び出しがない場合、これは無効操作です。

UnlockOSThreadを呼び出す前に、呼び出し元は他のゴルーチンを実行するためにOSスレッドが適していることを確認する必要があります。 呼び出し元が他のゴルーチンに影響を与えるスレッドの状態に対して恒久的な変更を行った場合、 この関数を呼び出さずにゴルーチンをOSスレッドにロックしたままにしておくべきです。

func Version

func Version() string

Version returns the Go tree's version string. It is either the commit hash and date at the time of the build or, when possible, a release tag like "go1.3".

Types

type BlockProfileRecord added in v1.1.0

type BlockProfileRecord struct {
	Count  int64
	Cycles int64
	StackRecord
}

BlockProfileRecordは、特定の呼び出しシーケンス(スタックトレース)で発生したブロッキングイベントを記述します。

type Error

type Error interface {
	error

	// 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.
	RuntimeError()
}

Error インターフェースはランタイムエラーを識別します。

type Frame added in v1.7.0

type Frame struct {

	// PCはこのフレームの位置に対するプログラムカウンタです。
	// 別のフレームを呼び出すフレームの場合、これは
	// 呼び出し命令のプログラムカウンタです。インライン展開のため、
	// 複数のフレームは同じPC値を持つことがありますが、異なる
	// シンボリック情報を持ちます。
	PC uintptr

	// Funcはこの呼び出しフレームのFunc値です。これは、非Goコードや完全にインライン化された関数の場合はnilになることがあります。
	Func *Func

	// Functionはこの呼び出しフレームのパッケージパス修飾された関数名です。非空であれば、この文字列はプログラム内の1つの関数を一意に識別します。
	// これは知られていない場合は空の文字列になることがあります。
	// Funcがnilでない場合、Function == Func.Name()です。
	Function string

	// FileとLineは、このフレームのファイル名と行番号です。
	// 非終端フレームの場合、これは呼び出しの位置になります。
	// もし分かっていない場合は、それぞれ空文字列とゼロになります。
	File string
	Line int

	// 関数のエントリーポイントのプログラムカウンター。不明の場合はゼロ。
	// Funcがnilでない場合、Entry == Func.Entry()。
	Entry uintptr
	// contains filtered or unexported fields
}

Frameは各コールフレームごとにFramesによって返される情報です。

type Frames added in v1.7.0

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

Framesを使用すると、Callersが返すPC値のスライスのための関数/ファイル/行情報を取得できます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/runtime"
	"github.com/shogo82148/std/strings"
)

func main() {
	c := func() {
		// runtime.Callersを含めて最大10個のPCを要求します。
		pc := make([]uintptr, 10)
		n := runtime.Callers(0, pc)
		if n == 0 {
			// PC(プログラムカウンタ)が利用できません。これは、runtime.Callersの最初の引数が大きい場合に発生する可能性があります。
			//
			// frames.Next以下で返されるはずのゼロのフレームを処理しないため、ここでリターンします。
			return
		}

		pc = pc[:n] // runtime.CallersFramesには有効なプログラムカウンタ(pcs)のみを渡してください。
		frames := runtime.CallersFrames(pc)

		// フレームを取得するためのループ。
		// 固定数のPCが無限のフレームに拡張できます。
		for {
			frame, more := frames.Next()

			// このフレームを処理します。
			//
			// この例の出力を安定させるために
			// テストパッケージに変更があっても
			// runtimeパッケージを抜けるとアンワインドを停止します。
			if !strings.Contains(frame.File, "runtime/") {
				break
			}
			fmt.Printf("- more:%v | %s\n", more, frame.Function)

			// このフレームの処理後にさらにフレームがあるかどうかを確認します。
			if !more {
				break
			}
		}
	}

	b := func() { c() }
	a := func() { b() }

	a()
}
Output:
- more:true | runtime.Callers
- more:true | runtime_test.ExampleFrames.func1
- more:true | runtime_test.ExampleFrames.func2
- more:true | runtime_test.ExampleFrames.func3
- more:true | runtime_test.ExampleFrames

func CallersFrames added in v1.7.0

func CallersFrames(callers []uintptr) *Frames

CallersFramesはCallersによって返されるPC値のスライスを受け取り、 関数/ファイル/行情報を返す準備をします。 Framesで終わるまでスライスを変更しないでください。

func (*Frames) Next added in v1.7.0

func (ci *Frames) Next() (frame Frame, more bool)

Nextは、PC値のスライス内で次の呼び出しフレームを表すFrameを返します。 すべての呼び出しフレームをすでに返した場合、NextはゼロのFrameを返します。

moreの結果は、次のNext呼び出しで有効なFrameが返されるかどうかを示します。 これが呼び出し元に一つ返されたかどうかを必ずしも示しません。

典型的な使用法については、Framesの例を参照してください。

type Func

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

Funcは実行中のバイナリ内のGo関数を表します。

func FuncForPC

func FuncForPC(pc uintptr) *Func

FuncForPCは、指定されたプログラムカウンターアドレスを含む関数を記述した*Funcを返します。もし複数の関数がインライン展開の影響で存在する場合は、最も内側の関数を示す*Funcを返しますが、最も外側の関数のエントリーも持っています。

func (*Func) Entry

func (f *Func) Entry() uintptr

Entryは関数のエントリーアドレスを返します。

func (*Func) FileLine

func (f *Func) FileLine(pc uintptr) (file string, line int)

FileLineは、プログラムカウンターpcに対応するソースコードのファイル名と行番号を返します。 pcがfのプログラムカウンターでない場合、結果は正確ではありません。

func (*Func) Name

func (f *Func) Name() string

Nameは関数の名前を返します。

type MemProfileRecord

type MemProfileRecord struct {
	AllocBytes, FreeBytes     int64
	AllocObjects, FreeObjects int64
	Stack0                    [32]uintptr
}

MemProfileRecordは、特定の呼び出しシーケンス(スタックトレース)によって割り当てられた生きているオブジェクトを記述します。

func (*MemProfileRecord) InUseBytes

func (r *MemProfileRecord) InUseBytes() int64

InUseBytesは使用中のバイト数(AllocBytes - FreeBytes)を返します。

func (*MemProfileRecord) InUseObjects

func (r *MemProfileRecord) InUseObjects() int64

InUseObjectsは使用中のオブジェクトの数を返します(AllocObjects - FreeObjects)。

func (*MemProfileRecord) Stack

func (r *MemProfileRecord) Stack() []uintptr

Stackは、レコードに関連付けられたスタックトレースを返します。 r.Stack0のプレフィックスです。

type MemStats

type MemStats struct {

	// Allocは割り当てられたヒープオブジェクトのバイト数です。
	//
	// これはHeapAllocと同じです(以下を参照)。
	Alloc uint64

	// TotalAllocはヒープオブジェクトのために割り当てられた累積バイト数です。
	//
	// TotalAllocはヒープオブジェクトが割り当てられると増加しますが、
	// AllocとHeapAllocとは異なり、オブジェクトが解放されると減少しません。
	TotalAlloc uint64

	// SysはOSから取得したメモリの合計バイト数です。
	//
	// Sysは以下のXSysフィールドの合計です。SysはGoランタイムがヒープ、スタック、および他の内部データ構造に予約した仮想アドレススペースを計測します。ある時点では、仮想アドレススペースのすべてが物理メモリでバックアップされているわけではありませんが、一般的にはすべてバックアップされています。
	Sys uint64

	// Lookupsはランタイムによって実行されるポインターの参照の数です。
	//
	// これは主にランタイム内部のデバッグに役立ちます。
	Lookups uint64

	// Mallocsはヒープオブジェクトの割り当て数の累積数です。
	// 生存しているオブジェクトの数はMallocs - Freesです。
	Mallocs uint64

	// Frees はヒープオブジェクトが解放された累積数です。
	Frees uint64

	// HeapAllocは割り当てられたヒープオブジェクトのバイト数です。
	//
	// "割り当てられた"ヒープオブジェクトには、到達可能なオブジェクト全体と、
	// ガベージコレクタがまだ解放していない到達不能なオブジェクトが含まれます。
	// 具体的には、ヒープオブジェクトが割り当てられるとHeapAllocは増加し、
	// ヒープがスイープされて到達不能なオブジェクトが解放されるとHeapAllocは減少します。
	// スイープはGCサイクル間に段階的に行われるため、
	// これらの2つのプロセスは同時に発生し、その結果HeapAllocは滑らかに変化します
	//(ストップ・ザ・ワールドのガベージコレクタの典型的なギザギザとは対照的です)。
	HeapAlloc uint64

	// HeapSysはOSから取得されたヒープメモリのバイト数です。
	//
	// HeapSysは、ヒープのために予約された仮想アドレス空間の量を測定します。
	// これには、まだ使用されていないが予約されている仮想アドレス空間が含まれます。
	// これは物理メモリを消費しませんが、通常は小さくなります。
	// また、使用されなくなった後に物理メモリがOSに返された仮想アドレス空間も含まれます(後者の測定にはHeapReleasedを参照してください)。
	//
	// HeapSysは、ヒープが持っていた最大のサイズを推測します。
	HeapSys uint64

	// HeapIdleはアイドル状態(未使用)のスパンのバイト数です。
	//
	// アイドルスパンにはオブジェクトが含まれていません。これらのスパンは
	// OSに返却されることができます(または既に返却されているかもしれません)し、ヒープの割り当てに再利用されることもあります。
	// また、スタックメモリとして再利用されることもあります。
	//
	// HeapIdleからHeapReleasedを引いた値は、OSに返還できるメモリ量を見積もるものですが、
	// ランタイムによって保持されているため、ヒープの拡張時にOSからの追加メモリ要求なしでヒープを成長させるために利用されています。
	// もし、この差がヒープサイズよりもはるかに大きい場合、最近の一時的なライブヒープサイズの急増を示しています。
	HeapIdle uint64

	// HeapInuseは使用中スパンのバイト数です。
	//
	// 使用中スパンには少なくとも1つのオブジェクトが含まれています。
	// これらのスパンはおおよそ同じサイズの他のオブジェクトにのみ使用できます。
	//
	// HeapInuseからHeapAllocを引いた値は、特定のサイズクラスに割り当てられたメモリの量を推定しますが、現在は使用されていません。
	// これは断片化の上限であり、一般的にこのメモリは効率的に再利用できます。
	HeapInuse uint64

	// HeapReleasedはOSに返される物理メモリのバイト数です。
	//
	// これは、ヒープに再取得される前に、アイドルスパンから返された
	// ヒープメモリをカウントしています。
	HeapReleased uint64

	// HeapObjectsは割り当てられたヒープオブジェクトの数です。
	//
	// HeapAllocと同様に、オブジェクトが割り当てられると増加し、
	// ヒープが掃引され、到達不能なオブジェクトが解放されると減少します。
	HeapObjects uint64

	// StackInuse はスタックスパンのバイト数です。
	//
	// 使用中のスタックスパンには少なくとも1つのスタックがあります。これらのスパンは同じサイズの他のスタックにしか使用できません。
	//
	// StackIdle は存在しません。未使用のスタックスパンはヒープに戻されるため(そのため HeapIdle にカウントされます)。
	StackInuse uint64

	// StackSysはOSから取得したスタックメモリのバイト数です。
	//
	// StackSysはStackInuseに加えて、OSスレッドスタック用に直接
	// OSから取得したメモリです。
	//
	// cgoを使用しないプログラムでは、このメトリックは現在StackInuseと同じです
	// (しかし、これに依存するべきではなく、値は将来変わる可能性があります)。
	//
	// cgoを使用するプログラムでは、OSスレッドスタックも含まれます。
	// 現在、c-sharedおよびc-archiveビルドモードでは1つのスタックのみを考慮し、
	// 他のOSからのスタック(特にCコードによって割り当てられたスタック)は現在計測されていません。
	// これも将来変更される可能性があります。
	StackSys uint64

	// MSpanInuseは割り当てられたmspan構造体のバイト数です。
	MSpanInuse uint64

	// MSpanSysは、mspan構造体のためにOSから取得したメモリのバイトです。
	MSpanSys uint64

	// MCacheInuseは割り当てられたmcache構造体のバイト数です。
	MCacheInuse uint64

	// MCacheSysは、mcache構造体のためにオペレーティングシステムから取得されたバイト数です。
	MCacheSys uint64

	BuckHashSys uint64

	// GCSysはゴミ回収メタデータのメモリのバイト数です。
	GCSys uint64

	// OtherSys は、さまざまなオフヒープランタイム割り当てのメモリのバイト数です。
	OtherSys uint64

	// NextGCは次のGCサイクルのターゲットヒープサイズです。
	//
	// ガベージコレクタの目標は、HeapAlloc ≤ NextGCを維持することです。
	// 各GCサイクルの終了時に、次のサイクルのターゲットは
	// アクセス可能なデータの量とGOGCの値に基づいて計算されます。
	NextGC uint64

	// LastGCは、最後のガベージコレクションが終了した時刻で、
	// 1970年以降のUNIXエポックからの経過時間(ナノ秒単位)です。
	LastGC uint64

	// PauseTotalNsは、プログラムが開始されてからのGCによる累積ナノ秒数です。
	//
	// ストップ・ザ・ワールド・ポーズ中には、すべてのゴルーチンが一時停止され、
	// ガベージコレクタのみが実行されます。
	PauseTotalNs uint64

	// PauseNsは直近のGCのストップ・ザ・ワールドの一時停止時間(ナノ秒)の循環バッファです。
	//
	// 最も直近の一時停止はPauseNs[(NumGC+255)%256]にあります。一般的に、PauseNs[N%256]は直近のN%256番目のGCサイクルでの一時停止時間を記録しています。1つのGCサイクルに複数の一時停止が存在する可能性があります。これはサイクル中のすべての一時停止の合計です。
	PauseNs [256]uint64

	// PauseEndは最近のGCの一時停止終了時間の循環バッファで、1970年以降のナノ秒(UNIXエポック)で表されます。
	//
	// このバッファはPauseNsと同じ方法で埋められます。1つのGCサイクルに複数の一時停止がある場合があります。このバッファはサイクル内の最後の一時停止の終了を記録します。
	PauseEnd [256]uint64

	// NumGCは完了したGCサイクルの数です。
	NumGC uint32

	// NumForcedGC は、アプリケーションがGC関数を呼び出し、強制的に実行されたGCサイクルの回数です。
	NumForcedGC uint32

	// GCCPUFractionは、プログラム開始以来のGCによって使用された利用可能なCPU時間の割合です。
	//
	// GCCPUFractionは0から1の数値で表され、0はこのプログラムのCPUの使用が全くないことを意味します。
	// プログラムの利用可能なCPU時間は、プログラム開始時からのGOMAXPROCSの積分と定義されます。
	// つまり、GOMAXPROCSが2で、プログラムが10秒間実行されている場合、その「利用可能なCPU時間」は20秒です。
	// GCCPUFractionには、書き込みバリアのアクティビティに使用されたCPU時間は含まれません。
	//
	// これは、GODEBUG=gctrace=1によって報告されるCPUの割合と同じです。
	GCCPUFraction float64

	// EnableGCはGCが有効であることを示します。常にtrueですが、
	// GOGC=offの場合でも有効です。
	EnableGC bool

	// DebugGC は現在使用されていません。
	DebugGC bool

	// BySizeは、サイズごとの割り当て統計を報告します。
	//
	// BySize[N]は、サイズSの割り当てに関する統計を提供します。ここで、BySize[N-1].Size < S ≤ BySize[N].Sizeです。
	//
	// これは、BySize[60].Sizeより大きい割り当てを報告しません。
	BySize [61]struct {
		Size uint32

		Mallocs uint64

		Frees uint64
	}
}

MemStatsはメモリアロケータに関する統計情報を記録します。

type PanicNilError added in v1.21.0

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

PanicNilErrorは、コードがpanic(nil)を呼び出したときに発生します。

Go 1.21より前のバージョンでは、panic(nil)を呼び出すプログラムでは、recoverがnilを返すことが観察されました。 Go 1.21以降、panic(nil)を呼び出すプログラムでは、recoverが*PanicNilErrorを返すことが観察されます。 プログラムは、GODEBUG=panicnil=1を設定することで古い動作に戻すことができます。

func (*PanicNilError) Error added in v1.21.0

func (*PanicNilError) Error() string

func (*PanicNilError) RuntimeError added in v1.21.0

func (*PanicNilError) RuntimeError()

type Pinner added in v1.21.0

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

Pinnerは固定されたGoオブジェクトのセットです。オブジェクトはPinメソッドで固定でき、Pinnerのすべての固定されたオブジェクトはUnpinメソッドで固定を解除できます。

func (*Pinner) Pin added in v1.21.0

func (p *Pinner) Pin(pointer any)

PinはGoのオブジェクトをピン留めし、ガベージコレクターによる移動や解放を防止します。 Unpinメソッドが呼び出されるまで、ピン留めされたオブジェクトへのポインタは、 Cメモリに直接格納するか、Goメモリに含めてC関数に渡すことができます。 ピン留めされたオブジェクト自体がGoオブジェクトへのポインタを持っている場合、 Cコードからアクセスするためにはそれらのオブジェクトも別途ピン留めする必要があります。

引数は任意の型のポインタまたはunsafe.Pointerである必要があります。 newの呼び出し結果、複合リテラルのアドレス、またはローカル変数のアドレスを取る必要があります。 上記の条件のいずれかが満たされない場合、Pinはパニックを引き起こします。

func (*Pinner) Unpin added in v1.21.0

func (p *Pinner) Unpin()

UnpinはPinnerのすべてのピン留めされたオブジェクトを解除します。

type StackRecord

type StackRecord struct {
	Stack0 [32]uintptr
}

StackRecordは単一の実行スタックを説明します。

func (*StackRecord) Stack

func (r *StackRecord) Stack() []uintptr

Stackは、レコードに関連付けられたスタックトレースを返します。 これはr.Stack0のプレフィックスです。

type TypeAssertionError

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

TypeAssertionErrorは、型アサーションの失敗を説明します。

func (*TypeAssertionError) Error

func (e *TypeAssertionError) Error() string

func (*TypeAssertionError) RuntimeError

func (*TypeAssertionError) RuntimeError()

Source Files

Directories

Path Synopsis
debug パッケージには、プログラムが実行中に自己デバッグするための機能が含まれています。
debug パッケージには、プログラムが実行中に自己デバッグするための機能が含まれています。
Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime.
Package metrics provides a stable interface to access implementation-defined metrics exported by the Go runtime.
Package pprofは、pprof視覚化ツールで期待される形式でランタイムプロファイリングデータを書き込みます。
Package pprofは、pprof視覚化ツールで期待される形式でランタイムプロファイリングデータを書き込みます。
Package raceはデータ競合検出ロジックを実装しています。
Package raceはデータ競合検出ロジックを実装しています。
Package trace contains facilities for programs to generate traces for the Go execution tracer.
Package trace contains facilities for programs to generate traces for the Go execution tracer.

Jump to

Keyboard shortcuts

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