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

View as plain text