Movatterモバイル変換


[0]ホーム

URL:


debug

packagestandard library
go1.25.2Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2025 License:BSD-3-ClauseImports:9Imported by:53,932

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package debug contains facilities for programs to debug themselves whilethey are running.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcFreeOSMemoryadded ingo1.1

func FreeOSMemory()

FreeOSMemory forces a garbage collection followed by anattempt to return as much memory to the operating systemas possible. (Even if this is not called, the runtime graduallyreturns memory to the operating system in a background task.)

funcPrintStack

func PrintStack()

PrintStack prints to standard error the stack trace returned by runtime.Stack.

funcReadGCStatsadded ingo1.1

func ReadGCStats(stats *GCStats)

ReadGCStats reads statistics about garbage collection into stats.The number of entries in the pause history is system-dependent;stats.Pause slice will be reused if large enough, reallocated otherwise.ReadGCStats may use the full capacity of the stats.Pause slice.If stats.PauseQuantiles is non-empty, ReadGCStats fills it with quantilessummarizing the distribution of pause time. For example, iflen(stats.PauseQuantiles) is 5, it will be filled with the minimum,25%, 50%, 75%, and maximum pause times.

funcSetCrashOutputadded ingo1.23.0

func SetCrashOutput(f *os.File, optsCrashOptions)error

SetCrashOutput configures a single additional file where unhandledpanics and other fatal errors are printed, in addition to standard error.There is only one additional file: calling SetCrashOutput again overridesany earlier call.SetCrashOutput duplicates f's file descriptor, so the caller may safelyclose f as soon as SetCrashOutput returns.To disable this additional crash output, call SetCrashOutput(nil).If called concurrently with a crash, some in-progress output may be writtento the old file even after an overriding SetCrashOutput returns.

Example (Monitor)

ExampleSetCrashOutput_monitor shows an example of usingdebug.SetCrashOutput to direct crashes to a "monitor" process,for automated crash reporting. The monitor is the same executable,invoked in a special mode indicated by an environment variable.

package mainimport ("io""log""os""os/exec""runtime/debug")// ExampleSetCrashOutput_monitor shows an example of using// [debug.SetCrashOutput] to direct crashes to a "monitor" process,// for automated crash reporting. The monitor is the same executable,// invoked in a special mode indicated by an environment variable.func main() {appmain()// This Example doesn't actually run as a test because its// purpose is to crash, so it has no "Output:" comment// within the function body.//// To observe the monitor in action, replace the entire text// of this comment with "Output:" and run this command:////    $ go test -run=ExampleSetCrashOutput_monitor runtime/debug//    panic: oops//    ...stack...//    monitor: saved crash report at /tmp/10804884239807998216.crash}// appmain represents the 'main' function of your application.func appmain() {monitor()// Run the application.println("hello")panic("oops")}// monitor starts the monitor process, which performs automated// crash reporting. Call this function immediately within main.//// This function re-executes the same executable as a child process,// in a special mode. In that mode, the call to monitor will never// return.func monitor() {const monitorVar = "RUNTIME_DEBUG_MONITOR"if os.Getenv(monitorVar) != "" {// This is the monitor (child) process.log.SetFlags(0)log.SetPrefix("monitor: ")crash, err := io.ReadAll(os.Stdin)if err != nil {log.Fatalf("failed to read from input pipe: %v", err)}if len(crash) == 0 {// Parent process terminated without reporting a crash.os.Exit(0)}// Save the crash report securely in the file system.f, err := os.CreateTemp("", "*.crash")if err != nil {log.Fatal(err)}if _, err := f.Write(crash); err != nil {log.Fatal(err)}if err := f.Close(); err != nil {log.Fatal(err)}log.Fatalf("saved crash report at %s", f.Name())}// This is the application process.// Fork+exec the same executable in monitor mode.exe, err := os.Executable()if err != nil {log.Fatal(err)}cmd := exec.Command(exe, "-test.run=^ExampleSetCrashOutput_monitor$")// Be selective in which variables we allow the child to inherit.// Depending on the application, some may be necessary,// while others (e.g. GOGC, GOMEMLIMIT) may be harmful; see #73490.cmd.Env = []string{monitorVar + "=1"}cmd.Stderr = os.Stderrcmd.Stdout = os.Stderrpipe, err := cmd.StdinPipe()if err != nil {log.Fatalf("StdinPipe: %v", err)}debug.SetCrashOutput(pipe.(*os.File), debug.CrashOptions{}) // (this conversion is safe)if err := cmd.Start(); err != nil {log.Fatalf("can't start monitor: %v", err)}// Now return and start the application proper...}

funcSetGCPercentadded ingo1.1

func SetGCPercent(percentint)int

