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

View as plain text