Debian Codegraph @

libgo/go/runtime/stack_test.go

raw
1 // Copyright 2012 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 runtime_test
6
7 import (
8 "bytes"
9 "fmt"
10 "reflect"
11 "regexp"
12 . "runtime"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "testing"
17 "time"
18 _ "unsafe" // for go:linkname
19 )
20
21 // TestStackMem measures per-thread stack segment cache behavior.
22 // The test consumed up to 500MB in the past.
23 func TestStackMem(t *testing.T) {
24 const (
25 BatchSize = 32
26 BatchCount = 256
27 ArraySize = 1024
28 RecursionDepth = 128
29 )
30 if testing.Short() {
31 return
32 }
33 defer GOMAXPROCS(GOMAXPROCS(BatchSize))
34 s0 := new(MemStats)
35 ReadMemStats(s0)
36 for b := 0; b < BatchCount; b++ {
37 c := make(chan bool, BatchSize)
38 for i := 0; i < BatchSize; i++ {
39 go func() {
40 var f func(k int, a [ArraySize]byte)
41 f = func(k int, a [ArraySize]byte) {
42 if k == 0 {
43 time.Sleep(time.Millisecond)
44 return
45 }
46 f(k-1, a)
47 }
48 f(RecursionDepth, [ArraySize]byte{})
49 c <- true
50 }()
51 }
52 for i := 0; i < BatchSize; i++ {
53 <-c
54 }
55
56 // The goroutines have signaled via c that they are ready to exit.
57 // Give them a chance to exit by sleeping. If we don't wait, we
58 // might not reuse them on the next batch.
59 time.Sleep(10 * time.Millisecond)
60 }
61 s1 := new(MemStats)
62 ReadMemStats(s1)
63 consumed := int64(s1.StackSys - s0.StackSys)
64 t.Logf("Consumed %vMB for stack mem", consumed>>20)
65 estimate := int64(8 * BatchSize * ArraySize * RecursionDepth) // 8 is to reduce flakiness.
66 if consumed > estimate {
67 t.Fatalf("Stack mem: want %v, got %v", estimate, consumed)
68 }
69 // Due to broken stack memory accounting (https://golang.org/issue/7468),
70 // StackInuse can decrease during function execution, so we cast the values to int64.
71 inuse := int64(s1.StackInuse) - int64(s0.StackInuse)
72 t.Logf("Inuse %vMB for stack mem", inuse>>20)
73 if inuse > 4<<20 {
74 t.Fatalf("Stack inuse: want %v, got %v", 4<<20, inuse)
75 }
76 }
77
78 // Test stack growing in different contexts.
79 func TestStackGrowth(t *testing.T) {
80 if *flagQuick {
81 t.Skip("-quick")
82 }
83
84 t.Parallel()
85
86 var wg sync.WaitGroup
87
88 // in a normal goroutine
89 var growDuration time.Duration // For debugging failures
90 wg.Add(1)
91 go func() {
92 defer wg.Done()
93 start := time.Now()
94 growStack(nil)
95 growDuration = time.Since(start)
96 }()
97 wg.Wait()
98 t.Log("first growStack took", growDuration)
99
100 // in locked goroutine
101 wg.Add(1)
102 go func() {
103 defer wg.Done()
104 LockOSThread()
105 growStack(nil)
106 UnlockOSThread()
107 }()
108 wg.Wait()
109
110 // in finalizer
111 if Compiler == "gccgo" && !*Pusestackmaps {
112 // This test is flaky for gccgo's
113 // conservative stack scanning.
114 return
115 }
116 var finalizerStart time.Time
117 var started, progress uint32
118 wg.Add(1)
119 s := new(string) // Must be of a type that avoids the tiny allocator, or else the finalizer might not run.
120 SetFinalizer(s, func(ss *string) {
121 defer wg.Done()
122 finalizerStart = time.Now()
123 atomic.StoreUint32(&started, 1)
124 growStack(&progress)
125 })
126 setFinalizerTime := time.Now()
127 s = nil
128
129 if d, ok := t.Deadline(); ok {
130 // Pad the timeout by an arbitrary 5% to give the AfterFunc time to run.
131 timeout := time.Until(d) * 19 / 20
132 timer := time.AfterFunc(timeout, func() {
133 // Panic — instead of calling t.Error and returning from the test — so
134 // that we get a useful goroutine dump if the test times out, especially
135 // if GOTRACEBACK=system or GOTRACEBACK=crash is set.
136 if atomic.LoadUint32(&started) == 0 {
137 panic("finalizer did not start")
138 } else {
139 panic(fmt.Sprintf("finalizer started %s ago (%s after registration) and ran %d iterations, but did not return", time.Since(finalizerStart), finalizerStart.Sub(setFinalizerTime), atomic.LoadUint32(&progress)))
140 }
141 })
142 defer timer.Stop()
143 }
144
145 GC()
146 wg.Wait()
147 t.Logf("finalizer started after %s and ran %d iterations in %v", finalizerStart.Sub(setFinalizerTime), atomic.LoadUint32(&progress), time.Since(finalizerStart))
148 }
149
150 // ... and in init
151 //func init() {
152 // growStack()
153 //}
154
155 func growStack(progress *uint32) {
156 n := 1 << 10
157 if testing.Short() {
158 n = 1 << 8
159 }
160 for i := 0; i < n; i++ {
161 x := 0
162 growStackIter(&x, i)
163 if x != i+1 {
164 panic("stack is corrupted")
165 }
166 if progress != nil {
167 atomic.StoreUint32(progress, uint32(i))
168 }
169 }
170 GC()
171 }
172
173 // This function is not an anonymous func, so that the compiler can do escape
174 // analysis and place x on stack (and subsequently stack growth update the pointer).
175 func growStackIter(p *int, n int) {
176 if n == 0 {
177 *p = n + 1
178 GC()
179 return
180 }
181 *p = n + 1
182 x := 0
183 growStackIter(&x, n-1)
184 if x != n {
185 panic("stack is corrupted")
186 }
187 }
188
189 func TestStackGrowthCallback(t *testing.T) {
190 t.Parallel()
191 var wg sync.WaitGroup
192
193 // test stack growth at chan op
194 wg.Add(1)
195 go func() {
196 defer wg.Done()
197 c := make(chan int, 1)
198 growStackWithCallback(func() {
199 c <- 1
200 <-c
201 })
202 }()
203
204 // test stack growth at map op
205 wg.Add(1)
206 go func() {
207 defer wg.Done()
208 m := make(map[int]int)
209 growStackWithCallback(func() {
210 _, _ = m[1]
211 m[1] = 1
212 })
213 }()
214
215 // test stack growth at goroutine creation
216 wg.Add(1)
217 go func() {
218 defer wg.Done()
219 growStackWithCallback(func() {
220 done := make(chan bool)
221 go func() {
222 done <- true
223 }()
224 <-done
225 })
226 }()
227 wg.Wait()
228 }
229
230 func growStackWithCallback(cb func()) {
231 var f func(n int)
232 f = func(n int) {
233 if n == 0 {
234 cb()
235 return
236 }
237 f(n - 1)
238 }
239 for i := 0; i < 1<<10; i++ {
240 f(i)
241 }
242 }
243
244 // TestDeferPtrs tests the adjustment of Defer's argument pointers (p aka &y)
245 // during a stack copy.
246 func set(p *int, x int) {
247 *p = x
248 }
249 func TestDeferPtrs(t *testing.T) {
250 var y int
251
252 defer func() {
253 if y != 42 {
254 t.Errorf("defer's stack references were not adjusted appropriately")
255 }
256 }()
257 defer set(&y, 42)
258 growStack(nil)
259 }
260
261 type bigBuf [4 * 1024]byte
262
263 // TestDeferPtrsGoexit is like TestDeferPtrs but exercises the possibility that the
264 // stack grows as part of starting the deferred function. It calls Goexit at various
265 // stack depths, forcing the deferred function (with >4kB of args) to be run at
266 // the bottom of the stack. The goal is to find a stack depth less than 4kB from
267 // the end of the stack. Each trial runs in a different goroutine so that an earlier
268 // stack growth does not invalidate a later attempt.
269 func TestDeferPtrsGoexit(t *testing.T) {
270 for i := 0; i < 100; i++ {
271 c := make(chan int, 1)
272 go testDeferPtrsGoexit(c, i)
273 if n := <-c; n != 42 {
274 t.Fatalf("defer's stack references were not adjusted appropriately (i=%d n=%d)", i, n)
275 }
276 }
277 }
278
279 func testDeferPtrsGoexit(c chan int, i int) {
280 var y int
281 defer func() {
282 c <- y
283 }()
284 defer setBig(&y, 42, bigBuf{})
285 useStackAndCall(i, Goexit)
286 }
287
288 func setBig(p *int, x int, b bigBuf) {
289 *p = x
290 }
291
292 // TestDeferPtrsPanic is like TestDeferPtrsGoexit, but it's using panic instead
293 // of Goexit to run the Defers. Those two are different execution paths
294 // in the runtime.
295 func TestDeferPtrsPanic(t *testing.T) {
296 for i := 0; i < 100; i++ {
297 c := make(chan int, 1)
298 go testDeferPtrsGoexit(c, i)
299 if n := <-c; n != 42 {
300 t.Fatalf("defer's stack references were not adjusted appropriately (i=%d n=%d)", i, n)
301 }
302 }
303 }
304
305 func testDeferPtrsPanic(c chan int, i int) {
306 var y int
307 defer func() {
308 if recover() == nil {
309 c <- -1
310 return
311 }
312 c <- y
313 }()
314 defer setBig(&y, 42, bigBuf{})
315 useStackAndCall(i, func() { panic(1) })
316 }
317
318 //go:noinline
319 func testDeferLeafSigpanic1() {
320 // Cause a sigpanic to be injected in this frame.
321 //
322 // This function has to be declared before
323 // TestDeferLeafSigpanic so the runtime will crash if we think
324 // this function's continuation PC is in
325 // TestDeferLeafSigpanic.
326 *(*int)(nil) = 0
327 }
328
329 // TestDeferLeafSigpanic tests defer matching around leaf functions
330 // that sigpanic. This is tricky because on LR machines the outer
331 // function and the inner function have the same SP, but it's critical
332 // that we match up the defer correctly to get the right liveness map.
333 // See issue #25499.
334 func TestDeferLeafSigpanic(t *testing.T) {
335 // Push a defer that will walk the stack.
336 defer func() {
337 if err := recover(); err == nil {
338 t.Fatal("expected panic from nil pointer")
339 }
340 GC()
341 }()
342 // Call a leaf function. We must set up the exact call stack:
343 //
344 // defering function -> leaf function -> sigpanic
345 //
346 // On LR machines, the leaf function will have the same SP as
347 // the SP pushed for the defer frame.
348 testDeferLeafSigpanic1()
349 }
350
351 // TestPanicUseStack checks that a chain of Panic structs on the stack are
352 // updated correctly if the stack grows during the deferred execution that
353 // happens as a result of the panic.
354 func TestPanicUseStack(t *testing.T) {
355 pc := make([]uintptr, 10000)
356 defer func() {
357 recover()
358 Callers(0, pc) // force stack walk
359 useStackAndCall(100, func() {
360 defer func() {
361 recover()
362 Callers(0, pc) // force stack walk
363 useStackAndCall(200, func() {
364 defer func() {
365 recover()
366 Callers(0, pc) // force stack walk
367 }()
368 panic(3)
369 })
370 }()
371 panic(2)
372 })
373 }()
374 panic(1)
375 }
376
377 func TestPanicFar(t *testing.T) {
378 var xtree *xtreeNode
379 pc := make([]uintptr, 10000)
380 defer func() {
381 // At this point we created a large stack and unwound
382 // it via recovery. Force a stack walk, which will
383 // check the stack's consistency.
384 Callers(0, pc)
385 }()
386 defer func() {
387 recover()
388 }()
389 useStackAndCall(100, func() {
390 // Kick off the GC and make it do something nontrivial.
391 // (This used to force stack barriers to stick around.)
392 xtree = makeTree(18)
393 // Give the GC time to start scanning stacks.
394 time.Sleep(time.Millisecond)
395 panic(1)
396 })
397 _ = xtree
398 }
399
400 type xtreeNode struct {
401 l, r *xtreeNode
402 }
403
404 func makeTree(d int) *xtreeNode {
405 if d == 0 {
406 return new(xtreeNode)
407 }
408 return &xtreeNode{makeTree(d - 1), makeTree(d - 1)}
409 }
410
411 // use about n KB of stack and call f
412 func useStackAndCall(n int, f func()) {
413 if n == 0 {
414 f()
415 return
416 }
417 var b [1024]byte // makes frame about 1KB
418 useStackAndCall(n-1+int(b[99]), f)
419 }
420
421 func useStack(n int) {
422 useStackAndCall(n, func() {})
423 }
424
425 func growing(c chan int, done chan struct{}) {
426 for n := range c {
427 useStack(n)
428 done <- struct{}{}
429 }
430 done <- struct{}{}
431 }
432
433 func TestStackCache(t *testing.T) {
434 // Allocate a bunch of goroutines and grow their stacks.
435 // Repeat a few times to test the stack cache.
436 const (
437 R = 4
438 G = 200
439 S = 5
440 )
441 for i := 0; i < R; i++ {
442 var reqchans [G]chan int
443 done := make(chan struct{})
444 for j := 0; j < G; j++ {
445 reqchans[j] = make(chan int)
446 go growing(reqchans[j], done)
447 }
448 for s := 0; s < S; s++ {
449 for j := 0; j < G; j++ {
450 reqchans[j] <- 1 << uint(s)
451 }
452 for j := 0; j < G; j++ {
453 <-done
454 }
455 }
456 for j := 0; j < G; j++ {
457 close(reqchans[j])
458 }
459 for j := 0; j < G; j++ {
460 <-done
461 }
462 }
463 }
464
465 func TestStackOutput(t *testing.T) {
466 b := make([]byte, 1024)
467 stk := string(b[:Stack(b, false)])
468 if !strings.HasPrefix(stk, "goroutine ") {
469 t.Errorf("Stack (len %d):\n%s", len(stk), stk)
470 t.Errorf("Stack output should begin with \"goroutine \"")
471 }
472 }
473
474 func TestStackAllOutput(t *testing.T) {
475 b := make([]byte, 1024)
476 stk := string(b[:Stack(b, true)])
477 if !strings.HasPrefix(stk, "goroutine ") {
478 t.Errorf("Stack (len %d):\n%s", len(stk), stk)
479 t.Errorf("Stack output should begin with \"goroutine \"")
480 }
481 }
482
483 func TestStackPanic(t *testing.T) {
484 // Test that stack copying copies panics correctly. This is difficult
485 // to test because it is very unlikely that the stack will be copied
486 // in the middle of gopanic. But it can happen.
487 // To make this test effective, edit panic.go:gopanic and uncomment
488 // the GC() call just before freedefer(d).
489 defer func() {
490 if x := recover(); x == nil {
491 t.Errorf("recover failed")
492 }
493 }()
494 useStack(32)
495 panic("test panic")
496 }
497
498 func BenchmarkStackCopyPtr(b *testing.B) {
499 c := make(chan bool)
500 for i := 0; i < b.N; i++ {
501 go func() {
502 i := 1000000
503 countp(&i)
504 c <- true
505 }()
506 <-c
507 }
508 }
509
510 func countp(n *int) {
511 if *n == 0 {
512 return
513 }
514 *n--
515 countp(n)
516 }
517
518 func BenchmarkStackCopy(b *testing.B) {
519 c := make(chan bool)
520 for i := 0; i < b.N; i++ {
521 go func() {
522 count(1000000)
523 c <- true
524 }()
525 <-c
526 }
527 }
528
529 func count(n int) int {
530 if n == 0 {
531 return 0
532 }
533 return 1 + count(n-1)
534 }
535
536 func BenchmarkStackCopyNoCache(b *testing.B) {
537 c := make(chan bool)
538 for i := 0; i < b.N; i++ {
539 go func() {
540 count1(1000000)
541 c <- true
542 }()
543 <-c
544 }
545 }
546
547 func count1(n int) int {
548 if n <= 0 {
549 return 0
550 }
551 return 1 + count2(n-1)
552 }
553
554 func count2(n int) int { return 1 + count3(n-1) }
555 func count3(n int) int { return 1 + count4(n-1) }
556 func count4(n int) int { return 1 + count5(n-1) }
557 func count5(n int) int { return 1 + count6(n-1) }
558 func count6(n int) int { return 1 + count7(n-1) }
559 func count7(n int) int { return 1 + count8(n-1) }
560 func count8(n int) int { return 1 + count9(n-1) }
561 func count9(n int) int { return 1 + count10(n-1) }
562 func count10(n int) int { return 1 + count11(n-1) }
563 func count11(n int) int { return 1 + count12(n-1) }
564 func count12(n int) int { return 1 + count13(n-1) }
565 func count13(n int) int { return 1 + count14(n-1) }
566 func count14(n int) int { return 1 + count15(n-1) }
567 func count15(n int) int { return 1 + count16(n-1) }
568 func count16(n int) int { return 1 + count17(n-1) }
569 func count17(n int) int { return 1 + count18(n-1) }
570 func count18(n int) int { return 1 + count19(n-1) }
571 func count19(n int) int { return 1 + count20(n-1) }
572 func count20(n int) int { return 1 + count21(n-1) }
573 func count21(n int) int { return 1 + count22(n-1) }
574 func count22(n int) int { return 1 + count23(n-1) }
575 func count23(n int) int { return 1 + count1(n-1) }
576
577 type stkobjT struct {
578 p *stkobjT
579 x int64
580 y [20]int // consume some stack
581 }
582
583 // Sum creates a linked list of stkobjTs.
584 func Sum(n int64, p *stkobjT) {
585 if n == 0 {
586 return
587 }
588 s := stkobjT{p: p, x: n}
589 Sum(n-1, &s)
590 p.x += s.x
591 }
592
593 func BenchmarkStackCopyWithStkobj(b *testing.B) {
594 c := make(chan bool)
595 for i := 0; i < b.N; i++ {
596 go func() {
597 var s stkobjT
598 Sum(100000, &s)
599 c <- true
600 }()
601 <-c
602 }
603 }
604
605 type structWithMethod struct{}
606
607 func (s structWithMethod) caller() string {
608 _, file, line, ok := Caller(1)
609 if !ok {
610 panic("Caller failed")
611 }
612 return fmt.Sprintf("%s:%d", file, line)
613 }
614
615 func (s structWithMethod) callers() []uintptr {
616 pc := make([]uintptr, 16)
617 return pc[:Callers(0, pc)]
618 }
619
620 func (s structWithMethod) stack() string {
621 buf := make([]byte, 4<<10)
622 return string(buf[:Stack(buf, false)])
623 }
624
625 func (s structWithMethod) nop() {}
626
627 func TestStackWrapperCaller(t *testing.T) {
628 var d structWithMethod
629 // Force the compiler to construct a wrapper method.
630 wrapper := (*structWithMethod).caller
631 // Check that the wrapper doesn't affect the stack trace.
632 if dc, ic := d.caller(), wrapper(&d); dc != ic {
633 t.Fatalf("direct caller %q != indirect caller %q", dc, ic)
634 }
635 }
636
637 func TestStackWrapperCallers(t *testing.T) {
638 var d structWithMethod
639 wrapper := (*structWithMethod).callers
640 // Check that <autogenerated> doesn't appear in the stack trace.
641 pcs := wrapper(&d)
642 frames := CallersFrames(pcs)
643 for {
644 fr, more := frames.Next()
645 if fr.File == "<autogenerated>" {
646 t.Fatalf("<autogenerated> appears in stack trace: %+v", fr)
647 }
648 if !more {
649 break
650 }
651 }
652 }
653
654 func TestStackWrapperStack(t *testing.T) {
655 var d structWithMethod
656 wrapper := (*structWithMethod).stack
657 // Check that <autogenerated> doesn't appear in the stack trace.
658 stk := wrapper(&d)
659 if strings.Contains(stk, "<autogenerated>") {
660 t.Fatalf("<autogenerated> appears in stack trace:\n%s", stk)
661 }
662 }
663
664 type I interface {
665 M()
666 }
667
668 func TestStackWrapperStackPanic(t *testing.T) {
669 if Compiler == "gccgo" {
670 t.Skip("gccgo currently uses different, meaningless, wrapper names")
671 }
672
673 t.Run("sigpanic", func(t *testing.T) {
674 // nil calls to interface methods cause a sigpanic.
675 testStackWrapperPanic(t, func() { I.M(nil) }, "runtime_test.I.M")
676 })
677 t.Run("panicwrap", func(t *testing.T) {
678 // Nil calls to value method wrappers call panicwrap.
679 wrapper := (*structWithMethod).nop
680 testStackWrapperPanic(t, func() { wrapper(nil) }, "runtime_test.(*structWithMethod).nop")
681 })
682 }
683
684 func testStackWrapperPanic(t *testing.T, cb func(), expect string) {
685 // Test that the stack trace from a panicking wrapper includes
686 // the wrapper, even though elide these when they don't panic.
687 t.Run("CallersFrames", func(t *testing.T) {
688 defer func() {
689 err := recover()
690 if err == nil {
691 t.Fatalf("expected panic")
692 }
693 pcs := make([]uintptr, 10)
694 n := Callers(0, pcs)
695 frames := CallersFrames(pcs[:n])
696 for {
697 frame, more := frames.Next()
698 t.Log(frame.Function)
699 if frame.Function == expect {
700 return
701 }
702 if !more {
703 break
704 }
705 }
706 t.Fatalf("panicking wrapper %s missing from stack trace", expect)
707 }()
708 cb()
709 })
710 t.Run("Stack", func(t *testing.T) {
711 defer func() {
712 err := recover()
713 if err == nil {
714 t.Fatalf("expected panic")
715 }
716 buf := make([]byte, 4<<10)
717 stk := string(buf[:Stack(buf, false)])
718 if !strings.Contains(stk, "\n"+expect) {
719 t.Fatalf("panicking wrapper %s missing from stack trace:\n%s", expect, stk)
720 }
721 }()
722 cb()
723 })
724 }
725
726 func TestCallersFromWrapper(t *testing.T) {
727 if Compiler == "gccgo" {
728 t.Skip("gccgo currently uses different, meaningless, wrapper names")
729 }
730 // Test that invoking CallersFrames on a stack where the first
731 // PC is an autogenerated wrapper keeps the wrapper in the
732 // trace. Normally we elide these, assuming that the wrapper
733 // calls the thing you actually wanted to see, but in this
734 // case we need to keep it.
735 pc := reflect.ValueOf(I.M).Pointer()
736 frames := CallersFrames([]uintptr{pc})
737 frame, more := frames.Next()
738 if frame.Function != "runtime_test.I.M" {
739 t.Fatalf("want function %s, got %s", "runtime_test.I.M", frame.Function)
740 }
741 if more {
742 t.Fatalf("want 1 frame, got > 1")
743 }
744 }
745
746 func TestTracebackSystemstack(t *testing.T) {
747 if Compiler == "gccgo" {
748 t.Skip("test currently fails with gccgo")
749 }
750 if GOARCH == "ppc64" || GOARCH == "ppc64le" {
751 t.Skip("systemstack tail call not implemented on ppc64x")
752 }
753
754 // Test that profiles correctly jump over systemstack,
755 // including nested systemstack calls.
756 pcs := make([]uintptr, 20)
757 pcs = pcs[:TracebackSystemstack(pcs, 5)]
758 // Check that runtime.TracebackSystemstack appears five times
759 // and that we see TestTracebackSystemstack.
760 countIn, countOut := 0, 0
761 frames := CallersFrames(pcs)
762 var tb bytes.Buffer
763 for {
764 frame, more := frames.Next()
765 fmt.Fprintf(&tb, "\n%s+0x%x %s:%d", frame.Function, frame.PC-frame.Entry, frame.File, frame.Line)
766 switch frame.Function {
767 case "runtime.TracebackSystemstack":
768 countIn++
769 case "runtime_test.TestTracebackSystemstack":
770 countOut++
771 }
772 if !more {
773 break
774 }
775 }
776 if countIn != 5 || countOut != 1 {
777 t.Fatalf("expected 5 calls to TracebackSystemstack and 1 call to TestTracebackSystemstack, got:%s", tb.String())
778 }
779 }
780
781 func TestTracebackAncestors(t *testing.T) {
782 if Compiler == "gccgo" {
783 t.Skip("gccgo currently doesn't generate full ancestor tracebacks")
784 }
785 goroutineRegex := regexp.MustCompile(`goroutine [0-9]+ \[`)
786 for _, tracebackDepth := range []int{0, 1, 5, 50} {
787 output := runTestProg(t, "testprog", "TracebackAncestors", fmt.Sprintf("GODEBUG=tracebackancestors=%d", tracebackDepth))
788
789 numGoroutines := 3
790 numFrames := 2
791 ancestorsExpected := numGoroutines
792 if numGoroutines > tracebackDepth {
793 ancestorsExpected = tracebackDepth
794 }
795
796 matches := goroutineRegex.FindAllStringSubmatch(output, -1)
797 if len(matches) != 2 {
798 t.Fatalf("want 2 goroutines, got:\n%s", output)
799 }
800
801 // Check functions in the traceback.
802 fns := []string{"main.recurseThenCallGo", "main.main", "main.printStack", "main.TracebackAncestors"}
803 for _, fn := range fns {
804 if !strings.Contains(output, "\n"+fn+"(") {
805 t.Fatalf("expected %q function in traceback:\n%s", fn, output)
806 }
807 }
808
809 if want, count := "originating from goroutine", ancestorsExpected; strings.Count(output, want) != count {
810 t.Errorf("output does not contain %d instances of %q:\n%s", count, want, output)
811 }
812
813 if want, count := "main.recurseThenCallGo(...)", ancestorsExpected*(numFrames+1); strings.Count(output, want) != count {
814 t.Errorf("output does not contain %d instances of %q:\n%s", count, want, output)
815 }
816
817 if want, count := "main.recurseThenCallGo(0x", 1; strings.Count(output, want) != count {
818 t.Errorf("output does not contain %d instances of %q:\n%s", count, want, output)
819 }
820 }
821 }
822
823 // Test that defer closure is correctly scanned when the stack is scanned.
824 func TestDeferLiveness(t *testing.T) {
825 output := runTestProg(t, "testprog", "DeferLiveness", "GODEBUG=clobberfree=1")
826 if output != "" {
827 t.Errorf("output:\n%s\n\nwant no output", output)
828 }
829 }
830
831 func TestDeferHeapAndStack(t *testing.T) {
832 P := 4 // processors
833 N := 10000 //iterations
834 D := 200 // stack depth
835
836 if testing.Short() {
837 P /= 2
838 N /= 10
839 D /= 10
840 }
841 c := make(chan bool)
842 for p := 0; p < P; p++ {
843 go func() {
844 for i := 0; i < N; i++ {
845 if deferHeapAndStack(D) != 2*D {
846 panic("bad result")
847 }
848 }
849 c <- true
850 }()
851 }
852 for p := 0; p < P; p++ {
853 <-c
854 }
855 }
856
857 // deferHeapAndStack(n) computes 2*n
858 func deferHeapAndStack(n int) (r int) {
859 if n == 0 {
860 return 0
861 }
862 if n%2 == 0 {
863 // heap-allocated defers
864 for i := 0; i < 2; i++ {
865 defer func() {
866 r++
867 }()
868 }
869 } else {
870 // stack-allocated defers
871 defer func() {
872 r++
873 }()
874 defer func() {
875 r++
876 }()
877 }
878 r = deferHeapAndStack(n - 1)
879 escapeMe(new([1024]byte)) // force some GCs
880 return
881 }
882
883 // Pass a value to escapeMe to force it to escape.
884 var escapeMe = func(x any) {}
885
886 // Test that when F -> G is inlined and F is excluded from stack
887 // traces, G still appears.
888 func TestTracebackInlineExcluded(t *testing.T) {
889 defer func() {
890 recover()
891 buf := make([]byte, 4<<10)
892 stk := string(buf[:Stack(buf, false)])
893
894 t.Log(stk)
895
896 if not := "tracebackExcluded"; strings.Contains(stk, not) {
897 t.Errorf("found but did not expect %q", not)
898 }
899 if want := "tracebackNotExcluded"; !strings.Contains(stk, want) {
900 t.Errorf("expected %q in stack", want)
901 }
902 }()
903 tracebackExcluded()
904 }
905
906 // tracebackExcluded should be excluded from tracebacks. There are
907 // various ways this could come up. Linking it to a "runtime." name is
908 // rather synthetic, but it's easy and reliable. See issue #42754 for
909 // one way this happened in real code.
910 //
911 //go:linkname tracebackExcluded runtime.tracebackExcluded
912 //go:noinline
913 func tracebackExcluded() {
914 // Call an inlined function that should not itself be excluded
915 // from tracebacks.
916 tracebackNotExcluded()
917 }
918
919 // tracebackNotExcluded should be inlined into tracebackExcluded, but
920 // should not itself be excluded from the traceback.
921 func tracebackNotExcluded() {
922 var x *int
923 *x = 0
924 }