SetGCPercent sets the garbage collection target percentage:a collection is triggered when the ratio of freshly allocated datato live data remaining after the previous collection reaches this percentage.SetGCPercent returns the previous setting.The initial setting is the value of the GOGC environment variableat startup, or 100 if the variable is not set.This setting may be effectively reduced in order to maintain a memorylimit.A negative percentage effectively disables garbage collection, unlessthe memory limit is reached.See SetMemoryLimit for more details.

funcSetMaxStackadded ingo1.2

func SetMaxStack(bytesint)int

SetMaxStack sets the maximum amount of memory thatcan be used by a single goroutine stack.If any goroutine exceeds this limit while growing its stack,the program crashes.SetMaxStack returns the previous setting.The initial setting is 1 GB on 64-bit systems, 250 MB on 32-bit systems.There may be a system-imposed maximum stack limit regardlessof the value provided to SetMaxStack.

SetMaxStack is useful mainly for limiting the damage done bygoroutines that enter an infinite recursion. It only limits futurestack growth.

funcSetMaxThreadsadded ingo1.2

func SetMaxThreads(threadsint)int

SetMaxThreads sets the maximum number of operating systemthreads that the Go program can use. If it attempts to use more thanthis many, the program crashes.SetMaxThreads returns the previous setting.The initial setting is 10,000 threads.

The limit controls the number of operating system threads, not the numberof goroutines. A Go program creates a new thread only when a goroutineis ready to run but all the existing threads are blocked in system calls, cgo calls,or are locked to other goroutines due to use of runtime.LockOSThread.

SetMaxThreads is useful mainly for limiting the damage done byprograms that create an unbounded number of threads. The idea isto take down the program before it takes down the operating system.

funcSetMemoryLimitadded ingo1.19

func SetMemoryLimit(limitint64)int64

SetMemoryLimit provides the runtime with a soft memory limit.

The runtime undertakes several processes to try to respect thismemory limit, including adjustments to the frequency of garbagecollections and returning memory to the underlying system moreaggressively. This limit will be respected even if GOGC=off (or,if SetGCPercent(-1) is executed).

The input limit is provided as bytes, and includes all memorymapped, managed, and not released by the Go runtime. Notably, itdoes not account for space used by the Go binary and memoryexternal to Go, such as memory managed by the underlying systemon behalf of the process, or memory managed by non-Go code insidethe same process. Examples of excluded memory sources include: OSkernel memory held on behalf of the process, memory allocated byC code, and memory mapped by syscall.Mmap (because it is notmanaged by the Go runtime).

More specifically, the following expression accurately reflectsthe value the runtime attempts to maintain as the limit:

runtime.MemStats.Sys - runtime.MemStats.HeapReleased

or in terms of the runtime/metrics package:

/memory/classes/total:bytes - /memory/classes/heap/released:bytes

A zero limit or a limit that's lower than the amount of memoryused by the Go runtime may cause the garbage collector to runnearly continuously. However, the application may still makeprogress.

The memory limit is always respected by the Go runtime, so toeffectively disable this behavior, set the limit very high.math.MaxInt64 is the canonical value for disabling the limit,but values much greater than the available memory on the underlyingsystem work just as well.

Seehttps://go.dev/doc/gc-guide for a detailed guide explainingthe soft memory limit in more detail, as well as a variety of commonuse-cases and scenarios.

The initial setting is math.MaxInt64 unless the GOMEMLIMITenvironment variable is set, in which case it provides the initialsetting. GOMEMLIMIT is a numeric value in bytes with an optionalunit suffix. The supported suffixes include B, KiB, MiB, GiB, andTiB. These suffixes represent quantities of bytes as defined bythe IEC 80000-13 standard. That is, they are based on powers oftwo: KiB means 2^10 bytes, MiB means 2^20 bytes, and so on.

SetMemoryLimit returns the previously set memory limit.A negative input does not adjust the limit, and allows forretrieval of the currently set memory limit.

funcSetPanicOnFaultadded ingo1.3

func SetPanicOnFault(enabledbool)bool

SetPanicOnFault controls the runtime's behavior when a program faultsat an unexpected (non-nil) address. Such faults are typically caused bybugs such as runtime memory corruption, so the default response is to crashthe program. Programs working with memory-mapped files or unsafemanipulation of memory may cause faults at non-nil addresses in lessdramatic situations; SetPanicOnFault allows such programs to requestthat the runtime trigger only a panic, not a crash.The runtime.Error that the runtime panics with may have an additional method:

Addr() uintptr

If that method exists, it returns the memory address which triggered the fault.The results of Addr are best-effort and the veracity of the resultmay depend on the platform.SetPanicOnFault applies only to the current goroutine.It returns the previous setting.

funcSetTracebackadded ingo1.6

func SetTraceback(levelstring)

