Source file src/runtime/pprof/pprof.go

     1  // Copyright 2010 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  // Package pprof writes runtime profiling data in the format expected
     6  // by the pprof visualization tool.
     7  //
     8  // # Profiling a Go program
     9  //
    10  // The first step to profiling a Go program is to enable profiling.
    11  // Support for profiling benchmarks built with the standard testing
    12  // package is built into go test. For example, the following command
    13  // runs benchmarks in the current directory and writes the CPU and
    14  // memory profiles to cpu.prof and mem.prof:
    15  //
    16  //	go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
    17  //
    18  // To add equivalent profiling support to a standalone program, add
    19  // code like the following to your main function:
    20  //
    21  //	var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
    22  //	var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
    23  //
    24  //	func main() {
    25  //	    flag.Parse()
    26  //	    if *cpuprofile != "" {
    27  //	        f, err := os.Create(*cpuprofile)
    28  //	        if err != nil {
    29  //	            log.Fatal("could not create CPU profile: ", err)
    30  //	        }
    31  //	        defer f.Close() // error handling omitted for example
    32  //	        if err := pprof.StartCPUProfile(f); err != nil {
    33  //	            log.Fatal("could not start CPU profile: ", err)
    34  //	        }
    35  //	        defer pprof.StopCPUProfile()
    36  //	    }
    37  //
    38  //	    // ... rest of the program ...
    39  //
    40  //	    if *memprofile != "" {
    41  //	        f, err := os.Create(*memprofile)
    42  //	        if err != nil {
    43  //	            log.Fatal("could not create memory profile: ", err)
    44  //	        }
    45  //	        defer f.Close() // error handling omitted for example
    46  //	        runtime.GC() // get up-to-date statistics
    47  //	        // Lookup("allocs") creates a profile similar to go test -memprofile.
    48  //	        // Alternatively, use Lookup("heap") for a profile
    49  //	        // that has inuse_space as the default index.
    50  //	        if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
    51  //	            log.Fatal("could not write memory profile: ", err)
    52  //	        }
    53  //	    }
    54  //	}
    55  //
    56  // There is also a standard HTTP interface to profiling data. Adding
    57  // the following line will install handlers under the /debug/pprof/
    58  // URL to download live profiles:
    59  //
    60  //	import _ "net/http/pprof"
    61  //
    62  // See the net/http/pprof package for more details.
    63  //
    64  // Profiles can then be visualized with the pprof tool:
    65  //
    66  //	go tool pprof cpu.prof
    67  //
    68  // There are many commands available from the pprof command line.
    69  // Commonly used commands include "top", which prints a summary of the
    70  // top program hot-spots, and "web", which opens an interactive graph
    71  // of hot-spots and their call graphs. Use "help" for information on
    72  // all pprof commands.
    73  //
    74  // For more information about pprof, see
    75  // https://github.com/google/pprof/blob/main/doc/README.md.
    76  package pprof
    77  
    78  import (
    79  	"bufio"
    80  	"cmp"
    81  	"fmt"
    82  	"internal/abi"
    83  	"internal/profilerecord"
    84  	"io"
    85  	"runtime"
    86  	"slices"
    87  	"sort"
    88  	"strings"
    89  	"sync"
    90  	"text/tabwriter"
    91  	"time"
    92  	"unsafe"
    93  )
    94  
    95  // BUG(rsc): Profiles are only as good as the kernel support used to generate them.
    96  // See https://golang.org/issue/13841 for details about known problems.
    97  
    98  // A Profile is a collection of stack traces showing the call sequences
    99  // that led to instances of a particular event, such as allocation.
   100  // Packages can create and maintain their own profiles; the most common
   101  // use is for tracking resources that must be explicitly closed, such as files
   102  // or network connections.
   103  //
   104  // A Profile's methods can be called from multiple goroutines simultaneously.
   105  //
   106  // Each Profile has a unique name. A few profiles are predefined:
   107  //
   108  //	goroutine      - stack traces of all current goroutines
   109  //	goroutineleak  - stack traces of all leaked goroutines
   110  //	allocs         - a sampling of all past memory allocations
   111  //	heap           - a sampling of memory allocations of live objects
   112  //	memory         - a breakdown of process memory usage at the last completed GC
   113  //	threadcreate   - stack traces that led to the creation of new OS threads
   114  //	block          - stack traces that led to blocking on synchronization primitives
   115  //	mutex          - stack traces of holders of contended mutexes
   116  //
   117  // These predefined profiles maintain themselves and panic on an explicit
   118  // [Profile.Add] or [Profile.Remove] method call.
   119  //
   120  // The CPU profile is not available as a Profile. It has a special API,
   121  // the [StartCPUProfile] and [StopCPUProfile] functions, because it streams
   122  // output to a writer during profiling.
   123  //
   124  // # Heap profile
   125  //
   126  // The heap profile reports statistics as of the most recently completed
   127  // garbage collection; it elides more recent allocation to avoid skewing
   128  // the profile away from live data and toward garbage.
   129  // If there has been no garbage collection at all, the heap profile reports
   130  // all known allocations. This exception helps mainly in programs running
   131  // without garbage collection enabled, usually for debugging purposes.
   132  //
   133  // The heap profile tracks both the allocation sites for all live objects in
   134  // the application memory and for all objects allocated since the program start.
   135  // Pprof's -inuse_space, -inuse_objects, -alloc_space, and -alloc_objects
   136  // flags select which to display, defaulting to -inuse_space (live objects,
   137  // scaled by size).
   138  //
   139  // # Allocs profile
   140  //
   141  // The allocs profile is the same as the heap profile but changes the default
   142  // pprof display to -alloc_space, the total number of bytes allocated since
   143  // the program began (including garbage-collected bytes).
   144  //
   145  // # Memory profile
   146  //
   147  // The memory profile is a superset of the inuse_space heap profile. It breaks
   148  // down the process's resident set size (RSS) into Go and non-Go memory. Go
   149  // memory is further split into the heap, stacks, and runtime metadata, using
   150  // the runtime's memory metrics (see [runtime/metrics]). The heap includes the
   151  // same live object samples as the heap profile, as well as dead objects the
   152  // most recently completed garbage collection found unreachable. Both are
   153  // attributed to the allocation stacks of sampled objects, scaled to match the
   154  // runtime's heap metrics.
   155  //
   156  // Non-Go memory, such as memory allocated by C libraries, is estimated as RSS
   157  // minus Go memory and is only reported where RSS is available (currently
   158  // Linux and Darwin). On Linux, it is further split into file-backed and shared
   159  // memory, and anonymous memory. Prefer this profile to the heap profile.
   160  //
   161  // # Block profile
   162  //
   163  // The block profile tracks time spent blocked on synchronization primitives,
   164  // such as [sync.Mutex], [sync.RWMutex], [sync.WaitGroup], [sync.Cond], and
   165  // channel send/receive/select.
   166  //
   167  // Stack traces correspond to the location that blocked (for example,
   168  // [sync.Mutex.Lock]).
   169  //
   170  // Sample values correspond to cumulative time spent blocked at that stack
   171  // trace, subject to time-based sampling specified by
   172  // [runtime.SetBlockProfileRate].
   173  //
   174  // # Mutex profile
   175  //
   176  // The mutex profile tracks contention on mutexes, such as [sync.Mutex],
   177  // [sync.RWMutex], and runtime-internal locks.
   178  //
   179  // Stack traces correspond to the end of the critical section causing
   180  // contention. For example, a lock held for a long time while other goroutines
   181  // are waiting to acquire the lock will report contention when the lock is
   182  // finally unlocked (that is, at [sync.Mutex.Unlock]).
   183  //
   184  // Sample values correspond to the approximate cumulative time other goroutines
   185  // spent blocked waiting for the lock, subject to event-based sampling
   186  // specified by [runtime.SetMutexProfileFraction]. For example, if a caller
   187  // holds a lock for 1s while 5 other goroutines are waiting for the entire
   188  // second to acquire the lock, its unlock call stack will report 5s of
   189  // contention.
   190  type Profile struct {
   191  	name  string
   192  	mu    sync.Mutex
   193  	m     map[any][]uintptr
   194  	count func() int
   195  	write func(io.Writer, int) error
   196  }
   197  
   198  // profiles records all registered profiles.
   199  var profiles struct {
   200  	mu sync.Mutex
   201  	m  map[string]*Profile
   202  }
   203  
   204  var goroutineProfile = &Profile{
   205  	name:  "goroutine",
   206  	count: countGoroutine,
   207  	write: writeGoroutine,
   208  }
   209  
   210  var goroutineLeakProfile = &Profile{
   211  	name:  "goroutineleak",
   212  	count: runtime_goroutineleakcount,
   213  	write: writeGoroutineLeak,
   214  }
   215  
   216  var threadcreateProfile = &Profile{
   217  	name:  "threadcreate",
   218  	count: countThreadCreate,
   219  	write: writeThreadCreate,
   220  }
   221  
   222  var heapProfile = &Profile{
   223  	name:  "heap",
   224  	count: countHeap,
   225  	write: writeHeap,
   226  }
   227  
   228  var allocsProfile = &Profile{
   229  	name:  "allocs",
   230  	count: countHeap, // identical to heap profile
   231  	write: writeAlloc,
   232  }
   233  
   234  var blockProfile = &Profile{
   235  	name:  "block",
   236  	count: countBlock,
   237  	write: writeBlock,
   238  }
   239  
   240  var mutexProfile = &Profile{
   241  	name:  "mutex",
   242  	count: countMutex,
   243  	write: writeMutex,
   244  }
   245  
   246  // goroutineLeakProfileLock ensures that the goroutine leak profile writer observes the
   247  // leaked goroutines discovered during the goroutine leak detection GC cycle
   248  // that was triggered by the profile request.
   249  // This prevents a race condition between the garbage collector and the profile writer
   250  // when multiple profile requests are issued concurrently: the status of leaked goroutines
   251  // is reset to _Gwaiting at the beginning of a leak detection cycle, which may lead the
   252  // profile writer of another concurrent request to produce an incomplete profile.
   253  //
   254  // Example trace:
   255  //
   256  //	G1                    | GC                          | G2
   257  //	----------------------+-----------------------------+---------------------
   258  //	Request profile       | .                           | .
   259  //	.                     | .                           | Request profile
   260  //	.                     | [G1] Resets leaked g status | .
   261  //	.                     | [G1] Leaks detected         | .
   262  //	.                     | <New cycle>                 | .
   263  //	.                     | [G2] Resets leaked g status | .
   264  //	Write profile         | .                           | .
   265  //	.                     | [G2] Leaks detected         | .
   266  //	.                     | .                           | Write profile
   267  //	----------------------+-----------------------------+---------------------
   268  //	Incomplete profile    |+++++++++++++++++++++++++++++| Complete profile
   269  var goroutineLeakProfileLock sync.Mutex
   270  
   271  func lockProfiles() {
   272  	profiles.mu.Lock()
   273  	if profiles.m == nil {
   274  		// Initial built-in profiles.
   275  		profiles.m = map[string]*Profile{
   276  			"goroutine":     goroutineProfile,
   277  			"threadcreate":  threadcreateProfile,
   278  			"heap":          heapProfile,
   279  			"allocs":        allocsProfile,
   280  			"block":         blockProfile,
   281  			"mutex":         mutexProfile,
   282  			"memory":        memoryProfile,
   283  			"goroutineleak": goroutineLeakProfile,
   284  		}
   285  	}
   286  }
   287  
   288  func unlockProfiles() {
   289  	profiles.mu.Unlock()
   290  }
   291  
   292  // NewProfile creates a new profile with the given name.
   293  // If a profile with that name already exists, NewProfile panics.
   294  // The convention is to use a 'import/path.' prefix to create
   295  // separate name spaces for each package.
   296  // For compatibility with various tools that read pprof data,
   297  // profile names should not contain spaces.
   298  func NewProfile(name string) *Profile {
   299  	lockProfiles()
   300  	defer unlockProfiles()
   301  	if name == "" {
   302  		panic("pprof: NewProfile with empty name")
   303  	}
   304  	if profiles.m[name] != nil {
   305  		panic("pprof: NewProfile name already in use: " + name)
   306  	}
   307  	p := &Profile{
   308  		name: name,
   309  		m:    map[any][]uintptr{},
   310  	}
   311  	profiles.m[name] = p
   312  	return p
   313  }
   314  
   315  // Lookup returns the profile with the given name, or nil if no such profile exists.
   316  func Lookup(name string) *Profile {
   317  	lockProfiles()
   318  	defer unlockProfiles()
   319  	return profiles.m[name]
   320  }
   321  
   322  // Profiles returns a slice of all the known profiles, sorted by name.
   323  func Profiles() []*Profile {
   324  	lockProfiles()
   325  	defer unlockProfiles()
   326  
   327  	all := make([]*Profile, 0, len(profiles.m))
   328  	for _, p := range profiles.m {
   329  
   330  		all = append(all, p)
   331  	}
   332  
   333  	slices.SortFunc(all, func(a, b *Profile) int {
   334  		return strings.Compare(a.name, b.name)
   335  	})
   336  	return all
   337  }
   338  
   339  // Name returns this profile's name, which can be passed to [Lookup] to reobtain the profile.
   340  func (p *Profile) Name() string {
   341  	return p.name
   342  }
   343  
   344  // Count returns the number of execution stacks currently in the profile.
   345  func (p *Profile) Count() int {
   346  	p.mu.Lock()
   347  	defer p.mu.Unlock()
   348  	if p.count != nil {
   349  		return p.count()
   350  	}
   351  	return len(p.m)
   352  }
   353  
   354  // Add adds the current execution stack to the profile, associated with value.
   355  // Add stores value in an internal map, so value must be suitable for use as
   356  // a map key and will not be garbage collected until the corresponding
   357  // call to [Profile.Remove]. Add panics if the profile already contains a stack for value.
   358  //
   359  // The skip parameter has the same meaning as [runtime.Caller]'s skip
   360  // and controls where the stack trace begins. Passing skip=0 begins the
   361  // trace in the function calling Add. For example, given this
   362  // execution stack:
   363  //
   364  //	Add
   365  //	called from rpc.NewClient
   366  //	called from mypkg.Run
   367  //	called from main.main
   368  //
   369  // Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient.
   370  // Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.
   371  func (p *Profile) Add(value any, skip int) {
   372  	if p.name == "" {
   373  		panic("pprof: use of uninitialized Profile")
   374  	}
   375  	if p.write != nil {
   376  		panic("pprof: Add called on built-in Profile " + p.name)
   377  	}
   378  
   379  	stk := make([]uintptr, 32)
   380  	n := runtime.Callers(skip+1, stk[:])
   381  	stk = stk[:n]
   382  	if len(stk) == 0 {
   383  		// The value for skip is too large, and there's no stack trace to record.
   384  		stk = []uintptr{abi.FuncPCABIInternal(lostProfileEvent)}
   385  	}
   386  
   387  	p.mu.Lock()
   388  	defer p.mu.Unlock()
   389  	if p.m[value] != nil {
   390  		panic("pprof: Profile.Add of duplicate value")
   391  	}
   392  	p.m[value] = stk
   393  }
   394  
   395  // Remove removes the execution stack associated with value from the profile.
   396  // It is a no-op if the value is not in the profile.
   397  func (p *Profile) Remove(value any) {
   398  	p.mu.Lock()
   399  	defer p.mu.Unlock()
   400  	delete(p.m, value)
   401  }
   402  
   403  // WriteTo writes a pprof-formatted snapshot of the profile to w.
   404  // If a write to w returns an error, WriteTo returns that error.
   405  // Otherwise, WriteTo returns nil.
   406  //
   407  // The debug parameter enables additional output.
   408  // Passing debug=0 writes the gzip-compressed protocol buffer described
   409  // in https://github.com/google/pprof/tree/main/proto#overview.
   410  // Passing debug=1 writes the legacy text format with comments
   411  // translating addresses to function names and line numbers, so that a
   412  // programmer can read the profile without tools.
   413  //
   414  // The predefined profiles may assign meaning to other debug values;
   415  // for example, when printing the "goroutine" profile, debug=2 means to
   416  // print the goroutine stacks in the same form that a Go program uses
   417  // when dying due to an unrecovered panic.
   418  func (p *Profile) WriteTo(w io.Writer, debug int) error {
   419  	if p.name == "" {
   420  		panic("pprof: use of zero Profile")
   421  	}
   422  	if p.write != nil {
   423  		return p.write(w, debug)
   424  	}
   425  
   426  	// Obtain consistent snapshot under lock; then process without lock.
   427  	p.mu.Lock()
   428  	all := make([][]uintptr, 0, len(p.m))
   429  	for _, stk := range p.m {
   430  		all = append(all, stk)
   431  	}
   432  	p.mu.Unlock()
   433  
   434  	// Map order is non-deterministic; make output deterministic.
   435  	slices.SortFunc(all, slices.Compare)
   436  
   437  	return printCountProfile(w, debug, p.name, stackProfile(all))
   438  }
   439  
   440  type stackProfile [][]uintptr
   441  
   442  func (x stackProfile) Len() int              { return len(x) }
   443  func (x stackProfile) Stack(i int) []uintptr { return x[i] }
   444  func (x stackProfile) Label(i int) *labelMap { return nil }
   445  
   446  // A countProfile is a set of stack traces to be printed as counts
   447  // grouped by stack trace. There are multiple implementations:
   448  // all that matters is that we can find out how many traces there are
   449  // and obtain each trace in turn.
   450  type countProfile interface {
   451  	Len() int
   452  	Stack(i int) []uintptr
   453  	Label(i int) *labelMap
   454  }
   455  
   456  // expandInlinedFrames copies the call stack from pcs into dst, expanding any
   457  // PCs corresponding to inlined calls into the corresponding PCs for the inlined
   458  // functions. Returns the number of frames copied to dst.
   459  func expandInlinedFrames(dst, pcs []uintptr) int {
   460  	cf := runtime.CallersFrames(pcs)
   461  	var n int
   462  	for n < len(dst) {
   463  		f, more := cf.Next()
   464  		// f.PC is a "call PC", but later consumers will expect
   465  		// "return PCs"
   466  		dst[n] = f.PC + 1
   467  		n++
   468  		if !more {
   469  			break
   470  		}
   471  	}
   472  	return n
   473  }
   474  
   475  // printCountCycleProfile outputs block profile records (for block or mutex profiles)
   476  // as the pprof-proto format output. Translations from cycle count to time duration
   477  // are done because The proto expects count and time (nanoseconds) instead of count
   478  // and the number of cycles for block, contention profiles.
   479  func printCountCycleProfile(w io.Writer, countName, cycleName string, records []profilerecord.BlockProfileRecord) error {
   480  	// Output profile in protobuf form.
   481  	b := newProfileBuilder(w)
   482  	b.pbValueType(tagProfile_PeriodType, countName, "count")
   483  	b.pb.int64Opt(tagProfile_Period, 1)
   484  	b.pbValueType(tagProfile_SampleType, countName, "count")
   485  	b.pbValueType(tagProfile_SampleType, cycleName, "nanoseconds")
   486  
   487  	cpuGHz := float64(pprof_cyclesPerSecond()) / 1e9
   488  
   489  	values := []int64{0, 0}
   490  	var locs []uint64
   491  	expandedStack := pprof_makeProfStack()
   492  	for _, r := range records {
   493  		values[0] = r.Count
   494  		values[1] = int64(float64(r.Cycles) / cpuGHz)
   495  		// For count profiles, all stack addresses are
   496  		// return PCs, which is what appendLocsForStack expects.
   497  		n := expandInlinedFrames(expandedStack, r.Stack)
   498  		locs = b.appendLocsForStack(locs[:0], expandedStack[:n])
   499  		b.pbSample(values, locs, nil)
   500  	}
   501  	return b.build()
   502  }
   503  
   504  // printCountProfile prints a countProfile at the specified debug level.
   505  // The profile will be in compressed proto format unless debug is nonzero.
   506  func printCountProfile(w io.Writer, debug int, name string, p countProfile) error {
   507  	// Build count of each stack.
   508  	var buf strings.Builder
   509  	key := func(stk []uintptr, lbls *labelMap) string {
   510  		buf.Reset()
   511  		fmt.Fprintf(&buf, "@")
   512  		for _, pc := range stk {
   513  			fmt.Fprintf(&buf, " %#x", pc)
   514  		}
   515  		if lbls != nil {
   516  			buf.WriteString("\n# labels: ")
   517  			buf.WriteString(lbls.String())
   518  		}
   519  		return buf.String()
   520  	}
   521  	count := map[string]int{}
   522  	index := map[string]int{}
   523  	var keys []string
   524  	n := p.Len()
   525  	for i := 0; i < n; i++ {
   526  		k := key(p.Stack(i), p.Label(i))
   527  		if count[k] == 0 {
   528  			index[k] = i
   529  			keys = append(keys, k)
   530  		}
   531  		count[k]++
   532  	}
   533  
   534  	sort.Sort(&keysByCount{keys, count})
   535  
   536  	if debug > 0 {
   537  		// Print debug profile in legacy format
   538  		tw := tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
   539  		fmt.Fprintf(tw, "%s profile: total %d\n", name, p.Len())
   540  		for _, k := range keys {
   541  			fmt.Fprintf(tw, "%d %s\n", count[k], k)
   542  			printStackRecord(tw, p.Stack(index[k]), false)
   543  		}
   544  		return tw.Flush()
   545  	}
   546  
   547  	// Output profile in protobuf form.
   548  	b := newProfileBuilder(w)
   549  	b.pbValueType(tagProfile_PeriodType, name, "count")
   550  	b.pb.int64Opt(tagProfile_Period, 1)
   551  	b.pbValueType(tagProfile_SampleType, name, "count")
   552  
   553  	values := []int64{0}
   554  	var locs []uint64
   555  	for _, k := range keys {
   556  		values[0] = int64(count[k])
   557  		// For count profiles, all stack addresses are
   558  		// return PCs, which is what appendLocsForStack expects.
   559  		locs = b.appendLocsForStack(locs[:0], p.Stack(index[k]))
   560  		idx := index[k]
   561  		var labels func()
   562  		if p.Label(idx) != nil {
   563  			labels = func() {
   564  				for _, lbl := range p.Label(idx).Set.List {
   565  					b.pbLabel(tagSample_Label, lbl.Key, lbl.Value, 0)
   566  				}
   567  			}
   568  		}
   569  		b.pbSample(values, locs, labels)
   570  	}
   571  	return b.build()
   572  }
   573  
   574  // keysByCount sorts keys with higher counts first, breaking ties by key string order.
   575  type keysByCount struct {
   576  	keys  []string
   577  	count map[string]int
   578  }
   579  
   580  func (x *keysByCount) Len() int      { return len(x.keys) }
   581  func (x *keysByCount) Swap(i, j int) { x.keys[i], x.keys[j] = x.keys[j], x.keys[i] }
   582  func (x *keysByCount) Less(i, j int) bool {
   583  	ki, kj := x.keys[i], x.keys[j]
   584  	ci, cj := x.count[ki], x.count[kj]
   585  	if ci != cj {
   586  		return ci > cj
   587  	}
   588  	return ki < kj
   589  }
   590  
   591  // printStackRecord prints the function + source line information
   592  // for a single stack trace.
   593  func printStackRecord(w io.Writer, stk []uintptr, allFrames bool) {
   594  	show := allFrames
   595  	frames := runtime.CallersFrames(stk)
   596  	for {
   597  		frame, more := frames.Next()
   598  		name := frame.Function
   599  		if name == "" {
   600  			show = true
   601  			fmt.Fprintf(w, "#\t%#x\n", frame.PC)
   602  		} else if name != "runtime.goexit" && (show || !(strings.HasPrefix(name, "runtime.") || strings.HasPrefix(name, "internal/runtime/"))) {
   603  			// Hide runtime.goexit and any runtime functions at the beginning.
   604  			// This is useful mainly for allocation traces.
   605  			show = true
   606  			fmt.Fprintf(w, "#\t%#x\t%s+%#x\t%s:%d\n", frame.PC, name, frame.PC-frame.Entry, frame.File, frame.Line)
   607  		}
   608  		if !more {
   609  			break
   610  		}
   611  	}
   612  	if !show {
   613  		// We didn't print anything; do it again,
   614  		// and this time include runtime functions.
   615  		printStackRecord(w, stk, true)
   616  		return
   617  	}
   618  	fmt.Fprintf(w, "\n")
   619  }
   620  
   621  // Interface to system profiles.
   622  
   623  // WriteHeapProfile is shorthand for [Lookup]("heap").WriteTo(w, 0).
   624  // It is preserved for backwards compatibility.
   625  func WriteHeapProfile(w io.Writer) error {
   626  	return writeHeap(w, 0)
   627  }
   628  
   629  // countHeap returns the number of records in the heap profile.
   630  func countHeap() int {
   631  	n, _ := pprof_memProfileInternal(nil, true, nil)
   632  	return n
   633  }
   634  
   635  // writeHeap writes the current runtime heap profile to w.
   636  func writeHeap(w io.Writer, debug int) error {
   637  	return writeHeapInternal(w, debug, "")
   638  }
   639  
   640  // writeAlloc writes the current runtime heap profile to w
   641  // with the total allocation space as the default sample type.
   642  func writeAlloc(w io.Writer, debug int) error {
   643  	return writeHeapInternal(w, debug, "alloc_space")
   644  }
   645  
   646  func writeHeapInternal(w io.Writer, debug int, defaultSampleType string) error {
   647  	var memStats *runtime.MemStats
   648  	if debug != 0 {
   649  		// Read mem stats first, so that our other allocations
   650  		// do not appear in the statistics.
   651  		memStats = new(runtime.MemStats)
   652  		runtime.ReadMemStats(memStats)
   653  	}
   654  
   655  	// Find out how many records there are (the call
   656  	// pprof_memProfileInternal(nil, true, nil) below),
   657  	// allocate that many records, and get the data.
   658  	// There's a race—more records might be added between
   659  	// the two calls—so allocate a few extra records for safety
   660  	// and also try again if we're very unlucky.
   661  	// The loop should only execute one iteration in the common case.
   662  	var p []profilerecord.MemProfileRecord
   663  	var metrics profilerecord.MemProfileMetrics
   664  	n, ok := pprof_memProfileInternal(nil, true, nil)
   665  	for {
   666  		// Allocate room for a slightly bigger profile,
   667  		// in case a few more entries have been added
   668  		// since the call to MemProfile.
   669  		p = make([]profilerecord.MemProfileRecord, n+50)
   670  		n, ok = pprof_memProfileInternal(p, true, &metrics)
   671  		if ok {
   672  			p = p[0:n]
   673  			break
   674  		}
   675  		// Profile grew; try again.
   676  	}
   677  	_ = metrics // reserved for future use by the memory profile
   678  
   679  	if debug == 0 {
   680  		return writeHeapProto(w, p, int64(runtime.MemProfileRate), defaultSampleType)
   681  	}
   682  
   683  	slices.SortFunc(p, func(a, b profilerecord.MemProfileRecord) int {
   684  		return cmp.Compare(a.InUseBytes(), b.InUseBytes())
   685  	})
   686  
   687  	b := bufio.NewWriter(w)
   688  	tw := tabwriter.NewWriter(b, 1, 8, 1, '\t', 0)
   689  	w = tw
   690  
   691  	var total runtime.MemProfileRecord
   692  	for i := range p {
   693  		r := &p[i]
   694  		total.AllocBytes += r.AllocObjects * r.ObjectSize
   695  		total.AllocObjects += r.AllocObjects
   696  		total.FreeBytes += r.FreeObjects * r.ObjectSize
   697  		total.FreeObjects += r.FreeObjects
   698  	}
   699  
   700  	// Technically the rate is MemProfileRate not 2*MemProfileRate,
   701  	// but early versions of the C++ heap profiler reported 2*MemProfileRate,
   702  	// so that's what pprof has come to expect.
   703  	rate := 2 * runtime.MemProfileRate
   704  
   705  	// pprof reads a profile with alloc == inuse as being a "2-column" profile
   706  	// (objects and bytes, not distinguishing alloc from inuse),
   707  	// but then such a profile can't be merged using pprof *.prof with
   708  	// other 4-column profiles where alloc != inuse.
   709  	// The easiest way to avoid this bug is to adjust allocBytes so it's never == inuseBytes.
   710  	// pprof doesn't use these header values anymore except for checking equality.
   711  	inUseBytes := total.InUseBytes()
   712  	allocBytes := total.AllocBytes
   713  	if inUseBytes == allocBytes {
   714  		allocBytes++
   715  	}
   716  
   717  	fmt.Fprintf(w, "heap profile: %d: %d [%d: %d] @ heap/%d\n",
   718  		total.InUseObjects(), inUseBytes,
   719  		total.AllocObjects, allocBytes,
   720  		rate)
   721  
   722  	for i := range p {
   723  		r := &p[i]
   724  		fmt.Fprintf(w, "%d: %d [%d: %d] @",
   725  			r.InUseObjects(), r.InUseBytes(),
   726  			r.AllocObjects, r.AllocObjects*r.ObjectSize)
   727  		for _, pc := range r.Stack {
   728  			fmt.Fprintf(w, " %#x", pc)
   729  		}
   730  		fmt.Fprintf(w, "\n")
   731  		printStackRecord(w, r.Stack, false)
   732  	}
   733  
   734  	// Print memstats information too.
   735  	// Pprof will ignore, but useful for people
   736  	s := memStats
   737  	fmt.Fprintf(w, "\n# runtime.MemStats\n")
   738  	fmt.Fprintf(w, "# Alloc = %d\n", s.Alloc)
   739  	fmt.Fprintf(w, "# TotalAlloc = %d\n", s.TotalAlloc)
   740  	fmt.Fprintf(w, "# Sys = %d\n", s.Sys)
   741  	fmt.Fprintf(w, "# Lookups = %d\n", s.Lookups)
   742  	fmt.Fprintf(w, "# Mallocs = %d\n", s.Mallocs)
   743  	fmt.Fprintf(w, "# Frees = %d\n", s.Frees)
   744  
   745  	fmt.Fprintf(w, "# HeapAlloc = %d\n", s.HeapAlloc)
   746  	fmt.Fprintf(w, "# HeapSys = %d\n", s.HeapSys)
   747  	fmt.Fprintf(w, "# HeapIdle = %d\n", s.HeapIdle)
   748  	fmt.Fprintf(w, "# HeapInuse = %d\n", s.HeapInuse)
   749  	fmt.Fprintf(w, "# HeapReleased = %d\n", s.HeapReleased)
   750  	fmt.Fprintf(w, "# HeapObjects = %d\n", s.HeapObjects)
   751  
   752  	fmt.Fprintf(w, "# Stack = %d / %d\n", s.StackInuse, s.StackSys)
   753  	fmt.Fprintf(w, "# MSpan = %d / %d\n", s.MSpanInuse, s.MSpanSys)
   754  	fmt.Fprintf(w, "# MCache = %d / %d\n", s.MCacheInuse, s.MCacheSys)
   755  	fmt.Fprintf(w, "# BuckHashSys = %d\n", s.BuckHashSys)
   756  	fmt.Fprintf(w, "# GCSys = %d\n", s.GCSys)
   757  	fmt.Fprintf(w, "# OtherSys = %d\n", s.OtherSys)
   758  
   759  	fmt.Fprintf(w, "# NextGC = %d\n", s.NextGC)
   760  	fmt.Fprintf(w, "# LastGC = %d\n", s.LastGC)
   761  	fmt.Fprintf(w, "# PauseNs = %d\n", s.PauseNs)
   762  	fmt.Fprintf(w, "# PauseEnd = %d\n", s.PauseEnd)
   763  	fmt.Fprintf(w, "# NumGC = %d\n", s.NumGC)
   764  	fmt.Fprintf(w, "# NumForcedGC = %d\n", s.NumForcedGC)
   765  	fmt.Fprintf(w, "# GCCPUFraction = %v\n", s.GCCPUFraction)
   766  	fmt.Fprintf(w, "# DebugGC = %v\n", s.DebugGC)
   767  
   768  	// Also flush out MaxRSS on supported platforms.
   769  	addMaxRSS(w)
   770  
   771  	tw.Flush()
   772  	return b.Flush()
   773  }
   774  
   775  // countThreadCreate returns the size of the current ThreadCreateProfile.
   776  func countThreadCreate() int {
   777  	n, _ := runtime.ThreadCreateProfile(nil)
   778  	return n
   779  }
   780  
   781  // writeThreadCreate writes the current runtime ThreadCreateProfile to w.
   782  func writeThreadCreate(w io.Writer, debug int) error {
   783  	// Until https://golang.org/issues/6104 is addressed, wrap
   784  	// ThreadCreateProfile because there's no point in tracking labels when we
   785  	// don't get any stack-traces.
   786  	return writeRuntimeProfile(w, debug, "threadcreate", func(p []profilerecord.StackRecord, _ []unsafe.Pointer) (n int, ok bool) {
   787  		return pprof_threadCreateInternal(p)
   788  	})
   789  }
   790  
   791  // countGoroutine returns the number of goroutines.
   792  func countGoroutine() int {
   793  	return runtime.NumGoroutine()
   794  }
   795  
   796  // writeGoroutine writes the current runtime GoroutineProfile to w.
   797  func writeGoroutine(w io.Writer, debug int) error {
   798  	if debug >= 2 {
   799  		return writeGoroutineStacks(w)
   800  	}
   801  	return writeRuntimeProfile(w, debug, "goroutine", pprof_goroutineProfileWithLabels)
   802  }
   803  
   804  // writeGoroutineLeak first invokes a GC cycle that performs goroutine leak detection.
   805  // It then writes the goroutine profile, filtering for leaked goroutines.
   806  func writeGoroutineLeak(w io.Writer, debug int) error {
   807  	// Acquire the goroutine leak detection lock and release
   808  	// it after the goroutine leak profile is written.
   809  	//
   810  	// While the critical section is long, this is needed to prevent
   811  	// a race condition between the garbage collector and the goroutine
   812  	// leak profile writer when multiple profile requests are issued concurrently.
   813  	goroutineLeakProfileLock.Lock()
   814  	defer goroutineLeakProfileLock.Unlock()
   815  
   816  	// Run the GC with leak detection first so that leaked goroutines
   817  	// may transition to the leaked state.
   818  	runtime_goroutineLeakGC()
   819  
   820  	// If the debug flag is set sufficiently high, just defer to writing goroutine stacks
   821  	// like in a regular goroutine profile. Include non-leaked goroutines, too.
   822  	if debug >= 2 {
   823  		return writeGoroutineStacks(w)
   824  	}
   825  
   826  	// Otherwise, write the goroutine leak profile.
   827  	return writeRuntimeProfile(w, debug, "goroutineleak", pprof_goroutineLeakProfileWithLabels)
   828  }
   829  
   830  func writeGoroutineStacks(w io.Writer) error {
   831  	// We don't know how big the buffer needs to be to collect
   832  	// all the goroutines. Start with 1 MB and try a few times, doubling each time.
   833  	// Give up and use a truncated trace if 64 MB is not enough.
   834  	buf := make([]byte, 1<<20)
   835  	for i := 0; ; i++ {
   836  		n := runtime.Stack(buf, true)
   837  		if n < len(buf) {
   838  			buf = buf[:n]
   839  			break
   840  		}
   841  		if len(buf) >= 64<<20 {
   842  			// Filled 64 MB - stop there.
   843  			break
   844  		}
   845  		buf = make([]byte, 2*len(buf))
   846  	}
   847  	_, err := w.Write(buf)
   848  	return err
   849  }
   850  
   851  func writeRuntimeProfile(w io.Writer, debug int, name string, fetch func([]profilerecord.StackRecord, []unsafe.Pointer) (int, bool)) error {
   852  	// Find out how many records there are (fetch(nil)),
   853  	// allocate that many records, and get the data.
   854  	// There's a race—more records might be added between
   855  	// the two calls—so allocate a few extra records for safety
   856  	// and also try again if we're very unlucky.
   857  	// The loop should only execute one iteration in the common case.
   858  	var p []profilerecord.StackRecord
   859  	var labels []unsafe.Pointer
   860  	n, ok := fetch(nil, nil)
   861  
   862  	for {
   863  		// Allocate room for a slightly bigger profile,
   864  		// in case a few more entries have been added
   865  		// since the call to ThreadProfile.
   866  		p = make([]profilerecord.StackRecord, n+10)
   867  		labels = make([]unsafe.Pointer, n+10)
   868  		n, ok = fetch(p, labels)
   869  		if ok {
   870  			p = p[0:n]
   871  			break
   872  		}
   873  		// Profile grew; try again.
   874  	}
   875  
   876  	return printCountProfile(w, debug, name, &runtimeProfile{p, labels})
   877  }
   878  
   879  type runtimeProfile struct {
   880  	stk    []profilerecord.StackRecord
   881  	labels []unsafe.Pointer
   882  }
   883  
   884  func (p *runtimeProfile) Len() int              { return len(p.stk) }
   885  func (p *runtimeProfile) Stack(i int) []uintptr { return p.stk[i].Stack }
   886  func (p *runtimeProfile) Label(i int) *labelMap { return (*labelMap)(p.labels[i]) }
   887  
   888  var cpu struct {
   889  	sync.Mutex
   890  	profiling bool
   891  	done      chan bool
   892  }
   893  
   894  // StartCPUProfile enables CPU profiling for the current process.
   895  // While profiling, the profile will be buffered and written to w.
   896  // StartCPUProfile returns an error if profiling is already enabled.
   897  //
   898  // On Unix-like systems, StartCPUProfile does not work by default for
   899  // Go code built with -buildmode=c-archive or -buildmode=c-shared.
   900  // StartCPUProfile relies on the SIGPROF signal, but that signal will
   901  // be delivered to the main program's SIGPROF signal handler (if any)
   902  // not to the one used by Go. To make it work, call [os/signal.Notify]
   903  // for [syscall.SIGPROF], but note that doing so may break any profiling
   904  // being done by the main program.
   905  func StartCPUProfile(w io.Writer) error {
   906  	// The runtime routines allow a variable profiling rate,
   907  	// but in practice operating systems cannot trigger signals
   908  	// at more than about 500 Hz, and our processing of the
   909  	// signal is not cheap (mostly getting the stack trace).
   910  	// 100 Hz is a reasonable choice: it is frequent enough to
   911  	// produce useful data, rare enough not to bog down the
   912  	// system, and a nice round number to make it easy to
   913  	// convert sample counts to seconds. Instead of requiring
   914  	// each client to specify the frequency, we hard code it.
   915  	const hz = 100
   916  
   917  	cpu.Lock()
   918  	defer cpu.Unlock()
   919  	if cpu.done == nil {
   920  		cpu.done = make(chan bool)
   921  	}
   922  	// Double-check.
   923  	if cpu.profiling {
   924  		return fmt.Errorf("cpu profiling already in use")
   925  	}
   926  	cpu.profiling = true
   927  	pprof_setCPUProfileRate(hz)
   928  	go profileWriter(w)
   929  	return nil
   930  }
   931  
   932  // readProfile, provided by the runtime, returns the next chunk of
   933  // binary CPU profiling stack trace data, blocking until data is available.
   934  // If profiling is turned off and all the profile data accumulated while it was
   935  // on has been returned, readProfile returns eof=true.
   936  // The caller must save the returned data and tags before calling readProfile again.
   937  func readProfile() (data []uint64, tags []unsafe.Pointer, eof bool)
   938  
   939  func profileWriter(w io.Writer) {
   940  	b := newProfileBuilder(w)
   941  	var err error
   942  	for {
   943  		if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
   944  			// see runtime_pprof_readProfile
   945  			time.Sleep(100 * time.Millisecond)
   946  		}
   947  		data, tags, eof := readProfile()
   948  		if e := b.addCPUData(data, tags); e != nil && err == nil {
   949  			err = e
   950  		}
   951  		if eof {
   952  			break
   953  		}
   954  	}
   955  	if err != nil {
   956  		// The runtime should never produce an invalid or truncated profile.
   957  		// It drops records that can't fit into its log buffers.
   958  		panic("runtime/pprof: converting profile: " + err.Error())
   959  	}
   960  	b.build()
   961  	cpu.done <- true
   962  }
   963  
   964  // StopCPUProfile stops the current CPU profile, if any.
   965  // StopCPUProfile only returns after all the writes for the
   966  // profile have completed.
   967  func StopCPUProfile() {
   968  	cpu.Lock()
   969  	defer cpu.Unlock()
   970  
   971  	if !cpu.profiling {
   972  		return
   973  	}
   974  	cpu.profiling = false
   975  	pprof_setCPUProfileRate(0)
   976  	<-cpu.done
   977  }
   978  
   979  // countBlock returns the number of records in the blocking profile.
   980  func countBlock() int {
   981  	n, _ := runtime.BlockProfile(nil)
   982  	return n
   983  }
   984  
   985  // countMutex returns the number of records in the mutex profile.
   986  func countMutex() int {
   987  	n, _ := runtime.MutexProfile(nil)
   988  	return n
   989  }
   990  
   991  // writeBlock writes the current blocking profile to w.
   992  func writeBlock(w io.Writer, debug int) error {
   993  	return writeProfileInternal(w, debug, "contention", pprof_blockProfileInternal)
   994  }
   995  
   996  // writeMutex writes the current mutex profile to w.
   997  func writeMutex(w io.Writer, debug int) error {
   998  	return writeProfileInternal(w, debug, "mutex", pprof_mutexProfileInternal)
   999  }
  1000  
  1001  // writeProfileInternal writes the current blocking or mutex profile depending on the passed parameters.
  1002  func writeProfileInternal(w io.Writer, debug int, name string, runtimeProfile func([]profilerecord.BlockProfileRecord) (int, bool)) error {
  1003  	var p []profilerecord.BlockProfileRecord
  1004  	n, ok := runtimeProfile(nil)
  1005  	for {
  1006  		p = make([]profilerecord.BlockProfileRecord, n+50)
  1007  		n, ok = runtimeProfile(p)
  1008  		if ok {
  1009  			p = p[:n]
  1010  			break
  1011  		}
  1012  	}
  1013  
  1014  	slices.SortFunc(p, func(a, b profilerecord.BlockProfileRecord) int {
  1015  		return cmp.Compare(b.Cycles, a.Cycles)
  1016  	})
  1017  
  1018  	if debug <= 0 {
  1019  		return printCountCycleProfile(w, "contentions", "delay", p)
  1020  	}
  1021  
  1022  	b := bufio.NewWriter(w)
  1023  	tw := tabwriter.NewWriter(b, 1, 8, 1, '\t', 0)
  1024  	w = tw
  1025  
  1026  	fmt.Fprintf(w, "--- %v:\n", name)
  1027  	fmt.Fprintf(w, "cycles/second=%v\n", pprof_cyclesPerSecond())
  1028  	if name == "mutex" {
  1029  		fmt.Fprintf(w, "sampling period=%d\n", runtime.SetMutexProfileFraction(-1))
  1030  	}
  1031  	expandedStack := pprof_makeProfStack()
  1032  	for i := range p {
  1033  		r := &p[i]
  1034  		fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count)
  1035  		n := expandInlinedFrames(expandedStack, r.Stack)
  1036  		stack := expandedStack[:n]
  1037  		for _, pc := range stack {
  1038  			fmt.Fprintf(w, " %#x", pc)
  1039  		}
  1040  		fmt.Fprint(w, "\n")
  1041  		if debug > 0 {
  1042  			printStackRecord(w, stack, true)
  1043  		}
  1044  	}
  1045  
  1046  	if tw != nil {
  1047  		tw.Flush()
  1048  	}
  1049  	return b.Flush()
  1050  }
  1051  
  1052  //go:linkname pprof_goroutineProfileWithLabels runtime.pprof_goroutineProfileWithLabels
  1053  func pprof_goroutineProfileWithLabels(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool)
  1054  
  1055  //go:linkname pprof_goroutineLeakProfileWithLabels runtime.pprof_goroutineLeakProfileWithLabels
  1056  func pprof_goroutineLeakProfileWithLabels(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool)
  1057  
  1058  //go:linkname pprof_cyclesPerSecond runtime/pprof.runtime_cyclesPerSecond
  1059  func pprof_cyclesPerSecond() int64
  1060  
  1061  //go:linknamestd pprof_memProfileInternal
  1062  func pprof_memProfileInternal(p []profilerecord.MemProfileRecord, inuseZero bool, metrics *profilerecord.MemProfileMetrics) (n int, ok bool)
  1063  
  1064  //go:linknamestd pprof_memoryProfileEnabled
  1065  func pprof_memoryProfileEnabled() bool
  1066  
  1067  //go:linkname pprof_blockProfileInternal runtime.pprof_blockProfileInternal
  1068  func pprof_blockProfileInternal(p []profilerecord.BlockProfileRecord) (n int, ok bool)
  1069  
  1070  //go:linkname pprof_mutexProfileInternal runtime.pprof_mutexProfileInternal
  1071  func pprof_mutexProfileInternal(p []profilerecord.BlockProfileRecord) (n int, ok bool)
  1072  
  1073  //go:linkname pprof_threadCreateInternal runtime.pprof_threadCreateInternal
  1074  func pprof_threadCreateInternal(p []profilerecord.StackRecord) (n int, ok bool)
  1075  
  1076  //go:linkname pprof_fpunwindExpand runtime.pprof_fpunwindExpand
  1077  func pprof_fpunwindExpand(dst, src []uintptr) int
  1078  
  1079  //go:linkname pprof_makeProfStack runtime.pprof_makeProfStack
  1080  func pprof_makeProfStack() []uintptr
  1081  
  1082  //go:linkname pprof_setCPUProfileRate runtime.pprof_setCPUProfileRate
  1083  func pprof_setCPUProfileRate(hz int)
  1084  

View as plain text