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