Source file
src/runtime/runtime_test.go
1
2
3
4
5 package runtime_test
6
7 import (
8 "flag"
9 "internal/asan"
10 "internal/cpu"
11 "internal/msan"
12 "internal/race"
13 "internal/runtime/atomic"
14 "internal/testenv"
15 "io"
16 "math/bits"
17 . "runtime"
18 "runtime/debug"
19 "slices"
20 "strings"
21 "sync"
22 "testing"
23 "time"
24 "unsafe"
25 )
26
27
28
29
30
31
32 var flagQuick = flag.Bool("quick", false, "skip slow tests, for cmd/dist test runtime:cpu124")
33
34 func init() {
35
36
37
38 SetTracebackEnv("system")
39 }
40
41 var errf error
42
43 func errfn() error {
44 return errf
45 }
46
47 func errfn1() error {
48 return io.EOF
49 }
50
51 func BenchmarkIfaceCmp100(b *testing.B) {
52 for i := 0; i < b.N; i++ {
53 for j := 0; j < 100; j++ {
54 if errfn() == io.EOF {
55 b.Fatal("bad comparison")
56 }
57 }
58 }
59 }
60
61 func BenchmarkIfaceCmpNil100(b *testing.B) {
62 for i := 0; i < b.N; i++ {
63 for j := 0; j < 100; j++ {
64 if errfn1() == nil {
65 b.Fatal("bad comparison")
66 }
67 }
68 }
69 }
70
71 var efaceCmp1 any
72 var efaceCmp2 any
73
74 func BenchmarkEfaceCmpDiff(b *testing.B) {
75 x := 5
76 efaceCmp1 = &x
77 y := 6
78 efaceCmp2 = &y
79 for i := 0; i < b.N; i++ {
80 for j := 0; j < 100; j++ {
81 if efaceCmp1 == efaceCmp2 {
82 b.Fatal("bad comparison")
83 }
84 }
85 }
86 }
87
88 func BenchmarkEfaceCmpDiffIndirect(b *testing.B) {
89 efaceCmp1 = [2]int{1, 2}
90 efaceCmp2 = [2]int{1, 2}
91 for i := 0; i < b.N; i++ {
92 for j := 0; j < 100; j++ {
93 if efaceCmp1 != efaceCmp2 {
94 b.Fatal("bad comparison")
95 }
96 }
97 }
98 }
99
100 func BenchmarkDefer(b *testing.B) {
101 for i := 0; i < b.N; i++ {
102 defer1()
103 }
104 }
105
106 func defer1() {
107 defer func(x, y, z int) {
108 if recover() != nil || x != 1 || y != 2 || z != 3 {
109 panic("bad recover")
110 }
111 }(1, 2, 3)
112 }
113
114 func BenchmarkDefer10(b *testing.B) {
115 for i := 0; i < b.N/10; i++ {
116 defer2()
117 }
118 }
119
120 func defer2() {
121 for i := 0; i < 10; i++ {
122 defer func(x, y, z int) {
123 if recover() != nil || x != 1 || y != 2 || z != 3 {
124 panic("bad recover")
125 }
126 }(1, 2, 3)
127 }
128 }
129
130 func BenchmarkDeferMany(b *testing.B) {
131 for i := 0; i < b.N; i++ {
132 defer func(x, y, z int) {
133 if recover() != nil || x != 1 || y != 2 || z != 3 {
134 panic("bad recover")
135 }
136 }(1, 2, 3)
137 }
138 }
139
140 func BenchmarkPanicRecover(b *testing.B) {
141 for i := 0; i < b.N; i++ {
142 defer3()
143 }
144 }
145
146 func defer3() {
147 defer func(x, y, z int) {
148 if recover() == nil {
149 panic("failed recover")
150 }
151 }(1, 2, 3)
152 panic("hi")
153 }
154
155
156 func TestStopCPUProfilingWithProfilerOff(t *testing.T) {
157 SetCPUProfileRate(0)
158 }
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173 var faultAddrs = []uint64{
174
175 0,
176 1,
177 0xfff,
178
179
180 0xffffffffffffffff,
181 0xfffffffffffff001,
182 0xffffffffffff0001,
183 0xfffffffffff00001,
184 0xffffffffff000001,
185 0xfffffffff0000001,
186 0xffffffff00000001,
187 0xfffffff000000001,
188 0xffffff0000000001,
189 0xfffff00000000001,
190 0xffff000000000001,
191 0xfff0000000000001,
192 0xff00000000000001,
193 0xf000000000000001,
194 0x8000000000000001,
195 }
196
197 func TestSetPanicOnFault(t *testing.T) {
198 old := debug.SetPanicOnFault(true)
199 defer debug.SetPanicOnFault(old)
200
201 nfault := 0
202 for _, addr := range faultAddrs {
203 testSetPanicOnFault(t, uintptr(addr), &nfault)
204 }
205 if nfault == 0 {
206 t.Fatalf("none of the addresses faulted")
207 }
208 }
209
210
211
212
213
214
215 func testSetPanicOnFault(t *testing.T, addr uintptr, nfault *int) {
216 if GOOS == "js" || GOOS == "wasip1" {
217 t.Skip(GOOS + " does not support catching faults")
218 }
219
220 defer func() {
221 if err := recover(); err != nil {
222 *nfault++
223 }
224 }()
225
226
227
228
229
230 v := *(*byte)(unsafe.Pointer(addr))
231 t.Logf("addr %#x: %#x\n", addr, v)
232 }
233
234 func eqstring_generic(s1, s2 string) bool {
235 if len(s1) != len(s2) {
236 return false
237 }
238
239
240 for i := 0; i < len(s1); i++ {
241 if s1[i] != s2[i] {
242 return false
243 }
244 }
245 return true
246 }
247
248 func TestEqString(t *testing.T) {
249
250
251
252 s := []string{
253 "",
254 "a",
255 "c",
256 "aaa",
257 "ccc",
258 "cccc"[:3],
259 "1234567890",
260 }
261 for _, s1 := range s {
262 for _, s2 := range s {
263 x := s1 == s2
264 y := eqstring_generic(s1, s2)
265 if x != y {
266 t.Errorf(`("%s" == "%s") = %t, want %t`, s1, s2, x, y)
267 }
268 }
269 }
270 }
271
272 func TestTrailingZero(t *testing.T) {
273
274 type T1 struct {
275 n int32
276 z [0]byte
277 }
278 if unsafe.Sizeof(T1{}) != 8 {
279 t.Errorf("sizeof(%#v)==%d, want 8", T1{}, unsafe.Sizeof(T1{}))
280 }
281 type T2 struct {
282 n int64
283 z struct{}
284 }
285 align := unsafe.Alignof(T2{})
286 wantT2 := (uintptr(9) + align - 1) &^ (align - 1)
287 if unsafe.Sizeof(T2{}) != wantT2 {
288 t.Errorf("sizeof(%#v)==%d, want %d", T2{}, unsafe.Sizeof(T2{}), wantT2)
289 }
290 type T3 struct {
291 n byte
292 z [4]struct{}
293 }
294 if unsafe.Sizeof(T3{}) != 2 {
295 t.Errorf("sizeof(%#v)==%d, want 2", T3{}, unsafe.Sizeof(T3{}))
296 }
297
298 type T4 struct {
299 a int32
300 b int16
301 c int8
302 z struct{}
303 }
304 if unsafe.Sizeof(T4{}) != 8 {
305 t.Errorf("sizeof(%#v)==%d, want 8", T4{}, unsafe.Sizeof(T4{}))
306 }
307
308 type T5 struct {
309 }
310 if unsafe.Sizeof(T5{}) != 0 {
311 t.Errorf("sizeof(%#v)==%d, want 0", T5{}, unsafe.Sizeof(T5{}))
312 }
313 }
314
315 func TestAppendGrowthHeap(t *testing.T) {
316 var x []int64
317 check := func(want int) {
318 if cap(x) != want {
319 t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
320 }
321 }
322
323 check(0)
324 want := 1
325 for i := 1; i <= 100; i++ {
326 x = append(x, 1)
327 check(want)
328 if i&(i-1) == 0 {
329 want = 2 * i
330 }
331 }
332 Escape(&x[0])
333 }
334
335 func TestAppendGrowthStack(t *testing.T) {
336 if race.Enabled || asan.Enabled || msan.Enabled {
337 t.Skip("instrumentation breaks this optimization")
338 }
339 var x []int64
340 check := func(want int) {
341 if cap(x) != want {
342 t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
343 }
344 }
345
346 check(0)
347 want := 32 / 8
348 if testenv.OptimizationOff() {
349 want = 1
350 }
351 for i := 1; i <= 100; i++ {
352 x = append(x, 1)
353 check(want)
354 if i&(i-1) == 0 {
355 want = max(want, 2*i)
356 }
357 }
358 }
359
360 var One = []int64{1}
361
362 func TestAppendSliceGrowth(t *testing.T) {
363 var x []int64
364 check := func(want int) {
365 if cap(x) != want {
366 t.Errorf("len=%d, cap=%d, want cap=%d", len(x), cap(x), want)
367 }
368 }
369
370 check(0)
371 want := 1
372 for i := 1; i <= 100; i++ {
373 x = append(x, One...)
374 check(want)
375 if i&(i-1) == 0 {
376 want = 2 * i
377 }
378 }
379 }
380
381 func TestGoroutineProfileTrivial(t *testing.T) {
382
383
384
385
386 for i := 0; ; i++ {
387 n1, ok := GoroutineProfile(nil)
388 if n1 < 1 || ok {
389 t.Fatalf("GoroutineProfile(nil) = %d, %v, want >0, false", n1, ok)
390 }
391 n2, ok := GoroutineProfile(make([]StackRecord, n1))
392 if n2 == n1 && ok {
393 break
394 }
395 t.Logf("GoroutineProfile(%d) = %d, %v, want %d, true", n1, n2, ok, n1)
396 if i >= 10 {
397 t.Fatalf("GoroutineProfile not converging")
398 }
399 }
400 }
401
402 func BenchmarkGoroutineProfile(b *testing.B) {
403 run := func(fn func() bool) func(b *testing.B) {
404 runOne := func(b *testing.B) {
405 latencies := make([]time.Duration, 0, b.N)
406
407 b.ResetTimer()
408 for i := 0; i < b.N; i++ {
409 start := time.Now()
410 ok := fn()
411 if !ok {
412 b.Fatal("goroutine profile failed")
413 }
414 latencies = append(latencies, time.Since(start))
415 }
416 b.StopTimer()
417
418
419 slices.Sort(latencies)
420 b.ReportMetric(float64(latencies[len(latencies)*50/100]), "p50-ns")
421 b.ReportMetric(float64(latencies[len(latencies)*90/100]), "p90-ns")
422 b.ReportMetric(float64(latencies[len(latencies)*99/100]), "p99-ns")
423 }
424 return func(b *testing.B) {
425 b.Run("idle", runOne)
426
427 b.Run("loaded", func(b *testing.B) {
428 stop := applyGCLoad(b)
429 runOne(b)
430
431
432
433 b.StopTimer()
434 stop()
435 })
436 }
437 }
438
439
440 b.Run("small-nil", run(func() bool {
441 GoroutineProfile(nil)
442 return true
443 }))
444
445
446 n := NumGoroutine()
447 p := make([]StackRecord, 2*n+2*GOMAXPROCS(0))
448 b.Run("small", run(func() bool {
449 _, ok := GoroutineProfile(p)
450 return ok
451 }))
452
453
454 ch := make(chan int)
455 var ready, done sync.WaitGroup
456 for i := 0; i < 5000; i++ {
457 ready.Add(1)
458 done.Add(1)
459 go func() { ready.Done(); <-ch; done.Done() }()
460 }
461 ready.Wait()
462
463
464 b.Run("large-nil", run(func() bool {
465 GoroutineProfile(nil)
466 return true
467 }))
468
469 n = NumGoroutine()
470 p = make([]StackRecord, 2*n+2*GOMAXPROCS(0))
471 b.Run("large", run(func() bool {
472 _, ok := GoroutineProfile(p)
473 return ok
474 }))
475
476 close(ch)
477 done.Wait()
478
479
480 b.Run("sparse-nil", run(func() bool {
481 GoroutineProfile(nil)
482 return true
483 }))
484
485
486 n = NumGoroutine()
487 p = make([]StackRecord, 2*n+2*GOMAXPROCS(0))
488 b.Run("sparse", run(func() bool {
489 _, ok := GoroutineProfile(p)
490 return ok
491 }))
492 }
493
494 func TestVersion(t *testing.T) {
495
496 vers := Version()
497 if strings.Contains(vers, "\r") || strings.Contains(vers, "\n") {
498 t.Fatalf("cr/nl in version: %q", vers)
499 }
500 }
501
502 func BenchmarkProcYield(b *testing.B) {
503 benchN := func(n uint32) func(*testing.B) {
504 return func(b *testing.B) {
505 for i := 0; i < b.N; i++ {
506 ProcYield(n)
507 }
508 }
509 }
510
511 b.Run("1", benchN(1))
512 b.Run("10", benchN(10))
513 b.Run("30", benchN(30))
514 b.Run("100", benchN(100))
515 b.Run("1000", benchN(1000))
516 }
517
518 func BenchmarkOSYield(b *testing.B) {
519 for i := 0; i < b.N; i++ {
520 OSYield()
521 }
522 }
523
524 func BenchmarkUsleep(b *testing.B) {
525 benchN := func(n uint32) func(*testing.B) {
526 return func(b *testing.B) {
527 for b.Loop() {
528 Usleep(n)
529 }
530 }
531 }
532
533 b.Run("1", benchN(1))
534 b.Run("3", benchN(3))
535 b.Run("20", benchN(20))
536 b.Run("10000", benchN(10*1000))
537 }
538
539 func BenchmarkStealRunnextSleep(b *testing.B) {
540 benchN := func(ns int64) func(*testing.B) {
541 return func(b *testing.B) {
542 for b.Loop() {
543 StealRunnextSleep(ns)
544 }
545 }
546 }
547
548 b.Run("3us", benchN(3000))
549 }
550
551 func BenchmarkNoteTSleep(b *testing.B) {
552 benchN := func(ns int64, fn func(n *Note, ns int64) bool) func(*testing.B) {
553 return func(b *testing.B) {
554 n := new(Note)
555 for b.Loop() {
556 NoteClear(n)
557 woke := fn(n, ns)
558 if woke {
559 b.Fatal("something woke note; we expected timeout")
560 }
561 }
562 }
563 }
564
565 b.Run("g0-100us", benchN(100*1000, NoteTSleepG0))
566 b.Run("g-100us", benchN(100*1000, NoteTSleepG))
567 }
568
569 func BenchmarkMutexContention(b *testing.B) {
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584 var state struct {
585 _ cpu.CacheLinePad
586 lock Mutex
587 _ cpu.CacheLinePad
588 count atomic.Int64
589 _ cpu.CacheLinePad
590 }
591
592 procs := GOMAXPROCS(0)
593 var wg sync.WaitGroup
594 for range procs {
595 wg.Add(1)
596 go func() {
597 defer wg.Done()
598 for {
599 Lock(&state.lock)
600 ours := state.count.Add(1)
601 Unlock(&state.lock)
602 if ours >= int64(b.N) {
603 return
604 }
605 }
606 }()
607 }
608 wg.Wait()
609 }
610
611 func BenchmarkMutexCapture(b *testing.B) {
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627 var state struct {
628 _ cpu.CacheLinePad
629 lock Mutex
630 _ cpu.CacheLinePad
631 count atomic.Int64
632 _ cpu.CacheLinePad
633 }
634
635 procs := GOMAXPROCS(0)
636 var wg sync.WaitGroup
637 histograms := make(chan [2][65]int)
638 for range procs {
639 wg.Add(1)
640 go func() {
641 var (
642 prev int64
643 streak int64
644 histogram [2][65]int
645 )
646 for {
647 Lock(&state.lock)
648 ours := state.count.Add(1)
649 Unlock(&state.lock)
650 delta := ours - prev - 1
651 prev = ours
652 if delta == 0 {
653 streak++
654 } else {
655 histogram[0][bits.LeadingZeros64(uint64(streak))]++
656 histogram[1][bits.LeadingZeros64(uint64(delta))]++
657 streak = 1
658 }
659 if ours >= int64(b.N) {
660 wg.Done()
661 if delta == 0 {
662 histogram[0][bits.LeadingZeros64(uint64(streak))]++
663 histogram[1][bits.LeadingZeros64(uint64(delta))]++
664 }
665 histograms <- histogram
666 return
667 }
668 }
669 }()
670 }
671
672 wg.Wait()
673 b.StopTimer()
674
675 var histogram [2][65]int
676 for range procs {
677 h := <-histograms
678 for i := range h {
679 for j := range h[i] {
680 histogram[i][j] += h[i][j]
681 }
682 }
683 }
684
685 percentile := func(h [65]int, p float64) int {
686 sum := 0
687 for i, v := range h {
688 bound := uint64(1<<63) >> i
689 sum += int(bound) * v
690 }
691
692
693
694
695
696 part := 0
697 for i, v := range h {
698 bound := uint64(1<<63) >> i
699 part += int(bound) * v
700
701 if float64(sum-part) < float64(sum)*p {
702 return int(bound)
703 }
704 }
705
706 return 0
707 }
708
709 perOp := float64(b.Elapsed().Nanoseconds()) / float64(b.N)
710 b.ReportMetric(perOp*float64(percentile(histogram[0], 1.0)), "ns/streak-p100")
711 b.ReportMetric(perOp*float64(percentile(histogram[0], 0.9)), "ns/streak-p90")
712 b.ReportMetric(perOp*float64(percentile(histogram[1], 1.0)), "ns/starve-p100")
713 b.ReportMetric(perOp*float64(percentile(histogram[1], 0.9)), "ns/starve-p90")
714 }
715
716 func BenchmarkMutexHandoff(b *testing.B) {
717 testcase := func(delay func(l *Mutex)) func(b *testing.B) {
718 return func(b *testing.B) {
719 if workers := 2; GOMAXPROCS(0) < workers {
720 b.Skipf("requires GOMAXPROCS >= %d", workers)
721 }
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741 var state struct {
742 _ cpu.CacheLinePad
743 lock Mutex
744 _ cpu.CacheLinePad
745 turn atomic.Int64
746 _ cpu.CacheLinePad
747 }
748
749 var delta atomic.Int64
750 var wg sync.WaitGroup
751
752
753
754
755
756
757
758 wg.Add(1)
759 go func() {
760 defer wg.Done()
761 var t int64
762 for range b.N {
763 Lock(&state.lock)
764 state.turn.Add(2)
765 delay(&state.lock)
766 t -= Nanotime()
767 Unlock(&state.lock)
768 for state.turn.Load()&0x2 != 0 {
769 }
770 }
771 state.turn.Add(1)
772 delta.Add(t)
773 }()
774
775
776
777
778
779 wg.Add(1)
780 go func() {
781 defer wg.Done()
782 var t int64
783 for {
784 switch state.turn.Load() & 0x3 {
785 case 0:
786 case 1, 3:
787 delta.Add(t)
788 return
789 case 2:
790 Lock(&state.lock)
791 t += Nanotime()
792 Unlock(&state.lock)
793 state.turn.Add(2)
794 }
795 }
796 }()
797
798 wg.Wait()
799 b.ReportMetric(float64(delta.Load())/float64(b.N), "ns/op")
800 }
801 }
802
803 b.Run("Solo", func(b *testing.B) {
804 var lock Mutex
805 for range b.N {
806 Lock(&lock)
807 Unlock(&lock)
808 }
809 })
810
811 b.Run("FastPingPong", testcase(func(l *Mutex) {}))
812 b.Run("SlowPingPong", testcase(func(l *Mutex) {
813
814 for !MutexContended(l) {
815 }
816
817
818 const extraNs = 10e3
819 for t0 := Nanotime(); Nanotime()-t0 < extraNs; {
820 }
821 }))
822 }
823
View as plain text