github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/runtime/pprof/pprof.go (about)

     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 `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  //            if err := pprof.StartCPUProfile(f); err != nil {
    32  //                log.Fatal("could not start CPU profile: ", err)
    33  //            }
    34  //            defer pprof.StopCPUProfile()
    35  //        }
    36  //
    37  //        // ... rest of the program ...
    38  //
    39  //        if *memprofile != "" {
    40  //            f, err := os.Create(*memprofile)
    41  //            if err != nil {
    42  //                log.Fatal("could not create memory profile: ", err)
    43  //            }
    44  //            runtime.GC() // get up-to-date statistics
    45  //            if err := pprof.WriteHeapProfile(f); err != nil {
    46  //                log.Fatal("could not write memory profile: ", err)
    47  //            }
    48  //            f.Close()
    49  //        }
    50  //    }
    51  //
    52  // There is also a standard HTTP interface to profiling data. Adding
    53  // the following line will install handlers under the /debug/pprof/
    54  // URL to download live profiles:
    55  //
    56  //    import _ "net/http/pprof"
    57  //
    58  // See the net/http/pprof package for more details.
    59  //
    60  // Profiles can then be visualized with the pprof tool:
    61  //
    62  //    go tool pprof cpu.prof
    63  //
    64  // There are many commands available from the pprof command line.
    65  // Commonly used commands include "top", which prints a summary of the
    66  // top program hot-spots, and "web", which opens an interactive graph
    67  // of hot-spots and their call graphs. Use "help" for information on
    68  // all pprof commands.
    69  //
    70  // For more information about pprof, see
    71  // https://github.com/google/pprof/blob/master/doc/pprof.md.
    72  package pprof
    73  
    74  import (
    75  	"bufio"
    76  	"bytes"
    77  	"fmt"
    78  	"io"
    79  	"runtime"
    80  	"sort"
    81  	"strings"
    82  	"sync"
    83  	"text/tabwriter"
    84  	"time"
    85  	"unsafe"
    86  )
    87  
    88  // BUG(rsc): Profiles are only as good as the kernel support used to generate them.
    89  // See https://golang.org/issue/13841 for details about known problems.
    90  
    91  // A Profile is a collection of stack traces showing the call sequences
    92  // that led to instances of a particular event, such as allocation.
    93  // Packages can create and maintain their own profiles; the most common
    94  // use is for tracking resources that must be explicitly closed, such as files
    95  // or network connections.
    96  //
    97  // A Profile's methods can be called from multiple goroutines simultaneously.
    98  //
    99  // Each Profile has a unique name. A few profiles are predefined:
   100  //
   101  //	goroutine    - stack traces of all current goroutines
   102  //	heap         - a sampling of all heap allocations
   103  //	threadcreate - stack traces that led to the creation of new OS threads
   104  //	block        - stack traces that led to blocking on synchronization primitives
   105  //	mutex        - stack traces of holders of contended mutexes
   106  //
   107  // These predefined profiles maintain themselves and panic on an explicit
   108  // Add or Remove method call.
   109  //
   110  // The heap profile reports statistics as of the most recently completed
   111  // garbage collection; it elides more recent allocation to avoid skewing
   112  // the profile away from live data and toward garbage.
   113  // If there has been no garbage collection at all, the heap profile reports
   114  // all known allocations. This exception helps mainly in programs running
   115  // without garbage collection enabled, usually for debugging purposes.
   116  //
   117  // The CPU profile is not available as a Profile. It has a special API,
   118  // the StartCPUProfile and StopCPUProfile functions, because it streams
   119  // output to a writer during profiling.
   120  //
   121  type Profile struct {
   122  	name  string
   123  	mu    sync.Mutex
   124  	m     map[interface{}][]uintptr
   125  	count func() int
   126  	write func(io.Writer, int) error
   127  }
   128  
   129  // profiles records all registered profiles.
   130  var profiles struct {
   131  	mu sync.Mutex
   132  	m  map[string]*Profile
   133  }
   134  
   135  var goroutineProfile = &Profile{
   136  	name:  "goroutine",
   137  	count: countGoroutine,
   138  	write: writeGoroutine,
   139  }
   140  
   141  var threadcreateProfile = &Profile{
   142  	name:  "threadcreate",
   143  	count: countThreadCreate,
   144  	write: writeThreadCreate,
   145  }
   146  
   147  var heapProfile = &Profile{
   148  	name:  "heap",
   149  	count: countHeap,
   150  	write: writeHeap,
   151  }
   152  
   153  var blockProfile = &Profile{
   154  	name:  "block",
   155  	count: countBlock,
   156  	write: writeBlock,
   157  }
   158  
   159  var mutexProfile = &Profile{
   160  	name:  "mutex",
   161  	count: countMutex,
   162  	write: writeMutex,
   163  }
   164  
   165  func lockProfiles() {
   166  	profiles.mu.Lock()
   167  	if profiles.m == nil {
   168  		// Initial built-in profiles.
   169  		profiles.m = map[string]*Profile{
   170  			"goroutine":    goroutineProfile,
   171  			"threadcreate": threadcreateProfile,
   172  			"heap":         heapProfile,
   173  			"block":        blockProfile,
   174  			"mutex":        mutexProfile,
   175  		}
   176  	}
   177  }
   178  
   179  func unlockProfiles() {
   180  	profiles.mu.Unlock()
   181  }
   182  
   183  // NewProfile creates a new profile with the given name.
   184  // If a profile with that name already exists, NewProfile panics.
   185  // The convention is to use a 'import/path.' prefix to create
   186  // separate name spaces for each package.
   187  // For compatibility with various tools that read pprof data,
   188  // profile names should not contain spaces.
   189  func NewProfile(name string) *Profile {
   190  	lockProfiles()
   191  	defer unlockProfiles()
   192  	if name == "" {
   193  		panic("pprof: NewProfile with empty name")
   194  	}
   195  	if profiles.m[name] != nil {
   196  		panic("pprof: NewProfile name already in use: " + name)
   197  	}
   198  	p := &Profile{
   199  		name: name,
   200  		m:    map[interface{}][]uintptr{},
   201  	}
   202  	profiles.m[name] = p
   203  	return p
   204  }
   205  
   206  // Lookup returns the profile with the given name, or nil if no such profile exists.
   207  func Lookup(name string) *Profile {
   208  	lockProfiles()
   209  	defer unlockProfiles()
   210  	return profiles.m[name]
   211  }
   212  
   213  // Profiles returns a slice of all the known profiles, sorted by name.
   214  func Profiles() []*Profile {
   215  	lockProfiles()
   216  	defer unlockProfiles()
   217  
   218  	all := make([]*Profile, 0, len(profiles.m))
   219  	for _, p := range profiles.m {
   220  		all = append(all, p)
   221  	}
   222  
   223  	sort.Slice(all, func(i, j int) bool { return all[i].name < all[j].name })
   224  	return all
   225  }
   226  
   227  // Name returns this profile's name, which can be passed to Lookup to reobtain the profile.
   228  func (p *Profile) Name() string {
   229  	return p.name
   230  }
   231  
   232  // Count returns the number of execution stacks currently in the profile.
   233  func (p *Profile) Count() int {
   234  	p.mu.Lock()
   235  	defer p.mu.Unlock()
   236  	if p.count != nil {
   237  		return p.count()
   238  	}
   239  	return len(p.m)
   240  }
   241  
   242  // Add adds the current execution stack to the profile, associated with value.
   243  // Add stores value in an internal map, so value must be suitable for use as
   244  // a map key and will not be garbage collected until the corresponding
   245  // call to Remove. Add panics if the profile already contains a stack for value.
   246  //
   247  // The skip parameter has the same meaning as runtime.Caller's skip
   248  // and controls where the stack trace begins. Passing skip=0 begins the
   249  // trace in the function calling Add. For example, given this
   250  // execution stack:
   251  //
   252  //	Add
   253  //	called from rpc.NewClient
   254  //	called from mypkg.Run
   255  //	called from main.main
   256  //
   257  // Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient.
   258  // Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.
   259  //
   260  func (p *Profile) Add(value interface{}, skip int) {
   261  	if p.name == "" {
   262  		panic("pprof: use of uninitialized Profile")
   263  	}
   264  	if p.write != nil {
   265  		panic("pprof: Add called on built-in Profile " + p.name)
   266  	}
   267  
   268  	stk := make([]uintptr, 32)
   269  	n := runtime.Callers(skip+1, stk[:])
   270  	stk = stk[:n]
   271  	if len(stk) == 0 {
   272  		// The value for skip is too large, and there's no stack trace to record.
   273  		stk = []uintptr{funcPC(lostProfileEvent)}
   274  	}
   275  
   276  	p.mu.Lock()
   277  	defer p.mu.Unlock()
   278  	if p.m[value] != nil {
   279  		panic("pprof: Profile.Add of duplicate value")
   280  	}
   281  	p.m[value] = stk
   282  }
   283  
   284  // Remove removes the execution stack associated with value from the profile.
   285  // It is a no-op if the value is not in the profile.
   286  func (p *Profile) Remove(value interface{}) {
   287  	p.mu.Lock()
   288  	defer p.mu.Unlock()
   289  	delete(p.m, value)
   290  }
   291  
   292  // WriteTo writes a pprof-formatted snapshot of the profile to w.
   293  // If a write to w returns an error, WriteTo returns that error.
   294  // Otherwise, WriteTo returns nil.
   295  //
   296  // The debug parameter enables additional output.
   297  // Passing debug=0 prints only the hexadecimal addresses that pprof needs.
   298  // Passing debug=1 adds comments translating addresses to function names
   299  // and line numbers, so that a programmer can read the profile without tools.
   300  //
   301  // The predefined profiles may assign meaning to other debug values;
   302  // for example, when printing the "goroutine" profile, debug=2 means to
   303  // print the goroutine stacks in the same form that a Go program uses
   304  // when dying due to an unrecovered panic.
   305  func (p *Profile) WriteTo(w io.Writer, debug int) error {
   306  	if p.name == "" {
   307  		panic("pprof: use of zero Profile")
   308  	}
   309  	if p.write != nil {
   310  		return p.write(w, debug)
   311  	}
   312  
   313  	// Obtain consistent snapshot under lock; then process without lock.
   314  	p.mu.Lock()
   315  	all := make([][]uintptr, 0, len(p.m))
   316  	for _, stk := range p.m {
   317  		all = append(all, stk)
   318  	}
   319  	p.mu.Unlock()
   320  
   321  	// Map order is non-deterministic; make output deterministic.
   322  	sort.Slice(all, func(i, j int) bool {
   323  		t, u := all[i], all[j]
   324  		for k := 0; k < len(t) && k < len(u); k++ {
   325  			if t[k] != u[k] {
   326  				return t[k] < u[k]
   327  			}
   328  		}
   329  		return len(t) < len(u)
   330  	})
   331  
   332  	return printCountProfile(w, debug, p.name, stackProfile(all))
   333  }
   334  
   335  type stackProfile [][]uintptr
   336  
   337  func (x stackProfile) Len() int              { return len(x) }
   338  func (x stackProfile) Stack(i int) []uintptr { return x[i] }
   339  
   340  // A countProfile is a set of stack traces to be printed as counts
   341  // grouped by stack trace. There are multiple implementations:
   342  // all that matters is that we can find out how many traces there are
   343  // and obtain each trace in turn.
   344  type countProfile interface {
   345  	Len() int
   346  	Stack(i int) []uintptr
   347  }
   348  
   349  // printCountProfile prints a countProfile at the specified debug level.
   350  // The profile will be in compressed proto format unless debug is nonzero.
   351  func printCountProfile(w io.Writer, debug int, name string, p countProfile) error {
   352  	// Build count of each stack.
   353  	var buf bytes.Buffer
   354  	key := func(stk []uintptr) string {
   355  		buf.Reset()
   356  		fmt.Fprintf(&buf, "@")
   357  		for _, pc := range stk {
   358  			fmt.Fprintf(&buf, " %#x", pc)
   359  		}
   360  		return buf.String()
   361  	}
   362  	count := map[string]int{}
   363  	index := map[string]int{}
   364  	var keys []string
   365  	n := p.Len()
   366  	for i := 0; i < n; i++ {
   367  		k := key(p.Stack(i))
   368  		if count[k] == 0 {
   369  			index[k] = i
   370  			keys = append(keys, k)
   371  		}
   372  		count[k]++
   373  	}
   374  
   375  	sort.Sort(&keysByCount{keys, count})
   376  
   377  	if debug > 0 {
   378  		// Print debug profile in legacy format
   379  		tw := tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
   380  		fmt.Fprintf(tw, "%s profile: total %d\n", name, p.Len())
   381  		for _, k := range keys {
   382  			fmt.Fprintf(tw, "%d %s\n", count[k], k)
   383  			printStackRecord(tw, p.Stack(index[k]), false)
   384  		}
   385  		return tw.Flush()
   386  	}
   387  
   388  	// Output profile in protobuf form.
   389  	b := newProfileBuilder(w)
   390  	b.pbValueType(tagProfile_PeriodType, name, "count")
   391  	b.pb.int64Opt(tagProfile_Period, 1)
   392  	b.pbValueType(tagProfile_SampleType, name, "count")
   393  
   394  	values := []int64{0}
   395  	var locs []uint64
   396  	for _, k := range keys {
   397  		values[0] = int64(count[k])
   398  		locs = locs[:0]
   399  		for _, addr := range p.Stack(index[k]) {
   400  			// For count profiles, all stack addresses are
   401  			// return PCs, which is what locForPC expects.
   402  			l := b.locForPC(addr)
   403  			if l == 0 { // runtime.goexit
   404  				continue
   405  			}
   406  			locs = append(locs, l)
   407  		}
   408  		b.pbSample(values, locs, nil)
   409  	}
   410  	b.build()
   411  	return nil
   412  }
   413  
   414  // keysByCount sorts keys with higher counts first, breaking ties by key string order.
   415  type keysByCount struct {
   416  	keys  []string
   417  	count map[string]int
   418  }
   419  
   420  func (x *keysByCount) Len() int      { return len(x.keys) }
   421  func (x *keysByCount) Swap(i, j int) { x.keys[i], x.keys[j] = x.keys[j], x.keys[i] }
   422  func (x *keysByCount) Less(i, j int) bool {
   423  	ki, kj := x.keys[i], x.keys[j]
   424  	ci, cj := x.count[ki], x.count[kj]
   425  	if ci != cj {
   426  		return ci > cj
   427  	}
   428  	return ki < kj
   429  }
   430  
   431  // printStackRecord prints the function + source line information
   432  // for a single stack trace.
   433  func printStackRecord(w io.Writer, stk []uintptr, allFrames bool) {
   434  	show := allFrames
   435  	frames := runtime.CallersFrames(stk)
   436  	for {
   437  		frame, more := frames.Next()
   438  		name := frame.Function
   439  		if name == "" {
   440  			show = true
   441  			fmt.Fprintf(w, "#\t%#x\n", frame.PC)
   442  		} else if name != "runtime.goexit" && (show || !strings.HasPrefix(name, "runtime.")) {
   443  			// Hide runtime.goexit and any runtime functions at the beginning.
   444  			// This is useful mainly for allocation traces.
   445  			show = true
   446  			fmt.Fprintf(w, "#\t%#x\t%s+%#x\t%s:%d\n", frame.PC, name, frame.PC-frame.Entry, frame.File, frame.Line)
   447  		}
   448  		if !more {
   449  			break
   450  		}
   451  	}
   452  	if !show {
   453  		// We didn't print anything; do it again,
   454  		// and this time include runtime functions.
   455  		printStackRecord(w, stk, true)
   456  		return
   457  	}
   458  	fmt.Fprintf(w, "\n")
   459  }
   460  
   461  // Interface to system profiles.
   462  
   463  // WriteHeapProfile is shorthand for Lookup("heap").WriteTo(w, 0).
   464  // It is preserved for backwards compatibility.
   465  func WriteHeapProfile(w io.Writer) error {
   466  	return writeHeap(w, 0)
   467  }
   468  
   469  // countHeap returns the number of records in the heap profile.
   470  func countHeap() int {
   471  	n, _ := runtime.MemProfile(nil, true)
   472  	return n
   473  }
   474  
   475  // writeHeap writes the current runtime heap profile to w.
   476  func writeHeap(w io.Writer, debug int) error {
   477  	// Find out how many records there are (MemProfile(nil, true)),
   478  	// allocate that many records, and get the data.
   479  	// There's a race—more records might be added between
   480  	// the two calls—so allocate a few extra records for safety
   481  	// and also try again if we're very unlucky.
   482  	// The loop should only execute one iteration in the common case.
   483  	var p []runtime.MemProfileRecord
   484  	n, ok := runtime.MemProfile(nil, true)
   485  	for {
   486  		// Allocate room for a slightly bigger profile,
   487  		// in case a few more entries have been added
   488  		// since the call to MemProfile.
   489  		p = make([]runtime.MemProfileRecord, n+50)
   490  		n, ok = runtime.MemProfile(p, true)
   491  		if ok {
   492  			p = p[0:n]
   493  			break
   494  		}
   495  		// Profile grew; try again.
   496  	}
   497  
   498  	if debug == 0 {
   499  		return writeHeapProto(w, p, int64(runtime.MemProfileRate))
   500  	}
   501  
   502  	sort.Slice(p, func(i, j int) bool { return p[i].InUseBytes() > p[j].InUseBytes() })
   503  
   504  	b := bufio.NewWriter(w)
   505  	tw := tabwriter.NewWriter(b, 1, 8, 1, '\t', 0)
   506  	w = tw
   507  
   508  	var total runtime.MemProfileRecord
   509  	for i := range p {
   510  		r := &p[i]
   511  		total.AllocBytes += r.AllocBytes
   512  		total.AllocObjects += r.AllocObjects
   513  		total.FreeBytes += r.FreeBytes
   514  		total.FreeObjects += r.FreeObjects
   515  	}
   516  
   517  	// Technically the rate is MemProfileRate not 2*MemProfileRate,
   518  	// but early versions of the C++ heap profiler reported 2*MemProfileRate,
   519  	// so that's what pprof has come to expect.
   520  	fmt.Fprintf(w, "heap profile: %d: %d [%d: %d] @ heap/%d\n",
   521  		total.InUseObjects(), total.InUseBytes(),
   522  		total.AllocObjects, total.AllocBytes,
   523  		2*runtime.MemProfileRate)
   524  
   525  	for i := range p {
   526  		r := &p[i]
   527  		fmt.Fprintf(w, "%d: %d [%d: %d] @",
   528  			r.InUseObjects(), r.InUseBytes(),
   529  			r.AllocObjects, r.AllocBytes)
   530  		for _, pc := range r.Stack() {
   531  			fmt.Fprintf(w, " %#x", pc)
   532  		}
   533  		fmt.Fprintf(w, "\n")
   534  		printStackRecord(w, r.Stack(), false)
   535  	}
   536  
   537  	// Print memstats information too.
   538  	// Pprof will ignore, but useful for people
   539  	s := new(runtime.MemStats)
   540  	runtime.ReadMemStats(s)
   541  	fmt.Fprintf(w, "\n# runtime.MemStats\n")
   542  	fmt.Fprintf(w, "# Alloc = %d\n", s.Alloc)
   543  	fmt.Fprintf(w, "# TotalAlloc = %d\n", s.TotalAlloc)
   544  	fmt.Fprintf(w, "# Sys = %d\n", s.Sys)
   545  	fmt.Fprintf(w, "# Lookups = %d\n", s.Lookups)
   546  	fmt.Fprintf(w, "# Mallocs = %d\n", s.Mallocs)
   547  	fmt.Fprintf(w, "# Frees = %d\n", s.Frees)
   548  
   549  	fmt.Fprintf(w, "# HeapAlloc = %d\n", s.HeapAlloc)
   550  	fmt.Fprintf(w, "# HeapSys = %d\n", s.HeapSys)
   551  	fmt.Fprintf(w, "# HeapIdle = %d\n", s.HeapIdle)
   552  	fmt.Fprintf(w, "# HeapInuse = %d\n", s.HeapInuse)
   553  	fmt.Fprintf(w, "# HeapReleased = %d\n", s.HeapReleased)
   554  	fmt.Fprintf(w, "# HeapObjects = %d\n", s.HeapObjects)
   555  
   556  	fmt.Fprintf(w, "# Stack = %d / %d\n", s.StackInuse, s.StackSys)
   557  	fmt.Fprintf(w, "# MSpan = %d / %d\n", s.MSpanInuse, s.MSpanSys)
   558  	fmt.Fprintf(w, "# MCache = %d / %d\n", s.MCacheInuse, s.MCacheSys)
   559  	fmt.Fprintf(w, "# BuckHashSys = %d\n", s.BuckHashSys)
   560  	fmt.Fprintf(w, "# GCSys = %d\n", s.GCSys)
   561  	fmt.Fprintf(w, "# OtherSys = %d\n", s.OtherSys)
   562  
   563  	fmt.Fprintf(w, "# NextGC = %d\n", s.NextGC)
   564  	fmt.Fprintf(w, "# LastGC = %d\n", s.LastGC)
   565  	fmt.Fprintf(w, "# PauseNs = %d\n", s.PauseNs)
   566  	fmt.Fprintf(w, "# PauseEnd = %d\n", s.PauseEnd)
   567  	fmt.Fprintf(w, "# NumGC = %d\n", s.NumGC)
   568  	fmt.Fprintf(w, "# NumForcedGC = %d\n", s.NumForcedGC)
   569  	fmt.Fprintf(w, "# GCCPUFraction = %v\n", s.GCCPUFraction)
   570  	fmt.Fprintf(w, "# DebugGC = %v\n", s.DebugGC)
   571  
   572  	tw.Flush()
   573  	return b.Flush()
   574  }
   575  
   576  // countThreadCreate returns the size of the current ThreadCreateProfile.
   577  func countThreadCreate() int {
   578  	n, _ := runtime.ThreadCreateProfile(nil)
   579  	return n
   580  }
   581  
   582  // writeThreadCreate writes the current runtime ThreadCreateProfile to w.
   583  func writeThreadCreate(w io.Writer, debug int) error {
   584  	return writeRuntimeProfile(w, debug, "threadcreate", runtime.ThreadCreateProfile)
   585  }
   586  
   587  // countGoroutine returns the number of goroutines.
   588  func countGoroutine() int {
   589  	return runtime.NumGoroutine()
   590  }
   591  
   592  // writeGoroutine writes the current runtime GoroutineProfile to w.
   593  func writeGoroutine(w io.Writer, debug int) error {
   594  	if debug >= 2 {
   595  		return writeGoroutineStacks(w)
   596  	}
   597  	return writeRuntimeProfile(w, debug, "goroutine", runtime.GoroutineProfile)
   598  }
   599  
   600  func writeGoroutineStacks(w io.Writer) error {
   601  	// We don't know how big the buffer needs to be to collect
   602  	// all the goroutines. Start with 1 MB and try a few times, doubling each time.
   603  	// Give up and use a truncated trace if 64 MB is not enough.
   604  	buf := make([]byte, 1<<20)
   605  	for i := 0; ; i++ {
   606  		n := runtime.Stack(buf, true)
   607  		if n < len(buf) {
   608  			buf = buf[:n]
   609  			break
   610  		}
   611  		if len(buf) >= 64<<20 {
   612  			// Filled 64 MB - stop there.
   613  			break
   614  		}
   615  		buf = make([]byte, 2*len(buf))
   616  	}
   617  	_, err := w.Write(buf)
   618  	return err
   619  }
   620  
   621  func writeRuntimeProfile(w io.Writer, debug int, name string, fetch func([]runtime.StackRecord) (int, bool)) error {
   622  	// Find out how many records there are (fetch(nil)),
   623  	// allocate that many records, and get the data.
   624  	// There's a race—more records might be added between
   625  	// the two calls—so allocate a few extra records for safety
   626  	// and also try again if we're very unlucky.
   627  	// The loop should only execute one iteration in the common case.
   628  	var p []runtime.StackRecord
   629  	n, ok := fetch(nil)
   630  	for {
   631  		// Allocate room for a slightly bigger profile,
   632  		// in case a few more entries have been added
   633  		// since the call to ThreadProfile.
   634  		p = make([]runtime.StackRecord, n+10)
   635  		n, ok = fetch(p)
   636  		if ok {
   637  			p = p[0:n]
   638  			break
   639  		}
   640  		// Profile grew; try again.
   641  	}
   642  
   643  	return printCountProfile(w, debug, name, runtimeProfile(p))
   644  }
   645  
   646  type runtimeProfile []runtime.StackRecord
   647  
   648  func (p runtimeProfile) Len() int              { return len(p) }
   649  func (p runtimeProfile) Stack(i int) []uintptr { return p[i].Stack() }
   650  
   651  var cpu struct {
   652  	sync.Mutex
   653  	profiling bool
   654  	done      chan bool
   655  }
   656  
   657  // StartCPUProfile enables CPU profiling for the current process.
   658  // While profiling, the profile will be buffered and written to w.
   659  // StartCPUProfile returns an error if profiling is already enabled.
   660  //
   661  // On Unix-like systems, StartCPUProfile does not work by default for
   662  // Go code built with -buildmode=c-archive or -buildmode=c-shared.
   663  // StartCPUProfile relies on the SIGPROF signal, but that signal will
   664  // be delivered to the main program's SIGPROF signal handler (if any)
   665  // not to the one used by Go. To make it work, call os/signal.Notify
   666  // for syscall.SIGPROF, but note that doing so may break any profiling
   667  // being done by the main program.
   668  func StartCPUProfile(w io.Writer) error {
   669  	// The runtime routines allow a variable profiling rate,
   670  	// but in practice operating systems cannot trigger signals
   671  	// at more than about 500 Hz, and our processing of the
   672  	// signal is not cheap (mostly getting the stack trace).
   673  	// 100 Hz is a reasonable choice: it is frequent enough to
   674  	// produce useful data, rare enough not to bog down the
   675  	// system, and a nice round number to make it easy to
   676  	// convert sample counts to seconds. Instead of requiring
   677  	// each client to specify the frequency, we hard code it.
   678  	const hz = 100
   679  
   680  	cpu.Lock()
   681  	defer cpu.Unlock()
   682  	if cpu.done == nil {
   683  		cpu.done = make(chan bool)
   684  	}
   685  	// Double-check.
   686  	if cpu.profiling {
   687  		return fmt.Errorf("cpu profiling already in use")
   688  	}
   689  	cpu.profiling = true
   690  	runtime.SetCPUProfileRate(hz)
   691  	go profileWriter(w)
   692  	return nil
   693  }
   694  
   695  // readProfile, provided by the runtime, returns the next chunk of
   696  // binary CPU profiling stack trace data, blocking until data is available.
   697  // If profiling is turned off and all the profile data accumulated while it was
   698  // on has been returned, readProfile returns eof=true.
   699  // The caller must save the returned data and tags before calling readProfile again.
   700  func readProfile() (data []uint64, tags []unsafe.Pointer, eof bool)
   701  
   702  func profileWriter(w io.Writer) {
   703  	b := newProfileBuilder(w)
   704  	var err error
   705  	for {
   706  		time.Sleep(100 * time.Millisecond)
   707  		data, tags, eof := readProfile()
   708  		if e := b.addCPUData(data, tags); e != nil && err == nil {
   709  			err = e
   710  		}
   711  		if eof {
   712  			break
   713  		}
   714  	}
   715  	if err != nil {
   716  		// The runtime should never produce an invalid or truncated profile.
   717  		// It drops records that can't fit into its log buffers.
   718  		panic("runtime/pprof: converting profile: " + err.Error())
   719  	}
   720  	b.build()
   721  	cpu.done <- true
   722  }
   723  
   724  // StopCPUProfile stops the current CPU profile, if any.
   725  // StopCPUProfile only returns after all the writes for the
   726  // profile have completed.
   727  func StopCPUProfile() {
   728  	cpu.Lock()
   729  	defer cpu.Unlock()
   730  
   731  	if !cpu.profiling {
   732  		return
   733  	}
   734  	cpu.profiling = false
   735  	runtime.SetCPUProfileRate(0)
   736  	<-cpu.done
   737  }
   738  
   739  // countBlock returns the number of records in the blocking profile.
   740  func countBlock() int {
   741  	n, _ := runtime.BlockProfile(nil)
   742  	return n
   743  }
   744  
   745  // countMutex returns the number of records in the mutex profile.
   746  func countMutex() int {
   747  	n, _ := runtime.MutexProfile(nil)
   748  	return n
   749  }
   750  
   751  // writeBlock writes the current blocking profile to w.
   752  func writeBlock(w io.Writer, debug int) error {
   753  	var p []runtime.BlockProfileRecord
   754  	n, ok := runtime.BlockProfile(nil)
   755  	for {
   756  		p = make([]runtime.BlockProfileRecord, n+50)
   757  		n, ok = runtime.BlockProfile(p)
   758  		if ok {
   759  			p = p[:n]
   760  			break
   761  		}
   762  	}
   763  
   764  	sort.Slice(p, func(i, j int) bool { return p[i].Cycles > p[j].Cycles })
   765  
   766  	b := bufio.NewWriter(w)
   767  	var tw *tabwriter.Writer
   768  	w = b
   769  	if debug > 0 {
   770  		tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
   771  		w = tw
   772  	}
   773  
   774  	fmt.Fprintf(w, "--- contention:\n")
   775  	fmt.Fprintf(w, "cycles/second=%v\n", runtime_cyclesPerSecond())
   776  	for i := range p {
   777  		r := &p[i]
   778  		fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count)
   779  		for _, pc := range r.Stack() {
   780  			fmt.Fprintf(w, " %#x", pc)
   781  		}
   782  		fmt.Fprint(w, "\n")
   783  		if debug > 0 {
   784  			printStackRecord(w, r.Stack(), true)
   785  		}
   786  	}
   787  
   788  	if tw != nil {
   789  		tw.Flush()
   790  	}
   791  	return b.Flush()
   792  }
   793  
   794  // writeMutex writes the current mutex profile to w.
   795  func writeMutex(w io.Writer, debug int) error {
   796  	// TODO(pjw): too much common code with writeBlock. FIX!
   797  	var p []runtime.BlockProfileRecord
   798  	n, ok := runtime.MutexProfile(nil)
   799  	for {
   800  		p = make([]runtime.BlockProfileRecord, n+50)
   801  		n, ok = runtime.MutexProfile(p)
   802  		if ok {
   803  			p = p[:n]
   804  			break
   805  		}
   806  	}
   807  
   808  	sort.Slice(p, func(i, j int) bool { return p[i].Cycles > p[j].Cycles })
   809  
   810  	b := bufio.NewWriter(w)
   811  	var tw *tabwriter.Writer
   812  	w = b
   813  	if debug > 0 {
   814  		tw = tabwriter.NewWriter(w, 1, 8, 1, '\t', 0)
   815  		w = tw
   816  	}
   817  
   818  	fmt.Fprintf(w, "--- mutex:\n")
   819  	fmt.Fprintf(w, "cycles/second=%v\n", runtime_cyclesPerSecond())
   820  	fmt.Fprintf(w, "sampling period=%d\n", runtime.SetMutexProfileFraction(-1))
   821  	for i := range p {
   822  		r := &p[i]
   823  		fmt.Fprintf(w, "%v %v @", r.Cycles, r.Count)
   824  		for _, pc := range r.Stack() {
   825  			fmt.Fprintf(w, " %#x", pc)
   826  		}
   827  		fmt.Fprint(w, "\n")
   828  		if debug > 0 {
   829  			printStackRecord(w, r.Stack(), true)
   830  		}
   831  	}
   832  
   833  	if tw != nil {
   834  		tw.Flush()
   835  	}
   836  	return b.Flush()
   837  }
   838  
   839  func runtime_cyclesPerSecond() int64