Debian Codegraph @

libgo/go/runtime/pprof/pprof_test.go

raw
1 // Copyright 2011 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 //go:build !js
6
7 package pprof
8
9 import (
10 "bytes"
11 "context"
12 "fmt"
13 "internal/abi"
14 "internal/profile"
15 "internal/testenv"
16 "io"
17 "math"
18 "math/big"
19 "os"
20 "os/exec"
21 "regexp"
22 "runtime"
23 "runtime/debug"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "testing"
28 "time"
29 _ "unsafe"
30 )
31
32 func cpuHogger(f func(x int) int, y *int, dur time.Duration) {
33 // We only need to get one 100 Hz clock tick, so we've got
34 // a large safety buffer.
35 // But do at least 500 iterations (which should take about 100ms),
36 // otherwise TestCPUProfileMultithreaded can fail if only one
37 // thread is scheduled during the testing period.
38 t0 := time.Now()
39 accum := *y
40 for i := 0; i < 500 || time.Since(t0) < dur; i++ {
41 accum = f(accum)
42 }
43 *y = accum
44 }
45
46 var (
47 salt1 = 0
48 salt2 = 0
49 )
50
51 // The actual CPU hogging function.
52 // Must not call other functions nor access heap/globals in the loop,
53 // otherwise under race detector the samples will be in the race runtime.
54 func cpuHog1(x int) int {
55 return cpuHog0(x, 1e5)
56 }
57
58 func cpuHog0(x, n int) int {
59 foo := x
60 for i := 0; i < n; i++ {
61 if foo > 0 {
62 foo *= foo
63 } else {
64 foo *= foo + 1
65 }
66 }
67 return foo
68 }
69
70 func cpuHog2(x int) int {
71 foo := x
72 for i := 0; i < 1e5; i++ {
73 if foo > 0 {
74 foo *= foo
75 } else {
76 foo *= foo + 2
77 }
78 }
79 return foo
80 }
81
82 // Return a list of functions that we don't want to ever appear in CPU
83 // profiles. For gccgo, that list includes the sigprof handler itself.
84 func avoidFunctions() []string {
85 if runtime.Compiler == "gccgo" {
86 return []string{"runtime.sigprof"}
87 }
88 return nil
89 }
90
91 func TestCPUProfile(t *testing.T) {
92 matches := matchAndAvoidStacks(stackContains, []string{"pprof.cpuHog1"}, avoidFunctions())
93 testCPUProfile(t, matches, func(dur time.Duration) {
94 cpuHogger(cpuHog1, &salt1, dur)
95 })
96 }
97
98 func TestCPUProfileMultithreaded(t *testing.T) {
99 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))
100 matches := matchAndAvoidStacks(stackContains, []string{"pprof.cpuHog1", "pprof.cpuHog2"}, avoidFunctions())
101 testCPUProfile(t, matches, func(dur time.Duration) {
102 c := make(chan int)
103 go func() {
104 cpuHogger(cpuHog1, &salt1, dur)
105 c <- 1
106 }()
107 cpuHogger(cpuHog2, &salt2, dur)
108 <-c
109 })
110 }
111
112 func TestCPUProfileMultithreadMagnitude(t *testing.T) {
113 if runtime.GOOS != "linux" {
114 t.Skip("issue 35057 is only confirmed on Linux")
115 }
116
117 // Linux [5.9,5.16) has a kernel bug that can break CPU timers on newly
118 // created threads, breaking our CPU accounting.
119 major, minor, patch, err := linuxKernelVersion()
120 if err != nil {
121 t.Errorf("Error determining kernel version: %v", err)
122 }
123 t.Logf("Running on Linux %d.%d.%d", major, minor, patch)
124 defer func() {
125 if t.Failed() {
126 t.Logf("Failure of this test may indicate that your system suffers from a known Linux kernel bug fixed on newer kernels. See https://golang.org/issue/49065.")
127 }
128 }()
129
130 // Disable on affected builders to avoid flakiness, but otherwise keep
131 // it enabled to potentially warn users that they are on a broken
132 // kernel.
133 if testenv.Builder() != "" && (runtime.GOARCH == "386" || runtime.GOARCH == "amd64") {
134 have59 := major > 5 || (major == 5 && minor >= 9)
135 have516 := major > 5 || (major == 5 && minor >= 16)
136 if have59 && !have516 {
137 testenv.SkipFlaky(t, 49065)
138 }
139 }
140
141 // Run a workload in a single goroutine, then run copies of the same
142 // workload in several goroutines. For both the serial and parallel cases,
143 // the CPU time the process measures with its own profiler should match the
144 // total CPU usage that the OS reports.
145 //
146 // We could also check that increases in parallelism (GOMAXPROCS) lead to a
147 // linear increase in the CPU usage reported by both the OS and the
148 // profiler, but without a guarantee of exclusive access to CPU resources
149 // that is likely to be a flaky test.
150
151 // Require the smaller value to be within 10%, or 40% in short mode.
152 maxDiff := 0.10
153 if testing.Short() {
154 maxDiff = 0.40
155 }
156
157 compare := func(a, b time.Duration, maxDiff float64) error {
158 if a <= 0 || b <= 0 {
159 return fmt.Errorf("Expected both time reports to be positive")
160 }
161
162 if a < b {
163 a, b = b, a
164 }
165
166 diff := float64(a-b) / float64(a)
167 if diff > maxDiff {
168 return fmt.Errorf("CPU usage reports are too different (limit -%.1f%%, got -%.1f%%)", maxDiff*100, diff*100)
169 }
170
171 return nil
172 }
173
174 for _, tc := range []struct {
175 name string
176 workers int
177 }{
178 {
179 name: "serial",
180 workers: 1,
181 },
182 {
183 name: "parallel",
184 workers: runtime.GOMAXPROCS(0),
185 },
186 } {
187 // check that the OS's perspective matches what the Go runtime measures.
188 t.Run(tc.name, func(t *testing.T) {
189 t.Logf("Running with %d workers", tc.workers)
190
191 var cpuTime time.Duration
192 matches := matchAndAvoidStacks(stackContains, []string{"runtime/pprof.cpuHog1"}, avoidFunctions())
193 p := testCPUProfile(t, matches, func(dur time.Duration) {
194 cpuTime = diffCPUTime(t, func() {
195 var wg sync.WaitGroup
196 var once sync.Once
197 for i := 0; i < tc.workers; i++ {
198 wg.Add(1)
199 go func() {
200 defer wg.Done()
201 var salt = 0
202 cpuHogger(cpuHog1, &salt, dur)
203 once.Do(func() { salt1 = salt })
204 }()
205 }
206 wg.Wait()
207 })
208 })
209
210 for i, unit := range []string{"count", "nanoseconds"} {
211 if have, want := p.SampleType[i].Unit, unit; have != want {
212 t.Errorf("pN SampleType[%d]; %q != %q", i, have, want)
213 }
214 }
215
216 // cpuHog1 called above is the primary source of CPU
217 // load, but there may be some background work by the
218 // runtime. Since the OS rusage measurement will
219 // include all work done by the process, also compare
220 // against all samples in our profile.
221 var value time.Duration
222 for _, sample := range p.Sample {
223 value += time.Duration(sample.Value[1]) * time.Nanosecond
224 }
225
226 t.Logf("compare %s vs %s", cpuTime, value)
227 if err := compare(cpuTime, value, maxDiff); err != nil {
228 t.Errorf("compare got %v want nil", err)
229 }
230 })
231 }
232 }
233
234 // containsInlinedCall reports whether the function body for the function f is
235 // known to contain an inlined function call within the first maxBytes bytes.
236 func containsInlinedCall(f any, maxBytes int) bool {
237 _, found := findInlinedCall(f, maxBytes)
238 return found
239 }
240
241 // findInlinedCall returns the PC of an inlined function call within
242 // the function body for the function f if any.
243 func findInlinedCall(f any, maxBytes int) (pc uint64, found bool) {
244 fFunc := runtime.FuncForPC(uintptr(abi.FuncPCABIInternal(f)))
245 if fFunc == nil || fFunc.Entry() == 0 {
246 panic("failed to locate function entry")
247 }
248
249 for offset := 0; offset < maxBytes; offset++ {
250 innerPC := fFunc.Entry() + uintptr(offset)
251 inner := runtime.FuncForPC(innerPC)
252 if inner == nil {
253 // No function known for this PC value.
254 // It might simply be misaligned, so keep searching.
255 continue
256 }
257 if inner.Entry() != fFunc.Entry() {
258 // Scanned past f and didn't find any inlined functions.
259 break
260 }
261 if inner.Name() != fFunc.Name() {
262 // This PC has f as its entry-point, but is not f. Therefore, it must be a
263 // function inlined into f.
264 return uint64(innerPC), true
265 }
266 }
267
268 return 0, false
269 }
270
271 func TestCPUProfileInlining(t *testing.T) {
272 if !containsInlinedCall(inlinedCaller, 4<<10) {
273 t.Skip("Can't determine whether inlinedCallee was inlined into inlinedCaller.")
274 }
275
276 matches := matchAndAvoidStacks(stackContains, []string{"pprof.inlinedCallee", "pprof.inlinedCaller"}, avoidFunctions())
277 p := testCPUProfile(t, matches, func(dur time.Duration) {
278 cpuHogger(inlinedCaller, &salt1, dur)
279 })
280
281 // Check if inlined function locations are encoded correctly. The inlinedCalee and inlinedCaller should be in one location.
282 for _, loc := range p.Location {
283 hasInlinedCallerAfterInlinedCallee, hasInlinedCallee := false, false
284 for _, line := range loc.Line {
285 if line.Function.Name == "runtime/pprof.inlinedCallee" {
286 hasInlinedCallee = true
287 }
288 if hasInlinedCallee && line.Function.Name == "runtime/pprof.inlinedCaller" {
289 hasInlinedCallerAfterInlinedCallee = true
290 }
291 }
292 if hasInlinedCallee != hasInlinedCallerAfterInlinedCallee {
293 t.Fatalf("want inlinedCallee followed by inlinedCaller, got separate Location entries:\n%v", p)
294 }
295 }
296 }
297
298 func inlinedCaller(x int) int {
299 x = inlinedCallee(x, 1e5)
300 return x
301 }
302
303 func inlinedCallee(x, n int) int {
304 return cpuHog0(x, n)
305 }
306
307 //go:noinline
308 func dumpCallers(pcs []uintptr) {
309 if pcs == nil {
310 return
311 }
312
313 skip := 2 // Callers and dumpCallers
314 runtime.Callers(skip, pcs)
315 }
316
317 //go:noinline
318 func inlinedCallerDump(pcs []uintptr) {
319 inlinedCalleeDump(pcs)
320 }
321
322 func inlinedCalleeDump(pcs []uintptr) {
323 dumpCallers(pcs)
324 }
325
326 func TestCPUProfileRecursion(t *testing.T) {
327 matches := matchAndAvoidStacks(stackContains, []string{"runtime/pprof.inlinedCallee", "runtime/pprof.recursionCallee", "runtime/pprof.recursionCaller"}, avoidFunctions())
328 p := testCPUProfile(t, matches, func(dur time.Duration) {
329 cpuHogger(recursionCaller, &salt1, dur)
330 })
331
332 // check the Location encoding was not confused by recursive calls.
333 for i, loc := range p.Location {
334 recursionFunc := 0
335 for _, line := range loc.Line {
336 if name := line.Function.Name; name == "runtime/pprof.recursionCaller" || name == "runtime/pprof.recursionCallee" {
337 recursionFunc++
338 }
339 }
340 if recursionFunc > 1 {
341 t.Fatalf("want at most one recursionCaller or recursionCallee in one Location, got a violating Location (index: %d):\n%v", i, p)
342 }
343 }
344 }
345
346 func recursionCaller(x int) int {
347 y := recursionCallee(3, x)
348 return y
349 }
350
351 func recursionCallee(n, x int) int {
352 if n == 0 {
353 return 1
354 }
355 y := inlinedCallee(x, 1e4)
356 return y * recursionCallee(n-1, x)
357 }
358
359 func recursionChainTop(x int, pcs []uintptr) {
360 if x < 0 {
361 return
362 }
363 recursionChainMiddle(x, pcs)
364 }
365
366 func recursionChainMiddle(x int, pcs []uintptr) {
367 recursionChainBottom(x, pcs)
368 }
369
370 func recursionChainBottom(x int, pcs []uintptr) {
371 // This will be called each time, we only care about the last. We
372 // can't make this conditional or this function won't be inlined.
373 dumpCallers(pcs)
374
375 recursionChainTop(x-1, pcs)
376 }
377
378 func parseProfile(t *testing.T, valBytes []byte, f func(uintptr, []*profile.Location, map[string][]string)) *profile.Profile {
379 p, err := profile.Parse(bytes.NewReader(valBytes))
380 if err != nil {
381 t.Fatal(err)
382 }
383 for _, sample := range p.Sample {
384 count := uintptr(sample.Value[0])
385 f(count, sample.Location, sample.Label)
386 }
387 return p
388 }
389
390 func cpuProfilingBroken() bool {
391 switch runtime.GOOS {
392 case "plan9":
393 // Profiling unimplemented.
394 return true
395 case "aix":
396 // See https://golang.org/issue/45170.
397 return true
398 case "ios", "dragonfly", "netbsd", "illumos", "solaris":
399 // See https://golang.org/issue/13841.
400 return true
401 case "openbsd":
402 if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
403 // See https://golang.org/issue/13841.
404 return true
405 }
406 }
407
408 return false
409 }
410
411 // testCPUProfile runs f under the CPU profiler, checking for some conditions specified by need,
412 // as interpreted by matches, and returns the parsed profile.
413 func testCPUProfile(t *testing.T, matches profileMatchFunc, f func(dur time.Duration)) *profile.Profile {
414 switch runtime.GOOS {
415 case "darwin":
416 out, err := exec.Command("uname", "-a").CombinedOutput()
417 if err != nil {
418 t.Fatal(err)
419 }
420 vers := string(out)
421 t.Logf("uname -a: %v", vers)
422 case "plan9":
423 t.Skip("skipping on plan9")
424 }
425
426 broken := cpuProfilingBroken()
427
428 maxDuration := 5 * time.Second
429 if testing.Short() && broken {
430 // If it's expected to be broken, no point waiting around.
431 maxDuration /= 10
432 }
433
434 // If we're running a long test, start with a long duration
435 // for tests that try to make sure something *doesn't* happen.
436 duration := 5 * time.Second
437 if testing.Short() {
438 duration = 100 * time.Millisecond
439 }
440
441 // Profiling tests are inherently flaky, especially on a
442 // loaded system, such as when this test is running with
443 // several others under go test std. If a test fails in a way
444 // that could mean it just didn't run long enough, try with a
445 // longer duration.
446 for duration <= maxDuration {
447 var prof bytes.Buffer
448 if err := StartCPUProfile(&prof); err != nil {
449 t.Fatal(err)
450 }
451 f(duration)
452 StopCPUProfile()
453
454 if p, ok := profileOk(t, matches, prof, duration); ok {
455 return p
456 }
457
458 duration *= 2
459 if duration <= maxDuration {
460 t.Logf("retrying with %s duration", duration)
461 }
462 }
463
464 if broken {
465 t.Skipf("ignoring failure on %s/%s; see golang.org/issue/13841", runtime.GOOS, runtime.GOARCH)
466 }
467
468 // Ignore the failure if the tests are running in a QEMU-based emulator,
469 // QEMU is not perfect at emulating everything.
470 // IN_QEMU environmental variable is set by some of the Go builders.
471 // IN_QEMU=1 indicates that the tests are running in QEMU. See issue 9605.
472 if os.Getenv("IN_QEMU") == "1" {
473 t.Skip("ignore the failure in QEMU; see golang.org/issue/9605")
474 }
475 t.FailNow()
476 return nil
477 }
478
479 var diffCPUTimeImpl func(f func()) time.Duration
480
481 func diffCPUTime(t *testing.T, f func()) time.Duration {
482 if fn := diffCPUTimeImpl; fn != nil {
483 return fn(f)
484 }
485 t.Fatalf("cannot measure CPU time on GOOS=%s GOARCH=%s", runtime.GOOS, runtime.GOARCH)
486 return 0
487 }
488
489 func contains(slice []string, s string) bool {
490 for i := range slice {
491 if slice[i] == s {
492 return true
493 }
494 }
495 return false
496 }
497
498 // stackContains matches if a function named spec appears anywhere in the stack trace.
499 func stackContains(spec string, count uintptr, stk []*profile.Location, labels map[string][]string) bool {
500 for _, loc := range stk {
501 for _, line := range loc.Line {
502 if strings.Contains(line.Function.Name, spec) {
503 return true
504 }
505 }
506 }
507 return false
508 }
509
510 type sampleMatchFunc func(spec string, count uintptr, stk []*profile.Location, labels map[string][]string) bool
511
512 func profileOk(t *testing.T, matches profileMatchFunc, prof bytes.Buffer, duration time.Duration) (_ *profile.Profile, ok bool) {
513 ok = true
514
515 var samples uintptr
516 var buf bytes.Buffer
517 p := parseProfile(t, prof.Bytes(), func(count uintptr, stk []*profile.Location, labels map[string][]string) {
518 fmt.Fprintf(&buf, "%d:", count)
519 fprintStack(&buf, stk)
520 fmt.Fprintf(&buf, " labels: %v\n", labels)
521 samples += count
522 fmt.Fprintf(&buf, "\n")
523 })
524 t.Logf("total %d CPU profile samples collected:\n%s", samples, buf.String())
525
526 if samples < 10 && runtime.GOOS == "windows" {
527 // On some windows machines we end up with
528 // not enough samples due to coarse timer
529 // resolution. Let it go.
530 t.Log("too few samples on Windows (golang.org/issue/10842)")
531 return p, false
532 }
533
534 // Check that we got a reasonable number of samples.
535 // We used to always require at least ideal/4 samples,
536 // but that is too hard to guarantee on a loaded system.
537 // Now we accept 10 or more samples, which we take to be
538 // enough to show that at least some profiling is occurring.
539 if ideal := uintptr(duration * 100 / time.Second); samples == 0 || (samples < ideal/4 && samples < 10) {
540 t.Logf("too few samples; got %d, want at least %d, ideally %d", samples, ideal/4, ideal)
541 ok = false
542 }
543
544 if matches != nil && !matches(t, p) {
545 ok = false
546 }
547
548 return p, ok
549 }
550
551 type profileMatchFunc func(*testing.T, *profile.Profile) bool
552
553 func matchAndAvoidStacks(matches sampleMatchFunc, need []string, avoid []string) profileMatchFunc {
554 return func(t *testing.T, p *profile.Profile) (ok bool) {
555 ok = true
556
557 // Check that profile is well formed, contains 'need', and does not contain
558 // anything from 'avoid'.
559 have := make([]uintptr, len(need))
560 avoidSamples := make([]uintptr, len(avoid))
561
562 for _, sample := range p.Sample {
563 count := uintptr(sample.Value[0])
564 for i, spec := range need {
565 if matches(spec, count, sample.Location, sample.Label) {
566 have[i] += count
567 }
568 }
569 for i, name := range avoid {
570 for _, loc := range sample.Location {
571 for _, line := range loc.Line {
572 if strings.Contains(line.Function.Name, name) {
573 avoidSamples[i] += count
574 }
575 }
576 }
577 }
578 }
579
580 for i, name := range avoid {
581 bad := avoidSamples[i]
582 if bad != 0 {
583 t.Logf("found %d samples in avoid-function %s\n", bad, name)
584 ok = false
585 }
586 }
587
588 if len(need) == 0 {
589 return
590 }
591
592 var total uintptr
593 for i, name := range need {
594 total += have[i]
595 t.Logf("%s: %d\n", name, have[i])
596 }
597 if total == 0 {
598 t.Logf("no samples in expected functions")
599 ok = false
600 }
601
602 // We'd like to check a reasonable minimum, like
603 // total / len(have) / smallconstant, but this test is
604 // pretty flaky (see bug 7095). So we'll just test to
605 // make sure we got at least one sample.
606 min := uintptr(1)
607 for i, name := range need {
608 if have[i] < min {
609 t.Logf("%s has %d samples out of %d, want at least %d, ideally %d", name, have[i], total, min, total/uintptr(len(have)))
610 ok = false
611 }
612 }
613 return
614 }
615 }
616
617 // Fork can hang if preempted with signals frequently enough (see issue 5517).
618 // Ensure that we do not do this.
619 func TestCPUProfileWithFork(t *testing.T) {
620 testenv.MustHaveExec(t)
621
622 heap := 1 << 30
623 if runtime.GOOS == "android" {
624 // Use smaller size for Android to avoid crash.
625 heap = 100 << 20
626 }
627 if runtime.GOOS == "windows" && runtime.GOARCH == "arm" {
628 // Use smaller heap for Windows/ARM to avoid crash.
629 heap = 100 << 20
630 }
631 if testing.Short() {
632 heap = 100 << 20
633 }
634 // This makes fork slower.
635 garbage := make([]byte, heap)
636 // Need to touch the slice, otherwise it won't be paged in.
637 done := make(chan bool)
638 go func() {
639 for i := range garbage {
640 garbage[i] = 42
641 }
642 done <- true
643 }()
644 <-done
645
646 var prof bytes.Buffer
647 if err := StartCPUProfile(&prof); err != nil {
648 t.Fatal(err)
649 }
650 defer StopCPUProfile()
651
652 for i := 0; i < 10; i++ {
653 exec.Command(os.Args[0], "-h").CombinedOutput()
654 }
655 }
656
657 // Test that profiler does not observe runtime.gogo as "user" goroutine execution.
658 // If it did, it would see inconsistent state and would either record an incorrect stack
659 // or crash because the stack was malformed.
660 func TestGoroutineSwitch(t *testing.T) {
661 if runtime.Compiler == "gccgo" {
662 t.Skip("not applicable for gccgo")
663 }
664 // How much to try. These defaults take about 1 seconds
665 // on a 2012 MacBook Pro. The ones in short mode take
666 // about 0.1 seconds.
667 tries := 10
668 count := 1000000
669 if testing.Short() {
670 tries = 1
671 }
672 for try := 0; try < tries; try++ {
673 var prof bytes.Buffer
674 if err := StartCPUProfile(&prof); err != nil {
675 t.Fatal(err)
676 }
677 for i := 0; i < count; i++ {
678 runtime.Gosched()
679 }
680 StopCPUProfile()
681
682 // Read profile to look for entries for gogo with an attempt at a traceback.
683 // "runtime.gogo" is OK, because that's the part of the context switch
684 // before the actual switch begins. But we should not see "gogo",
685 // aka "gogo<>(SB)", which does the actual switch and is marked SPWRITE.
686 parseProfile(t, prof.Bytes(), func(count uintptr, stk []*profile.Location, _ map[string][]string) {
687 // An entry with two frames with 'System' in its top frame
688 // exists to record a PC without a traceback. Those are okay.
689 if len(stk) == 2 {
690 name := stk[1].Line[0].Function.Name
691 if name == "runtime._System" || name == "runtime._ExternalCode" || name == "runtime._GC" {
692 return
693 }
694 }
695
696 // An entry with just one frame is OK too:
697 // it knew to stop at gogo.
698 if len(stk) == 1 {
699 return
700 }
701
702 // Otherwise, should not see gogo.
703 // The place we'd see it would be the inner most frame.
704 name := stk[0].Line[0].Function.Name
705 if name == "gogo" {
706 var buf bytes.Buffer
707 fprintStack(&buf, stk)
708 t.Fatalf("found profile entry for gogo:\n%s", buf.String())
709 }
710 })
711 }
712 }
713
714 func fprintStack(w io.Writer, stk []*profile.Location) {
715 for _, loc := range stk {
716 fmt.Fprintf(w, " %#x", loc.Address)
717 fmt.Fprintf(w, " (")
718 for i, line := range loc.Line {
719 if i > 0 {
720 fmt.Fprintf(w, " ")
721 }
722 fmt.Fprintf(w, "%s:%d", line.Function.Name, line.Line)
723 }
724 fmt.Fprintf(w, ")")
725 }
726 }
727
728 // Test that profiling of division operations is okay, especially on ARM. See issue 6681.
729 func TestMathBigDivide(t *testing.T) {
730 testCPUProfile(t, nil, func(duration time.Duration) {
731 t := time.After(duration)
732 pi := new(big.Int)
733 for {
734 for i := 0; i < 100; i++ {
735 n := big.NewInt(2646693125139304345)
736 d := big.NewInt(842468587426513207)
737 pi.Div(n, d)
738 }
739 select {
740 case <-t:
741 return
742 default:
743 }
744 }
745 })
746 }
747
748 // stackContainsAll matches if all functions in spec (comma-separated) appear somewhere in the stack trace.
749 func stackContainsAll(spec string, count uintptr, stk []*profile.Location, labels map[string][]string) bool {
750 for _, f := range strings.Split(spec, ",") {
751 if !stackContains(f, count, stk, labels) {
752 return false
753 }
754 }
755 return true
756 }
757
758 func TestMorestack(t *testing.T) {
759 if runtime.Compiler == "gccgo" {
760 t.Skip("no runtime.newstack in gccgo")
761 }
762 matches := matchAndAvoidStacks(stackContainsAll, []string{"runtime.newstack,runtime/pprof.growstack"}, avoidFunctions())
763 testCPUProfile(t, matches, func(duration time.Duration) {
764 t := time.After(duration)
765 c := make(chan bool)
766 for {
767 go func() {
768 growstack1()
769 c <- true
770 }()
771 select {
772 case <-t:
773 return
774 case <-c:
775 }
776 }
777 })
778 }
779
780 //go:noinline
781 func growstack1() {
782 growstack(10)
783 }
784
785 //go:noinline
786 func growstack(n int) {
787 var buf [8 << 18]byte
788 use(buf)
789 if n > 0 {
790 growstack(n - 1)
791 }
792 }
793
794 //go:noinline
795 func use(x [8 << 18]byte) {}
796
797 func TestBlockProfile(t *testing.T) {
798 t.Skip("lots of details are different for gccgo; FIXME")
799 type TestCase struct {
800 name string
801 f func(*testing.T)
802 stk []string
803 re string
804 }
805 tests := [...]TestCase{
806 {
807 name: "chan recv",
808 f: blockChanRecv,
809 stk: []string{
810 "runtime.chanrecv1",
811 "runtime/pprof.blockChanRecv",
812 "runtime/pprof.TestBlockProfile",
813 },
814 re: `
815 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
816 # 0x[0-9a-f]+ runtime\.chanrecv1\+0x[0-9a-f]+ .*/src/runtime/chan.go:[0-9]+
817 # 0x[0-9a-f]+ runtime/pprof\.blockChanRecv\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
818 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
819 `},
820 {
821 name: "chan send",
822 f: blockChanSend,
823 stk: []string{
824 "runtime.chansend1",
825 "runtime/pprof.blockChanSend",
826 "runtime/pprof.TestBlockProfile",
827 },
828 re: `
829 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
830 # 0x[0-9a-f]+ runtime\.chansend1\+0x[0-9a-f]+ .*/src/runtime/chan.go:[0-9]+
831 # 0x[0-9a-f]+ runtime/pprof\.blockChanSend\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
832 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
833 `},
834 {
835 name: "chan close",
836 f: blockChanClose,
837 stk: []string{
838 "runtime.chanrecv1",
839 "runtime/pprof.blockChanClose",
840 "runtime/pprof.TestBlockProfile",
841 },
842 re: `
843 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
844 # 0x[0-9a-f]+ runtime\.chanrecv1\+0x[0-9a-f]+ .*/src/runtime/chan.go:[0-9]+
845 # 0x[0-9a-f]+ runtime/pprof\.blockChanClose\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
846 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
847 `},
848 {
849 name: "select recv async",
850 f: blockSelectRecvAsync,
851 stk: []string{
852 "runtime.selectgo",
853 "runtime/pprof.blockSelectRecvAsync",
854 "runtime/pprof.TestBlockProfile",
855 },
856 re: `
857 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
858 # 0x[0-9a-f]+ runtime\.selectgo\+0x[0-9a-f]+ .*/src/runtime/select.go:[0-9]+
859 # 0x[0-9a-f]+ runtime/pprof\.blockSelectRecvAsync\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
860 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
861 `},
862 {
863 name: "select send sync",
864 f: blockSelectSendSync,
865 stk: []string{
866 "runtime.selectgo",
867 "runtime/pprof.blockSelectSendSync",
868 "runtime/pprof.TestBlockProfile",
869 },
870 re: `
871 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
872 # 0x[0-9a-f]+ runtime\.selectgo\+0x[0-9a-f]+ .*/src/runtime/select.go:[0-9]+
873 # 0x[0-9a-f]+ runtime/pprof\.blockSelectSendSync\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
874 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
875 `},
876 {
877 name: "mutex",
878 f: blockMutex,
879 stk: []string{
880 "sync.(*Mutex).Lock",
881 "runtime/pprof.blockMutex",
882 "runtime/pprof.TestBlockProfile",
883 },
884 re: `
885 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
886 # 0x[0-9a-f]+ sync\.\(\*Mutex\)\.Lock\+0x[0-9a-f]+ .*/src/sync/mutex\.go:[0-9]+
887 # 0x[0-9a-f]+ runtime/pprof\.blockMutex\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
888 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
889 `},
890 {
891 name: "cond",
892 f: blockCond,
893 stk: []string{
894 "sync.(*Cond).Wait",
895 "runtime/pprof.blockCond",
896 "runtime/pprof.TestBlockProfile",
897 },
898 re: `
899 [0-9]+ [0-9]+ @( 0x[[:xdigit:]]+)+
900 # 0x[0-9a-f]+ sync\.\(\*Cond\)\.Wait\+0x[0-9a-f]+ .*/src/sync/cond\.go:[0-9]+
901 # 0x[0-9a-f]+ runtime/pprof\.blockCond\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
902 # 0x[0-9a-f]+ runtime/pprof\.TestBlockProfile\+0x[0-9a-f]+ .*/src/runtime/pprof/pprof_test.go:[0-9]+
903 `},
904 }
905
906 // Generate block profile
907 runtime.SetBlockProfileRate(1)
908 defer runtime.SetBlockProfileRate(0)
909 for _, test := range tests {
910 test.f(t)
911 }
912
913 t.Run("debug=1", func(t *testing.T) {
914 var w bytes.Buffer
915 Lookup("block").WriteTo(&w, 1)
916 prof := w.String()
917
918 if !strings.HasPrefix(prof, "--- contention:\ncycles/second=") {
919 t.Fatalf("Bad profile header:\n%v", prof)
920 }
921
922 if strings.HasSuffix(prof, "#\t0x0\n\n") {
923 t.Errorf("Useless 0 suffix:\n%v", prof)
924 }
925
926 for _, test := range tests {
927 if !regexp.MustCompile(strings.ReplaceAll(test.re, "\t", "\t+")).MatchString(prof) {
928 t.Errorf("Bad %v entry, expect:\n%v\ngot:\n%v", test.name, test.re, prof)
929 }
930 }
931 })
932
933 t.Run("proto", func(t *testing.T) {
934 // proto format
935 var w bytes.Buffer
936 Lookup("block").WriteTo(&w, 0)
937 p, err := profile.Parse(&w)
938 if err != nil {
939 t.Fatalf("failed to parse profile: %v", err)
940 }
941 t.Logf("parsed proto: %s", p)
942 if err := p.CheckValid(); err != nil {
943 t.Fatalf("invalid profile: %v", err)
944 }
945
946 stks := stacks(p)
947 for _, test := range tests {
948 if !containsStack(stks, test.stk) {
949 t.Errorf("No matching stack entry for %v, want %+v", test.name, test.stk)
950 }
951 }
952 })
953
954 }
955
956 func stacks(p *profile.Profile) (res [][]string) {
957 for _, s := range p.Sample {
958 var stk []string
959 for _, l := range s.Location {
960 for _, line := range l.Line {
961 stk = append(stk, line.Function.Name)
962 }
963 }
964 res = append(res, stk)
965 }
966 return res
967 }
968
969 func containsStack(got [][]string, want []string) bool {
970 for _, stk := range got {
971 if len(stk) < len(want) {
972 continue
973 }
974 for i, f := range want {
975 if f != stk[i] {
976 break
977 }
978 if i == len(want)-1 {
979 return true
980 }
981 }
982 }
983 return false
984 }
985
986 // awaitBlockedGoroutine spins on runtime.Gosched until a runtime stack dump
987 // shows a goroutine in the given state with a stack frame in
988 // runtime/pprof.<fName>.
989 func awaitBlockedGoroutine(t *testing.T, state, fName string) {
990 re := fmt.Sprintf(`(?m)^goroutine \d+ \[%s\]:\n(?:.+\n\t.+\n)*runtime/pprof\.%s`, regexp.QuoteMeta(state), fName)
991 r := regexp.MustCompile(re)
992
993 if deadline, ok := t.Deadline(); ok {
994 if d := time.Until(deadline); d > 1*time.Second {
995 timer := time.AfterFunc(d-1*time.Second, func() {
996 debug.SetTraceback("all")
997 panic(fmt.Sprintf("timed out waiting for %#q", re))
998 })
999 defer timer.Stop()
1000 }
1001 }
1002
1003 buf := make([]byte, 64<<10)
1004 for {
1005 runtime.Gosched()
1006 n := runtime.Stack(buf, true)
1007 if n == len(buf) {
1008 // Buffer wasn't large enough for a full goroutine dump.
1009 // Resize it and try again.
1010 buf = make([]byte, 2*len(buf))
1011 continue
1012 }
1013 if r.Match(buf[:n]) {
1014 return
1015 }
1016 }
1017 }
1018
1019 func blockChanRecv(t *testing.T) {
1020 c := make(chan bool)
1021 go func() {
1022 awaitBlockedGoroutine(t, "chan receive", "blockChanRecv")
1023 c <- true
1024 }()
1025 <-c
1026 }
1027
1028 func blockChanSend(t *testing.T) {
1029 c := make(chan bool)
1030 go func() {
1031 awaitBlockedGoroutine(t, "chan send", "blockChanSend")
1032 <-c
1033 }()
1034 c <- true
1035 }
1036
1037 func blockChanClose(t *testing.T) {
1038 c := make(chan bool)
1039 go func() {
1040 awaitBlockedGoroutine(t, "chan receive", "blockChanClose")
1041 close(c)
1042 }()
1043 <-c
1044 }
1045
1046 func blockSelectRecvAsync(t *testing.T) {
1047 const numTries = 3
1048 c := make(chan bool, 1)
1049 c2 := make(chan bool, 1)
1050 go func() {
1051 for i := 0; i < numTries; i++ {
1052 awaitBlockedGoroutine(t, "select", "blockSelectRecvAsync")
1053 c <- true
1054 }
1055 }()
1056 for i := 0; i < numTries; i++ {
1057 select {
1058 case <-c:
1059 case <-c2:
1060 }
1061 }
1062 }
1063
1064 func blockSelectSendSync(t *testing.T) {
1065 c := make(chan bool)
1066 c2 := make(chan bool)
1067 go func() {
1068 awaitBlockedGoroutine(t, "select", "blockSelectSendSync")
1069 <-c
1070 }()
1071 select {
1072 case c <- true:
1073 case c2 <- true:
1074 }
1075 }
1076
1077 func blockMutex(t *testing.T) {
1078 var mu sync.Mutex
1079 mu.Lock()
1080 go func() {
1081 awaitBlockedGoroutine(t, "semacquire", "blockMutex")
1082 mu.Unlock()
1083 }()
1084 // Note: Unlock releases mu before recording the mutex event,
1085 // so it's theoretically possible for this to proceed and
1086 // capture the profile before the event is recorded. As long
1087 // as this is blocked before the unlock happens, it's okay.
1088 mu.Lock()
1089 }
1090
1091 func blockCond(t *testing.T) {
1092 var mu sync.Mutex
1093 c := sync.NewCond(&mu)
1094 mu.Lock()
1095 go func() {
1096 awaitBlockedGoroutine(t, "sync.Cond.Wait", "blockCond")
1097 mu.Lock()
1098 c.Signal()
1099 mu.Unlock()
1100 }()
1101 c.Wait()
1102 mu.Unlock()
1103 }
1104
1105 // See http://golang.org/cl/299991.
1106 func TestBlockProfileBias(t *testing.T) {
1107 rate := int(1000) // arbitrary value
1108 runtime.SetBlockProfileRate(rate)
1109 defer runtime.SetBlockProfileRate(0)
1110
1111 // simulate blocking events
1112 blockFrequentShort(rate)
1113 blockInfrequentLong(rate)
1114
1115 var w bytes.Buffer
1116 Lookup("block").WriteTo(&w, 0)
1117 p, err := profile.Parse(&w)
1118 if err != nil {
1119 t.Fatalf("failed to parse profile: %v", err)
1120 }
1121 t.Logf("parsed proto: %s", p)
1122
1123 il := float64(-1) // blockInfrequentLong duration
1124 fs := float64(-1) // blockFrequentShort duration
1125 for _, s := range p.Sample {
1126 for _, l := range s.Location {
1127 for _, line := range l.Line {
1128 if len(s.Value) < 2 {
1129 t.Fatal("block profile has less than 2 sample types")
1130 }
1131
1132 if line.Function.Name == "runtime/pprof.blockInfrequentLong" {
1133 il = float64(s.Value[1])
1134 } else if line.Function.Name == "runtime/pprof.blockFrequentShort" {
1135 fs = float64(s.Value[1])
1136 }
1137 }
1138 }
1139 }
1140 if il == -1 || fs == -1 {
1141 t.Fatal("block profile is missing expected functions")
1142 }
1143
1144 // stddev of bias from 100 runs on local machine multiplied by 10x
1145 const threshold = 0.2
1146 if bias := (il - fs) / il; math.Abs(bias) > threshold {
1147 t.Fatalf("bias: abs(%f) > %f", bias, threshold)
1148 } else {
1149 t.Logf("bias: abs(%f) < %f", bias, threshold)
1150 }
1151 }
1152
1153 // blockFrequentShort produces 100000 block events with an average duration of
1154 // rate / 10.
1155 func blockFrequentShort(rate int) {
1156 for i := 0; i < 100000; i++ {
1157 blockevent(int64(rate/10), 1)
1158 }
1159 }
1160
1161 // blockFrequentShort produces 10000 block events with an average duration of
1162 // rate.
1163 func blockInfrequentLong(rate int) {
1164 for i := 0; i < 10000; i++ {
1165 blockevent(int64(rate), 1)
1166 }
1167 }
1168
1169 // Used by TestBlockProfileBias.
1170 //go:linkname blockevent runtime.blockevent
1171 func blockevent(cycles int64, skip int)
1172
1173 func TestMutexProfile(t *testing.T) {
1174 // Generate mutex profile
1175
1176 old := runtime.SetMutexProfileFraction(1)
1177 defer runtime.SetMutexProfileFraction(old)
1178 if old != 0 {
1179 t.Fatalf("need MutexProfileRate 0, got %d", old)
1180 }
1181
1182 blockMutex(t)
1183
1184 t.Run("debug=1", func(t *testing.T) {
1185 var w bytes.Buffer
1186 Lookup("mutex").WriteTo(&w, 1)
1187 prof := w.String()
1188 t.Logf("received profile: %v", prof)
1189
1190 if !strings.HasPrefix(prof, "--- mutex:\ncycles/second=") {
1191 t.Errorf("Bad profile header:\n%v", prof)
1192 }
1193 prof = strings.Trim(prof, "\n")
1194 lines := strings.Split(prof, "\n")
1195 if len(lines) != 6 {
1196 t.Errorf("expected 6 lines, got %d %q\n%s", len(lines), prof, prof)
1197 }
1198 if len(lines) < 6 {
1199 return
1200 }
1201 // checking that the line is like "35258904 1 @ 0x48288d 0x47cd28 0x458931"
1202 r2 := `^\d+ \d+ @(?: 0x[[:xdigit:]]+)+`
1203 //r2 := "^[0-9]+ 1 @ 0x[0-9a-f x]+$"
1204 if ok, err := regexp.MatchString(r2, lines[3]); err != nil || !ok {
1205 t.Errorf("%q didn't match %q", lines[3], r2)
1206 }
1207 if runtime.Compiler != "gccgo" {
1208 r3 := "^#.*pprof.blockMutex.*$"
1209 if ok, err := regexp.MatchString(r3, lines[5]); err != nil || !ok {
1210 t.Errorf("%q didn't match %q", lines[5], r3)
1211 }
1212 }
1213 t.Logf(prof)
1214 })
1215 t.Run("proto", func(t *testing.T) {
1216 // proto format
1217 var w bytes.Buffer
1218 Lookup("mutex").WriteTo(&w, 0)
1219 p, err := profile.Parse(&w)
1220 if err != nil {
1221 t.Fatalf("failed to parse profile: %v", err)
1222 }
1223 t.Logf("parsed proto: %s", p)
1224 if err := p.CheckValid(); err != nil {
1225 t.Fatalf("invalid profile: %v", err)
1226 }
1227
1228 stks := stacks(p)
1229 for _, want := range [][]string{
1230 // {"sync.(*Mutex).Unlock", "runtime/pprof.blockMutex.func1"},
1231 {"sync.Mutex.Unlock", "runtime/pprof.blockMutex..func1"},
1232 } {
1233 if !containsStack(stks, want) {
1234 t.Errorf("No matching stack entry for %+v", want)
1235 }
1236 }
1237 })
1238 }
1239
1240 func func1(c chan int) { <-c }
1241 func func2(c chan int) { <-c }
1242 func func3(c chan int) { <-c }
1243 func func4(c chan int) { <-c }
1244
1245 func TestGoroutineCounts(t *testing.T) {
1246 if runtime.Compiler == "gccgo" {
1247 t.Skip("goroutine stacks not supported on gccgo")
1248 }
1249
1250 // Setting GOMAXPROCS to 1 ensures we can force all goroutines to the
1251 // desired blocking point.
1252 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
1253
1254 c := make(chan int)
1255 for i := 0; i < 100; i++ {
1256 switch {
1257 case i%10 == 0:
1258 go func1(c)
1259 case i%2 == 0:
1260 go func2(c)
1261 default:
1262 go func3(c)
1263 }
1264 // Let goroutines block on channel
1265 for j := 0; j < 5; j++ {
1266 runtime.Gosched()
1267 }
1268 }
1269 ctx := context.Background()
1270
1271 // ... and again, with labels this time (just with fewer iterations to keep
1272 // sorting deterministic).
1273 Do(ctx, Labels("label", "value"), func(context.Context) {
1274 for i := 0; i < 89; i++ {
1275 switch {
1276 case i%10 == 0:
1277 go func1(c)
1278 case i%2 == 0:
1279 go func2(c)
1280 default:
1281 go func3(c)
1282 }
1283 // Let goroutines block on channel
1284 for j := 0; j < 5; j++ {
1285 runtime.Gosched()
1286 }
1287 }
1288 })
1289
1290 var w bytes.Buffer
1291 goroutineProf := Lookup("goroutine")
1292
1293 // Check debug profile
1294 goroutineProf.WriteTo(&w, 1)
1295 prof := w.String()
1296
1297 labels := labelMap{"label": "value"}
1298 labelStr := "\n# labels: " + labels.String()
1299 if !containsInOrder(prof, "\n50 @ ", "\n44 @", labelStr,
1300 "\n40 @", "\n36 @", labelStr, "\n10 @", "\n9 @", labelStr, "\n1 @") {
1301 t.Errorf("expected sorted goroutine counts with Labels:\n%s", prof)
1302 }
1303
1304 // Check proto profile
1305 w.Reset()
1306 goroutineProf.WriteTo(&w, 0)
1307 p, err := profile.Parse(&w)
1308 if err != nil {
1309 t.Errorf("error parsing protobuf profile: %v", err)
1310 }
1311 if err := p.CheckValid(); err != nil {
1312 t.Errorf("protobuf profile is invalid: %v", err)
1313 }
1314 expectedLabels := map[int64]map[string]string{
1315 50: map[string]string{},
1316 44: map[string]string{"label": "value"},
1317 40: map[string]string{},
1318 36: map[string]string{"label": "value"},
1319 10: map[string]string{},
1320 9: map[string]string{"label": "value"},
1321 1: map[string]string{},
1322 }
1323 if !containsCountsLabels(p, expectedLabels) {
1324 t.Errorf("expected count profile to contain goroutines with counts and labels %v, got %v",
1325 expectedLabels, p)
1326 }
1327
1328 close(c)
1329
1330 time.Sleep(10 * time.Millisecond) // let goroutines exit
1331 }
1332
1333 func containsInOrder(s string, all ...string) bool {
1334 for _, t := range all {
1335 var ok bool
1336 if _, s, ok = strings.Cut(s, t); !ok {
1337 return false
1338 }
1339 }
1340 return true
1341 }
1342
1343 func containsCountsLabels(prof *profile.Profile, countLabels map[int64]map[string]string) bool {
1344 m := make(map[int64]int)
1345 type nkey struct {
1346 count int64
1347 key, val string
1348 }
1349 n := make(map[nkey]int)
1350 for c, kv := range countLabels {
1351 m[c]++
1352 for k, v := range kv {
1353 n[nkey{
1354 count: c,
1355 key: k,
1356 val: v,
1357 }]++
1358
1359 }
1360 }
1361 for _, s := range prof.Sample {
1362 // The count is the single value in the sample
1363 if len(s.Value) != 1 {
1364 return false
1365 }
1366 m[s.Value[0]]--
1367 for k, vs := range s.Label {
1368 for _, v := range vs {
1369 n[nkey{
1370 count: s.Value[0],
1371 key: k,
1372 val: v,
1373 }]--
1374 }
1375 }
1376 }
1377 for _, n := range m {
1378 if n > 0 {
1379 return false
1380 }
1381 }
1382 for _, ncnt := range n {
1383 if ncnt != 0 {
1384 return false
1385 }
1386 }
1387 return true
1388 }
1389
1390 var emptyCallStackTestRun int64
1391
1392 // Issue 18836.
1393 func TestEmptyCallStack(t *testing.T) {
1394 name := fmt.Sprintf("test18836_%d", emptyCallStackTestRun)
1395 emptyCallStackTestRun++
1396
1397 t.Parallel()
1398 var buf bytes.Buffer
1399 p := NewProfile(name)
1400
1401 p.Add("foo", 47674)
1402 p.WriteTo(&buf, 1)
1403 p.Remove("foo")
1404 got := buf.String()
1405 prefix := name + " profile: total 1\n"
1406 if !strings.HasPrefix(got, prefix) {
1407 t.Fatalf("got:\n\t%q\nwant prefix:\n\t%q\n", got, prefix)
1408 }
1409 lostevent := "lostProfileEvent"
1410 if !strings.Contains(got, lostevent) {
1411 t.Fatalf("got:\n\t%q\ndoes not contain:\n\t%q\n", got, lostevent)
1412 }
1413 }
1414
1415 // stackContainsLabeled takes a spec like funcname;key=value and matches if the stack has that key
1416 // and value and has funcname somewhere in the stack.
1417 func stackContainsLabeled(spec string, count uintptr, stk []*profile.Location, labels map[string][]string) bool {
1418 base, kv, ok := strings.Cut(spec, ";")
1419 if !ok {
1420 panic("no semicolon in key/value spec")
1421 }
1422 k, v, ok := strings.Cut(kv, "=")
1423 if !ok {
1424 panic("missing = in key/value spec")
1425 }
1426 if !contains(labels[k], v) {
1427 return false
1428 }
1429 return stackContains(base, count, stk, labels)
1430 }
1431
1432 func TestCPUProfileLabel(t *testing.T) {
1433 matches := matchAndAvoidStacks(stackContainsLabeled, []string{"pprof.cpuHogger;key=value"}, avoidFunctions())
1434 testCPUProfile(t, matches, func(dur time.Duration) {
1435 Do(context.Background(), Labels("key", "value"), func(context.Context) {
1436 cpuHogger(cpuHog1, &salt1, dur)
1437 })
1438 })
1439 }
1440
1441 func TestLabelRace(t *testing.T) {
1442 // Test the race detector annotations for synchronization
1443 // between settings labels and consuming them from the
1444 // profile.
1445 matches := matchAndAvoidStacks(stackContainsLabeled, []string{"pprof.cpuHogger;key=value"}, nil)
1446 testCPUProfile(t, matches, func(dur time.Duration) {
1447 start := time.Now()
1448 var wg sync.WaitGroup
1449 for time.Since(start) < dur {
1450 var salts [10]int
1451 for i := 0; i < 10; i++ {
1452 wg.Add(1)
1453 go func(j int) {
1454 Do(context.Background(), Labels("key", "value"), func(context.Context) {
1455 cpuHogger(cpuHog1, &salts[j], time.Millisecond)
1456 })
1457 wg.Done()
1458 }(i)
1459 }
1460 wg.Wait()
1461 }
1462 })
1463 }
1464
1465 // TestLabelSystemstack makes sure CPU profiler samples of goroutines running
1466 // on systemstack include the correct pprof labels. See issue #48577
1467 func TestLabelSystemstack(t *testing.T) {
1468 // Grab and re-set the initial value before continuing to ensure
1469 // GOGC doesn't actually change following the test.
1470 gogc := debug.SetGCPercent(100)
1471 debug.SetGCPercent(gogc)
1472
1473 matches := matchAndAvoidStacks(stackContainsLabeled, []string{"runtime.systemstack;key=value"}, avoidFunctions())
1474 p := testCPUProfile(t, matches, func(dur time.Duration) {
1475 Do(context.Background(), Labels("key", "value"), func(ctx context.Context) {
1476 parallelLabelHog(ctx, dur, gogc)
1477 })
1478 })
1479
1480 // Two conditions to check:
1481 // * labelHog should always be labeled.
1482 // * The label should _only_ appear on labelHog and the Do call above.
1483 for _, s := range p.Sample {
1484 isLabeled := s.Label != nil && contains(s.Label["key"], "value")
1485 var (
1486 mayBeLabeled bool
1487 mustBeLabeled bool
1488 mustNotBeLabeled bool
1489 )
1490 for _, loc := range s.Location {
1491 for _, l := range loc.Line {
1492 switch l.Function.Name {
1493 case "runtime/pprof.labelHog", "runtime/pprof.parallelLabelHog", "runtime/pprof.parallelLabelHog.func1":
1494 mustBeLabeled = true
1495 case "runtime/pprof.Do":
1496 // Do sets the labels, so samples may
1497 // or may not be labeled depending on
1498 // which part of the function they are
1499 // at.
1500 mayBeLabeled = true
1501 case "runtime.bgsweep", "runtime.bgscavenge", "runtime.forcegchelper", "runtime.gcBgMarkWorker", "runtime.runfinq", "runtime.sysmon":
1502 // Runtime system goroutines or threads
1503 // (such as those identified by
1504 // runtime.isSystemGoroutine). These
1505 // should never be labeled.
1506 mustNotBeLabeled = true
1507 case "gogo", "gosave_systemstack_switch", "racecall":
1508 // These are context switch/race
1509 // critical that we can't do a full
1510 // traceback from. Typically this would
1511 // be covered by the runtime check
1512 // below, but these symbols don't have
1513 // the package name.
1514 mayBeLabeled = true
1515 }
1516
1517 if l.Function.Name == "" || strings.HasPrefix(l.Function.Name, "runtime.") || strings.HasPrefix(l.Function.Name, "runtime_") {
1518 // There are many places in the runtime
1519 // where we can't do a full traceback.
1520 // Ideally we'd list them all, but
1521 // barring that allow anything in the
1522 // runtime, unless explicitly excluded
1523 // above.
1524 mayBeLabeled = true
1525 }
1526 }
1527 }
1528 if mustNotBeLabeled {
1529 // If this must not be labeled, then mayBeLabeled hints
1530 // are not relevant.
1531 mayBeLabeled = false
1532 }
1533 if mustBeLabeled && !isLabeled {
1534 var buf bytes.Buffer
1535 fprintStack(&buf, s.Location)
1536 t.Errorf("Sample labeled got false want true: %s", buf.String())
1537 }
1538 if mustNotBeLabeled && isLabeled {
1539 var buf bytes.Buffer
1540 fprintStack(&buf, s.Location)
1541 t.Errorf("Sample labeled got true want false: %s", buf.String())
1542 }
1543 if isLabeled && !(mayBeLabeled || mustBeLabeled) {
1544 var buf bytes.Buffer
1545 fprintStack(&buf, s.Location)
1546 t.Errorf("Sample labeled got true want false: %s", buf.String())
1547 }
1548 }
1549 }
1550
1551 // labelHog is designed to burn CPU time in a way that a high number of CPU
1552 // samples end up running on systemstack.
1553 func labelHog(stop chan struct{}, gogc int) {
1554 // Regression test for issue 50032. We must give GC an opportunity to
1555 // be initially triggered by a labelled goroutine.
1556 runtime.GC()
1557
1558 for i := 0; ; i++ {
1559 select {
1560 case <-stop:
1561 return
1562 default:
1563 debug.SetGCPercent(gogc)
1564 }
1565 }
1566 }
1567
1568 // parallelLabelHog runs GOMAXPROCS goroutines running labelHog.
1569 func parallelLabelHog(ctx context.Context, dur time.Duration, gogc int) {
1570 var wg sync.WaitGroup
1571 stop := make(chan struct{})
1572 for i := 0; i < runtime.GOMAXPROCS(0); i++ {
1573 wg.Add(1)
1574 go func() {
1575 defer wg.Done()
1576 labelHog(stop, gogc)
1577 }()
1578 }
1579
1580 time.Sleep(dur)
1581 close(stop)
1582 wg.Wait()
1583 }
1584
1585 // Check that there is no deadlock when the program receives SIGPROF while in
1586 // 64bit atomics' critical section. Used to happen on mips{,le}. See #20146.
1587 func TestAtomicLoadStore64(t *testing.T) {
1588 f, err := os.CreateTemp("", "profatomic")
1589 if err != nil {
1590 t.Fatalf("TempFile: %v", err)
1591 }
1592 defer os.Remove(f.Name())
1593 defer f.Close()
1594
1595 if err := StartCPUProfile(f); err != nil {
1596 t.Fatal(err)
1597 }
1598 defer StopCPUProfile()
1599
1600 var flag uint64
1601 done := make(chan bool, 1)
1602
1603 go func() {
1604 for atomic.LoadUint64(&flag) == 0 {
1605 runtime.Gosched()
1606 }
1607 done <- true
1608 }()
1609 time.Sleep(50 * time.Millisecond)
1610 atomic.StoreUint64(&flag, 1)
1611 <-done
1612 }
1613
1614 func TestTracebackAll(t *testing.T) {
1615 // With gccgo, if a profiling signal arrives at the wrong time
1616 // during traceback, it may crash or hang. See issue #29448.
1617 f, err := os.CreateTemp("", "proftraceback")
1618 if err != nil {
1619 t.Fatalf("TempFile: %v", err)
1620 }
1621 defer os.Remove(f.Name())
1622 defer f.Close()
1623
1624 if err := StartCPUProfile(f); err != nil {
1625 t.Fatal(err)
1626 }
1627 defer StopCPUProfile()
1628
1629 ch := make(chan int)
1630 defer close(ch)
1631
1632 count := 10
1633 for i := 0; i < count; i++ {
1634 go func() {
1635 <-ch // block
1636 }()
1637 }
1638
1639 N := 10000
1640 if testing.Short() {
1641 N = 500
1642 }
1643 buf := make([]byte, 10*1024)
1644 for i := 0; i < N; i++ {
1645 runtime.Stack(buf, true)
1646 }
1647 }
1648
1649 // TestTryAdd tests the cases that are hard to test with real program execution.
1650 //
1651 // For example, the current go compilers may not always inline functions
1652 // involved in recursion but that may not be true in the future compilers. This
1653 // tests such cases by using fake call sequences and forcing the profile build
1654 // utilizing translateCPUProfile defined in proto_test.go
1655 func TestTryAdd(t *testing.T) {
1656 if _, found := findInlinedCall(inlinedCallerDump, 4<<10); !found {
1657 t.Skip("Can't determine whether anything was inlined into inlinedCallerDump.")
1658 }
1659
1660 // inlinedCallerDump
1661 // inlinedCalleeDump
1662 pcs := make([]uintptr, 2)
1663 inlinedCallerDump(pcs)
1664 inlinedCallerStack := make([]uint64, 2)
1665 for i := range pcs {
1666 inlinedCallerStack[i] = uint64(pcs[i])
1667 }
1668
1669 if _, found := findInlinedCall(recursionChainBottom, 4<<10); !found {
1670 t.Skip("Can't determine whether anything was inlined into recursionChainBottom.")
1671 }
1672
1673 // recursionChainTop
1674 // recursionChainMiddle
1675 // recursionChainBottom
1676 // recursionChainTop
1677 // recursionChainMiddle
1678 // recursionChainBottom
1679 pcs = make([]uintptr, 6)
1680 recursionChainTop(1, pcs)
1681 recursionStack := make([]uint64, len(pcs))
1682 for i := range pcs {
1683 recursionStack[i] = uint64(pcs[i])
1684 }
1685
1686 period := int64(2000 * 1000) // 1/500*1e9 nanosec.
1687
1688 testCases := []struct {
1689 name string
1690 input []uint64 // following the input format assumed by profileBuilder.addCPUData.
1691 count int // number of records in input.
1692 wantLocs [][]string // ordered location entries with function names.
1693 wantSamples []*profile.Sample // ordered samples, we care only about Value and the profile location IDs.
1694 }{{
1695 // Sanity test for a normal, complete stack trace.
1696 name: "full_stack_trace",
1697 input: []uint64{
1698 3, 0, 500, // hz = 500. Must match the period.
1699 5, 0, 50, inlinedCallerStack[0], inlinedCallerStack[1],
1700 },
1701 count: 2,
1702 wantLocs: [][]string{
1703 {"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"},
1704 },
1705 wantSamples: []*profile.Sample{
1706 {Value: []int64{50, 50 * period}, Location: []*profile.Location{{ID: 1}}},
1707 },
1708 }, {
1709 name: "bug35538",
1710 input: []uint64{
1711 3, 0, 500, // hz = 500. Must match the period.
1712 // Fake frame: tryAdd will have inlinedCallerDump
1713 // (stack[1]) on the deck when it encounters the next
1714 // inline function. It should accept this.
1715 7, 0, 10, inlinedCallerStack[0], inlinedCallerStack[1], inlinedCallerStack[0], inlinedCallerStack[1],
1716 5, 0, 20, inlinedCallerStack[0], inlinedCallerStack[1],
1717 },
1718 count: 3,
1719 wantLocs: [][]string{{"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"}},
1720 wantSamples: []*profile.Sample{
1721 {Value: []int64{10, 10 * period}, Location: []*profile.Location{{ID: 1}, {ID: 1}}},
1722 {Value: []int64{20, 20 * period}, Location: []*profile.Location{{ID: 1}}},
1723 },
1724 }, {
1725 name: "bug38096",
1726 input: []uint64{
1727 3, 0, 500, // hz = 500. Must match the period.
1728 // count (data[2]) == 0 && len(stk) == 1 is an overflow
1729 // entry. The "stk" entry is actually the count.
1730 4, 0, 0, 4242,
1731 },
1732 count: 2,
1733 wantLocs: [][]string{{"runtime/pprof.lostProfileEvent"}},
1734 wantSamples: []*profile.Sample{
1735 {Value: []int64{4242, 4242 * period}, Location: []*profile.Location{{ID: 1}}},
1736 },
1737 }, {
1738 // If a function is directly called recursively then it must
1739 // not be inlined in the caller.
1740 //
1741 // N.B. We're generating an impossible profile here, with a
1742 // recursive inlineCalleeDump call. This is simulating a non-Go
1743 // function that looks like an inlined Go function other than
1744 // its recursive property. See pcDeck.tryAdd.
1745 name: "directly_recursive_func_is_not_inlined",
1746 input: []uint64{
1747 3, 0, 500, // hz = 500. Must match the period.
1748 5, 0, 30, inlinedCallerStack[0], inlinedCallerStack[0],
1749 4, 0, 40, inlinedCallerStack[0],
1750 },
1751 count: 3,
1752 // inlinedCallerDump shows up here because
1753 // runtime_expandFinalInlineFrame adds it to the stack frame.
1754 wantLocs: [][]string{{"runtime/pprof.inlinedCalleeDump"}, {"runtime/pprof.inlinedCallerDump"}},
1755 wantSamples: []*profile.Sample{
1756 {Value: []int64{30, 30 * period}, Location: []*profile.Location{{ID: 1}, {ID: 1}, {ID: 2}}},
1757 {Value: []int64{40, 40 * period}, Location: []*profile.Location{{ID: 1}, {ID: 2}}},
1758 },
1759 }, {
1760 name: "recursion_chain_inline",
1761 input: []uint64{
1762 3, 0, 500, // hz = 500. Must match the period.
1763 9, 0, 10, recursionStack[0], recursionStack[1], recursionStack[2], recursionStack[3], recursionStack[4], recursionStack[5],
1764 },
1765 count: 2,
1766 wantLocs: [][]string{
1767 {"runtime/pprof.recursionChainBottom"},
1768 {
1769 "runtime/pprof.recursionChainMiddle",
1770 "runtime/pprof.recursionChainTop",
1771 "runtime/pprof.recursionChainBottom",
1772 },
1773 {
1774 "runtime/pprof.recursionChainMiddle",
1775 "runtime/pprof.recursionChainTop",
1776 "runtime/pprof.TestTryAdd", // inlined into the test.
1777 },
1778 },
1779 wantSamples: []*profile.Sample{
1780 {Value: []int64{10, 10 * period}, Location: []*profile.Location{{ID: 1}, {ID: 2}, {ID: 3}}},
1781 },
1782 }, {
1783 name: "truncated_stack_trace_later",
1784 input: []uint64{
1785 3, 0, 500, // hz = 500. Must match the period.
1786 5, 0, 50, inlinedCallerStack[0], inlinedCallerStack[1],
1787 4, 0, 60, inlinedCallerStack[0],
1788 },
1789 count: 3,
1790 wantLocs: [][]string{{"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"}},
1791 wantSamples: []*profile.Sample{
1792 {Value: []int64{50, 50 * period}, Location: []*profile.Location{{ID: 1}}},
1793 {Value: []int64{60, 60 * period}, Location: []*profile.Location{{ID: 1}}},
1794 },
1795 }, {
1796 name: "truncated_stack_trace_first",
1797 input: []uint64{
1798 3, 0, 500, // hz = 500. Must match the period.
1799 4, 0, 70, inlinedCallerStack[0],
1800 5, 0, 80, inlinedCallerStack[0], inlinedCallerStack[1],
1801 },
1802 count: 3,
1803 wantLocs: [][]string{{"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"}},
1804 wantSamples: []*profile.Sample{
1805 {Value: []int64{70, 70 * period}, Location: []*profile.Location{{ID: 1}}},
1806 {Value: []int64{80, 80 * period}, Location: []*profile.Location{{ID: 1}}},
1807 },
1808 }, {
1809 // We can recover the inlined caller from a truncated stack.
1810 name: "truncated_stack_trace_only",
1811 input: []uint64{
1812 3, 0, 500, // hz = 500. Must match the period.
1813 4, 0, 70, inlinedCallerStack[0],
1814 },
1815 count: 2,
1816 wantLocs: [][]string{{"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"}},
1817 wantSamples: []*profile.Sample{
1818 {Value: []int64{70, 70 * period}, Location: []*profile.Location{{ID: 1}}},
1819 },
1820 }, {
1821 // The same location is used for duplicated stacks.
1822 name: "truncated_stack_trace_twice",
1823 input: []uint64{
1824 3, 0, 500, // hz = 500. Must match the period.
1825 4, 0, 70, inlinedCallerStack[0],
1826 // Fake frame: add a fake call to
1827 // inlinedCallerDump to prevent this sample
1828 // from getting merged into above.
1829 5, 0, 80, inlinedCallerStack[1], inlinedCallerStack[0],
1830 },
1831 count: 3,
1832 wantLocs: [][]string{
1833 {"runtime/pprof.inlinedCalleeDump", "runtime/pprof.inlinedCallerDump"},
1834 {"runtime/pprof.inlinedCallerDump"},
1835 },
1836 wantSamples: []*profile.Sample{
1837 {Value: []int64{70, 70 * period}, Location: []*profile.Location{{ID: 1}}},
1838 {Value: []int64{80, 80 * period}, Location: []*profile.Location{{ID: 2}, {ID: 1}}},
1839 },
1840 }}
1841
1842 for _, tc := range testCases {
1843 t.Run(tc.name, func(t *testing.T) {
1844 p, err := translateCPUProfile(tc.input, tc.count)
1845 if err != nil {
1846 t.Fatalf("translating profile: %v", err)
1847 }
1848 t.Logf("Profile: %v\n", p)
1849
1850 // One location entry with all inlined functions.
1851 var gotLoc [][]string
1852 for _, loc := range p.Location {
1853 var names []string
1854 for _, line := range loc.Line {
1855 names = append(names, line.Function.Name)
1856 }
1857 gotLoc = append(gotLoc, names)
1858 }
1859 if got, want := fmtJSON(gotLoc), fmtJSON(tc.wantLocs); got != want {
1860 t.Errorf("Got Location = %+v\n\twant %+v", got, want)
1861 }
1862 // All samples should point to one location.
1863 var gotSamples []*profile.Sample
1864 for _, sample := range p.Sample {
1865 var locs []*profile.Location
1866 for _, loc := range sample.Location {
1867 locs = append(locs, &profile.Location{ID: loc.ID})
1868 }
1869 gotSamples = append(gotSamples, &profile.Sample{Value: sample.Value, Location: locs})
1870 }
1871 if got, want := fmtJSON(gotSamples), fmtJSON(tc.wantSamples); got != want {
1872 t.Errorf("Got Samples = %+v\n\twant %+v", got, want)
1873 }
1874 })
1875 }
1876 }
1877
1878 func TestTimeVDSO(t *testing.T) {
1879 // Test that time functions have the right stack trace. In particular,
1880 // it shouldn't be recursive.
1881
1882 if runtime.GOOS == "android" {
1883 // Flaky on Android, issue 48655. VDSO may not be enabled.
1884 testenv.SkipFlaky(t, 48655)
1885 }
1886
1887 matches := matchAndAvoidStacks(stackContains, []string{"time.now"}, avoidFunctions())
1888 p := testCPUProfile(t, matches, func(dur time.Duration) {
1889 t0 := time.Now()
1890 for {
1891 t := time.Now()
1892 if t.Sub(t0) >= dur {
1893 return
1894 }
1895 }
1896 })
1897
1898 // Check for recursive time.now sample.
1899 for _, sample := range p.Sample {
1900 var seenNow bool
1901 for _, loc := range sample.Location {
1902 for _, line := range loc.Line {
1903 if line.Function.Name == "time.now" {
1904 if seenNow {
1905 t.Fatalf("unexpected recursive time.now")
1906 }
1907 seenNow = true
1908 }
1909 }
1910 }
1911 }
1912 }