SetTraceback sets the amount of detail printed by the runtime inthe traceback it prints before exiting due to an unrecovered panicor an internal runtime error.The level argument takes the same values as the GOTRACEBACKenvironment variable. For example, SetTraceback("all") ensurethat the program prints all goroutines when it crashes.See the package runtime documentation for details.If SetTraceback is called with a level lower than that of theenvironment variable, the call is ignored.

funcStack

func Stack() []byte

Stack returns a formatted stack trace of the goroutine that calls it.It callsruntime.Stack with a large enough buffer to capture the entire trace.

funcWriteHeapDumpadded ingo1.3

func WriteHeapDump(fduintptr)

WriteHeapDump writes a description of the heap and the objects init to the given file descriptor.

WriteHeapDump suspends the execution of all goroutines until the heapdump is completely written. Thus, the file descriptor must not beconnected to a pipe or socket whose other end is in the same Goprocess; instead, use a temporary file or network socket.

The heap dump format is defined athttps://golang.org/s/go15heapdump.

Types

typeBuildInfoadded ingo1.12

type BuildInfo struct {// GoVersion is the version of the Go toolchain that built the binary// (for example, "go1.19.2").GoVersionstring `json:",omitempty"`// Path is the package path of the main package for the binary// (for example, "golang.org/x/tools/cmd/stringer").Pathstring `json:",omitempty"`// Main describes the module that contains the main package for the binary.MainModule `json:""`// Deps describes all the dependency modules, both direct and indirect,// that contributed packages to the build of this binary.Deps []*Module `json:",omitempty"`// Settings describes the build settings used to build the binary.Settings []BuildSetting `json:",omitempty"`}

BuildInfo represents the build information read from a Go binary.

funcParseBuildInfoadded ingo1.18

func ParseBuildInfo(datastring) (bi *BuildInfo, errerror)

ParseBuildInfo parses the string returned by*BuildInfo.String,restoring the original BuildInfo,except that the GoVersion field is not set.Programs should normally not call this function,but instead callReadBuildInfo,debug/buildinfo.ReadFile,ordebug/buildinfo.Read.

funcReadBuildInfoadded ingo1.12

func ReadBuildInfo() (info *BuildInfo, okbool)

ReadBuildInfo returns the build information embeddedin the running binary. The information is available onlyin binaries built with module support.

func (*BuildInfo)Stringadded ingo1.18

func (bi *BuildInfo) String()string

String returns a string representation of aBuildInfo.

typeBuildSettingadded ingo1.18

type BuildSetting struct {// Key and Value describe the build setting.// Key must not contain an equals sign, space, tab, or newline.Keystring `json:",omitempty"`// Value must not contain newlines ('\n').Valuestring `json:",omitempty"`}

A BuildSetting is a key-value pair describing one setting that influenced a build.

Defined keys include:

  • -buildmode: the buildmode flag used (typically "exe")
  • -compiler: the compiler toolchain flag used (typically "gc")
  • CGO_ENABLED: the effective CGO_ENABLED environment variable
  • CGO_CFLAGS: the effective CGO_CFLAGS environment variable
  • CGO_CPPFLAGS: the effective CGO_CPPFLAGS environment variable
  • CGO_CXXFLAGS: the effective CGO_CXXFLAGS environment variable
  • CGO_LDFLAGS: the effective CGO_LDFLAGS environment variable
  • DefaultGODEBUG: the effective GODEBUG settings
  • GOARCH: the architecture target
  • GOAMD64/GOARM/GO386/etc: the architecture feature level for GOARCH
  • GOOS: the operating system target
  • GOFIPS140: the frozen FIPS 140-3 module version, if any
  • vcs: the version control system for the source tree where the build ran
  • vcs.revision: the revision identifier for the current commit or checkout
  • vcs.time: the modification time associated with vcs.revision, in RFC3339 format
  • vcs.modified: true or false indicating whether the source tree had local modifications

typeCrashOptionsadded ingo1.23.0

type CrashOptions struct {}

CrashOptions provides options that control the formatting of thefatal crash message.

typeGCStatsadded ingo1.1

type GCStats struct {LastGCtime.Time// time of last collectionNumGCint64// number of garbage collectionsPauseTotaltime.Duration// total pause for all collectionsPause          []time.Duration// pause history, most recent firstPauseEnd       []time.Time// pause end times history, most recent firstPauseQuantiles []time.Duration}

GCStats collect information about recent garbage collections.

typeModuleadded ingo1.12

type Module struct {Pathstring  `json:",omitempty"`// module pathVersionstring  `json:",omitempty"`// module versionSumstring  `json:",omitempty"`// checksumReplace *Module `json:",omitempty"`// replaced by this module}

A Module describes a single module included in a build.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp