github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/runtime/gc_test.go (about)

     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  package runtime_test
     6  
     7  import (
     8  	"io"
     9  	"os"
    10  	"reflect"
    11  	"runtime"
    12  	"runtime/debug"
    13  	"testing"
    14  	"time"
    15  	"unsafe"
    16  )
    17  
    18  func TestGcSys(t *testing.T) {
    19  	if os.Getenv("GOGC") == "off" {
    20  		t.Skip("skipping test; GOGC=off in environment")
    21  	}
    22  	data := struct{ Short bool }{testing.Short()}
    23  	got := executeTest(t, testGCSysSource, &data)
    24  	want := "OK\n"
    25  	if got != want {
    26  		t.Fatalf("expected %q, but got %q", want, got)
    27  	}
    28  }
    29  
    30  const testGCSysSource = `
    31  package main
    32  
    33  import (
    34  	"fmt"
    35  	"runtime"
    36  )
    37  
    38  func main() {
    39  	runtime.GOMAXPROCS(1)
    40  	memstats := new(runtime.MemStats)
    41  	runtime.GC()
    42  	runtime.ReadMemStats(memstats)
    43  	sys := memstats.Sys
    44  
    45  	runtime.MemProfileRate = 0 // disable profiler
    46  
    47  	itercount := 1000000
    48  {{if .Short}}
    49  	itercount = 100000
    50  {{end}}
    51  	for i := 0; i < itercount; i++ {
    52  		workthegc()
    53  	}
    54  
    55  	// Should only be using a few MB.
    56  	// We allocated 100 MB or (if not short) 1 GB.
    57  	runtime.ReadMemStats(memstats)
    58  	if sys > memstats.Sys {
    59  		sys = 0
    60  	} else {
    61  		sys = memstats.Sys - sys
    62  	}
    63  	if sys > 16<<20 {
    64  		fmt.Printf("using too much memory: %d bytes\n", sys)
    65  		return
    66  	}
    67  	fmt.Printf("OK\n")
    68  }
    69  
    70  func workthegc() []byte {
    71  	return make([]byte, 1029)
    72  }
    73  `
    74  
    75  func TestGcDeepNesting(t *testing.T) {
    76  	type T [2][2][2][2][2][2][2][2][2][2]*int
    77  	a := new(T)
    78  
    79  	// Prevent the compiler from applying escape analysis.
    80  	// This makes sure new(T) is allocated on heap, not on the stack.
    81  	t.Logf("%p", a)
    82  
    83  	a[0][0][0][0][0][0][0][0][0][0] = new(int)
    84  	*a[0][0][0][0][0][0][0][0][0][0] = 13
    85  	runtime.GC()
    86  	if *a[0][0][0][0][0][0][0][0][0][0] != 13 {
    87  		t.Fail()
    88  	}
    89  }
    90  
    91  func TestGcHashmapIndirection(t *testing.T) {
    92  	defer debug.SetGCPercent(debug.SetGCPercent(1))
    93  	runtime.GC()
    94  	type T struct {
    95  		a [256]int
    96  	}
    97  	m := make(map[T]T)
    98  	for i := 0; i < 2000; i++ {
    99  		var a T
   100  		a.a[0] = i
   101  		m[a] = T{}
   102  	}
   103  }
   104  
   105  func TestGcArraySlice(t *testing.T) {
   106  	type X struct {
   107  		buf     [1]byte
   108  		nextbuf []byte
   109  		next    *X
   110  	}
   111  	var head *X
   112  	for i := 0; i < 10; i++ {
   113  		p := &X{}
   114  		p.buf[0] = 42
   115  		p.next = head
   116  		if head != nil {
   117  			p.nextbuf = head.buf[:]
   118  		}
   119  		head = p
   120  		runtime.GC()
   121  	}
   122  	for p := head; p != nil; p = p.next {
   123  		if p.buf[0] != 42 {
   124  			t.Fatal("corrupted heap")
   125  		}
   126  	}
   127  }
   128  
   129  func TestGcRescan(t *testing.T) {
   130  	type X struct {
   131  		c     chan error
   132  		nextx *X
   133  	}
   134  	type Y struct {
   135  		X
   136  		nexty *Y
   137  		p     *int
   138  	}
   139  	var head *Y
   140  	for i := 0; i < 10; i++ {
   141  		p := &Y{}
   142  		p.c = make(chan error)
   143  		if head != nil {
   144  			p.nextx = &head.X
   145  		}
   146  		p.nexty = head
   147  		p.p = new(int)
   148  		*p.p = 42
   149  		head = p
   150  		runtime.GC()
   151  	}
   152  	for p := head; p != nil; p = p.nexty {
   153  		if *p.p != 42 {
   154  			t.Fatal("corrupted heap")
   155  		}
   156  	}
   157  }
   158  
   159  func TestGcLastTime(t *testing.T) {
   160  	ms := new(runtime.MemStats)
   161  	t0 := time.Now().UnixNano()
   162  	runtime.GC()
   163  	t1 := time.Now().UnixNano()
   164  	runtime.ReadMemStats(ms)
   165  	last := int64(ms.LastGC)
   166  	if t0 > last || last > t1 {
   167  		t.Fatalf("bad last GC time: got %v, want [%v, %v]", last, t0, t1)
   168  	}
   169  	pause := ms.PauseNs[(ms.NumGC+255)%256]
   170  	// Due to timer granularity, pause can actually be 0 on windows
   171  	// or on virtualized environments.
   172  	if pause == 0 {
   173  		t.Logf("last GC pause was 0")
   174  	} else if pause > 10e9 {
   175  		t.Logf("bad last GC pause: got %v, want [0, 10e9]", pause)
   176  	}
   177  }
   178  
   179  var hugeSink interface{}
   180  
   181  func TestHugeGCInfo(t *testing.T) {
   182  	// The test ensures that compiler can chew these huge types even on weakest machines.
   183  	// The types are not allocated at runtime.
   184  	if hugeSink != nil {
   185  		// 400MB on 32 bots, 4TB on 64-bits.
   186  		const n = (400 << 20) + (unsafe.Sizeof(uintptr(0))-4)<<40
   187  		hugeSink = new([n]*byte)
   188  		hugeSink = new([n]uintptr)
   189  		hugeSink = new(struct {
   190  			x float64
   191  			y [n]*byte
   192  			z []string
   193  		})
   194  		hugeSink = new(struct {
   195  			x float64
   196  			y [n]uintptr
   197  			z []string
   198  		})
   199  	}
   200  }
   201  
   202  func TestPeriodicGC(t *testing.T) {
   203  	// Make sure we're not in the middle of a GC.
   204  	runtime.GC()
   205  
   206  	var ms1, ms2 runtime.MemStats
   207  	runtime.ReadMemStats(&ms1)
   208  
   209  	// Make periodic GC run continuously.
   210  	orig := *runtime.ForceGCPeriod
   211  	*runtime.ForceGCPeriod = 0
   212  
   213  	// Let some periodic GCs happen. In a heavily loaded system,
   214  	// it's possible these will be delayed, so this is designed to
   215  	// succeed quickly if things are working, but to give it some
   216  	// slack if things are slow.
   217  	var numGCs uint32
   218  	const want = 2
   219  	for i := 0; i < 20 && numGCs < want; i++ {
   220  		time.Sleep(5 * time.Millisecond)
   221  
   222  		// Test that periodic GC actually happened.
   223  		runtime.ReadMemStats(&ms2)
   224  		numGCs = ms2.NumGC - ms1.NumGC
   225  	}
   226  	*runtime.ForceGCPeriod = orig
   227  
   228  	if numGCs < want {
   229  		t.Fatalf("no periodic GC: got %v GCs, want >= 2", numGCs)
   230  	}
   231  }
   232  
   233  func BenchmarkSetTypePtr(b *testing.B) {
   234  	benchSetType(b, new(*byte))
   235  }
   236  
   237  func BenchmarkSetTypePtr8(b *testing.B) {
   238  	benchSetType(b, new([8]*byte))
   239  }
   240  
   241  func BenchmarkSetTypePtr16(b *testing.B) {
   242  	benchSetType(b, new([16]*byte))
   243  }
   244  
   245  func BenchmarkSetTypePtr32(b *testing.B) {
   246  	benchSetType(b, new([32]*byte))
   247  }
   248  
   249  func BenchmarkSetTypePtr64(b *testing.B) {
   250  	benchSetType(b, new([64]*byte))
   251  }
   252  
   253  func BenchmarkSetTypePtr126(b *testing.B) {
   254  	benchSetType(b, new([126]*byte))
   255  }
   256  
   257  func BenchmarkSetTypePtr128(b *testing.B) {
   258  	benchSetType(b, new([128]*byte))
   259  }
   260  
   261  func BenchmarkSetTypePtrSlice(b *testing.B) {
   262  	benchSetType(b, make([]*byte, 1<<10))
   263  }
   264  
   265  type Node1 struct {
   266  	Value       [1]uintptr
   267  	Left, Right *byte
   268  }
   269  
   270  func BenchmarkSetTypeNode1(b *testing.B) {
   271  	benchSetType(b, new(Node1))
   272  }
   273  
   274  func BenchmarkSetTypeNode1Slice(b *testing.B) {
   275  	benchSetType(b, make([]Node1, 32))
   276  }
   277  
   278  type Node8 struct {
   279  	Value       [8]uintptr
   280  	Left, Right *byte
   281  }
   282  
   283  func BenchmarkSetTypeNode8(b *testing.B) {
   284  	benchSetType(b, new(Node8))
   285  }
   286  
   287  func BenchmarkSetTypeNode8Slice(b *testing.B) {
   288  	benchSetType(b, make([]Node8, 32))
   289  }
   290  
   291  type Node64 struct {
   292  	Value       [64]uintptr
   293  	Left, Right *byte
   294  }
   295  
   296  func BenchmarkSetTypeNode64(b *testing.B) {
   297  	benchSetType(b, new(Node64))
   298  }
   299  
   300  func BenchmarkSetTypeNode64Slice(b *testing.B) {
   301  	benchSetType(b, make([]Node64, 32))
   302  }
   303  
   304  type Node64Dead struct {
   305  	Left, Right *byte
   306  	Value       [64]uintptr
   307  }
   308  
   309  func BenchmarkSetTypeNode64Dead(b *testing.B) {
   310  	benchSetType(b, new(Node64Dead))
   311  }
   312  
   313  func BenchmarkSetTypeNode64DeadSlice(b *testing.B) {
   314  	benchSetType(b, make([]Node64Dead, 32))
   315  }
   316  
   317  type Node124 struct {
   318  	Value       [124]uintptr
   319  	Left, Right *byte
   320  }
   321  
   322  func BenchmarkSetTypeNode124(b *testing.B) {
   323  	benchSetType(b, new(Node124))
   324  }
   325  
   326  func BenchmarkSetTypeNode124Slice(b *testing.B) {
   327  	benchSetType(b, make([]Node124, 32))
   328  }
   329  
   330  type Node126 struct {
   331  	Value       [126]uintptr
   332  	Left, Right *byte
   333  }
   334  
   335  func BenchmarkSetTypeNode126(b *testing.B) {
   336  	benchSetType(b, new(Node126))
   337  }
   338  
   339  func BenchmarkSetTypeNode126Slice(b *testing.B) {
   340  	benchSetType(b, make([]Node126, 32))
   341  }
   342  
   343  type Node128 struct {
   344  	Value       [128]uintptr
   345  	Left, Right *byte
   346  }
   347  
   348  func BenchmarkSetTypeNode128(b *testing.B) {
   349  	benchSetType(b, new(Node128))
   350  }
   351  
   352  func BenchmarkSetTypeNode128Slice(b *testing.B) {
   353  	benchSetType(b, make([]Node128, 32))
   354  }
   355  
   356  type Node130 struct {
   357  	Value       [130]uintptr
   358  	Left, Right *byte
   359  }
   360  
   361  func BenchmarkSetTypeNode130(b *testing.B) {
   362  	benchSetType(b, new(Node130))
   363  }
   364  
   365  func BenchmarkSetTypeNode130Slice(b *testing.B) {
   366  	benchSetType(b, make([]Node130, 32))
   367  }
   368  
   369  type Node1024 struct {
   370  	Value       [1024]uintptr
   371  	Left, Right *byte
   372  }
   373  
   374  func BenchmarkSetTypeNode1024(b *testing.B) {
   375  	benchSetType(b, new(Node1024))
   376  }
   377  
   378  func BenchmarkSetTypeNode1024Slice(b *testing.B) {
   379  	benchSetType(b, make([]Node1024, 32))
   380  }
   381  
   382  func benchSetType(b *testing.B, x interface{}) {
   383  	v := reflect.ValueOf(x)
   384  	t := v.Type()
   385  	switch t.Kind() {
   386  	case reflect.Ptr:
   387  		b.SetBytes(int64(t.Elem().Size()))
   388  	case reflect.Slice:
   389  		b.SetBytes(int64(t.Elem().Size()) * int64(v.Len()))
   390  	}
   391  	b.ResetTimer()
   392  	runtime.BenchSetType(b.N, x)
   393  }
   394  
   395  func BenchmarkAllocation(b *testing.B) {
   396  	type T struct {
   397  		x, y *byte
   398  	}
   399  	ngo := runtime.GOMAXPROCS(0)
   400  	work := make(chan bool, b.N+ngo)
   401  	result := make(chan *T)
   402  	for i := 0; i < b.N; i++ {
   403  		work <- true
   404  	}
   405  	for i := 0; i < ngo; i++ {
   406  		work <- false
   407  	}
   408  	for i := 0; i < ngo; i++ {
   409  		go func() {
   410  			var x *T
   411  			for <-work {
   412  				for i := 0; i < 1000; i++ {
   413  					x = &T{}
   414  				}
   415  			}
   416  			result <- x
   417  		}()
   418  	}
   419  	for i := 0; i < ngo; i++ {
   420  		<-result
   421  	}
   422  }
   423  
   424  func TestPrintGC(t *testing.T) {
   425  	if testing.Short() {
   426  		t.Skip("Skipping in short mode")
   427  	}
   428  	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))
   429  	done := make(chan bool)
   430  	go func() {
   431  		for {
   432  			select {
   433  			case <-done:
   434  				return
   435  			default:
   436  				runtime.GC()
   437  			}
   438  		}
   439  	}()
   440  	for i := 0; i < 1e4; i++ {
   441  		func() {
   442  			defer print("")
   443  		}()
   444  	}
   445  	close(done)
   446  }
   447  
   448  // The implicit y, ok := x.(error) for the case error
   449  // in testTypeSwitch used to not initialize the result y
   450  // before passing &y to assertE2I2GC.
   451  // Catch this by making assertE2I2 call runtime.GC,
   452  // which will force a stack scan and failure if there are
   453  // bad pointers, and then fill the stack with bad pointers
   454  // and run the type switch.
   455  func TestAssertE2I2Liveness(t *testing.T) {
   456  	// Note that this flag is defined in export_test.go
   457  	// and is not available to ordinary imports of runtime.
   458  	*runtime.TestingAssertE2I2GC = true
   459  	defer func() {
   460  		*runtime.TestingAssertE2I2GC = false
   461  	}()
   462  
   463  	poisonStack()
   464  	testTypeSwitch(io.EOF)
   465  	poisonStack()
   466  	testAssert(io.EOF)
   467  	poisonStack()
   468  	testAssertVar(io.EOF)
   469  }
   470  
   471  func poisonStack() uintptr {
   472  	var x [1000]uintptr
   473  	for i := range x {
   474  		x[i] = 0xff
   475  	}
   476  	return x[123]
   477  }
   478  
   479  func testTypeSwitch(x interface{}) error {
   480  	switch y := x.(type) {
   481  	case nil:
   482  		// ok
   483  	case error:
   484  		return y
   485  	}
   486  	return nil
   487  }
   488  
   489  func testAssert(x interface{}) error {
   490  	if y, ok := x.(error); ok {
   491  		return y
   492  	}
   493  	return nil
   494  }
   495  
   496  func testAssertVar(x interface{}) error {
   497  	var y, ok = x.(error)
   498  	if ok {
   499  		return y
   500  	}
   501  	return nil
   502  }
   503  
   504  func TestAssertE2T2Liveness(t *testing.T) {
   505  	*runtime.TestingAssertE2T2GC = true
   506  	defer func() {
   507  		*runtime.TestingAssertE2T2GC = false
   508  	}()
   509  
   510  	poisonStack()
   511  	testIfaceEqual(io.EOF)
   512  }
   513  
   514  var a bool
   515  
   516  //go:noinline
   517  func testIfaceEqual(x interface{}) {
   518  	if x == "abc" {
   519  		a = true
   520  	}
   521  }