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