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