github.com/lzhfromustc/gofuzz@v0.0.0-20211116160056-151b3108bbd1/runtime/malloc_test.go (about)

     1  // Copyright 2013 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  	"flag"
     9  	"fmt"
    10  	"internal/race"
    11  	"internal/testenv"
    12  	"os"
    13  	"os/exec"
    14  	"reflect"
    15  	"runtime"
    16  	. "runtime"
    17  	"strings"
    18  	"sync/atomic"
    19  	"testing"
    20  	"time"
    21  	"unsafe"
    22  )
    23  
    24  var testMemStatsCount int
    25  
    26  func TestMemStats(t *testing.T) {
    27  	testMemStatsCount++
    28  
    29  	// Make sure there's at least one forced GC.
    30  	GC()
    31  
    32  	// Test that MemStats has sane values.
    33  	st := new(MemStats)
    34  	ReadMemStats(st)
    35  
    36  	nz := func(x interface{}) error {
    37  		if x != reflect.Zero(reflect.TypeOf(x)).Interface() {
    38  			return nil
    39  		}
    40  		return fmt.Errorf("zero value")
    41  	}
    42  	le := func(thresh float64) func(interface{}) error {
    43  		return func(x interface{}) error {
    44  			// These sanity tests aren't necessarily valid
    45  			// with high -test.count values, so only run
    46  			// them once.
    47  			if testMemStatsCount > 1 {
    48  				return nil
    49  			}
    50  
    51  			if reflect.ValueOf(x).Convert(reflect.TypeOf(thresh)).Float() < thresh {
    52  				return nil
    53  			}
    54  			return fmt.Errorf("insanely high value (overflow?); want <= %v", thresh)
    55  		}
    56  	}
    57  	eq := func(x interface{}) func(interface{}) error {
    58  		return func(y interface{}) error {
    59  			if x == y {
    60  				return nil
    61  			}
    62  			return fmt.Errorf("want %v", x)
    63  		}
    64  	}
    65  	// Of the uint fields, HeapReleased, HeapIdle can be 0.
    66  	// PauseTotalNs can be 0 if timer resolution is poor.
    67  	fields := map[string][]func(interface{}) error{
    68  		"Alloc": {nz, le(1e10)}, "TotalAlloc": {nz, le(1e11)}, "Sys": {nz, le(1e10)},
    69  		"Lookups": {eq(uint64(0))}, "Mallocs": {nz, le(1e10)}, "Frees": {nz, le(1e10)},
    70  		"HeapAlloc": {nz, le(1e10)}, "HeapSys": {nz, le(1e10)}, "HeapIdle": {le(1e10)},
    71  		"HeapInuse": {nz, le(1e10)}, "HeapReleased": {le(1e10)}, "HeapObjects": {nz, le(1e10)},
    72  		"StackInuse": {nz, le(1e10)}, "StackSys": {nz, le(1e10)},
    73  		"MSpanInuse": {nz, le(1e10)}, "MSpanSys": {nz, le(1e10)},
    74  		"MCacheInuse": {nz, le(1e10)}, "MCacheSys": {nz, le(1e10)},
    75  		"BuckHashSys": {nz, le(1e10)}, "GCSys": {nz, le(1e10)}, "OtherSys": {nz, le(1e10)},
    76  		"NextGC": {nz, le(1e10)}, "LastGC": {nz},
    77  		"PauseTotalNs": {le(1e11)}, "PauseNs": nil, "PauseEnd": nil,
    78  		"NumGC": {nz, le(1e9)}, "NumForcedGC": {nz, le(1e9)},
    79  		"GCCPUFraction": {le(0.99)}, "EnableGC": {eq(true)}, "DebugGC": {eq(false)},
    80  		"BySize": nil,
    81  	}
    82  
    83  	rst := reflect.ValueOf(st).Elem()
    84  	for i := 0; i < rst.Type().NumField(); i++ {
    85  		name, val := rst.Type().Field(i).Name, rst.Field(i).Interface()
    86  		checks, ok := fields[name]
    87  		if !ok {
    88  			t.Errorf("unknown MemStats field %s", name)
    89  			continue
    90  		}
    91  		for _, check := range checks {
    92  			if err := check(val); err != nil {
    93  				t.Errorf("%s = %v: %s", name, val, err)
    94  			}
    95  		}
    96  	}
    97  
    98  	if st.Sys != st.HeapSys+st.StackSys+st.MSpanSys+st.MCacheSys+
    99  		st.BuckHashSys+st.GCSys+st.OtherSys {
   100  		t.Fatalf("Bad sys value: %+v", *st)
   101  	}
   102  
   103  	if st.HeapIdle+st.HeapInuse != st.HeapSys {
   104  		t.Fatalf("HeapIdle(%d) + HeapInuse(%d) should be equal to HeapSys(%d), but isn't.", st.HeapIdle, st.HeapInuse, st.HeapSys)
   105  	}
   106  
   107  	if lpe := st.PauseEnd[int(st.NumGC+255)%len(st.PauseEnd)]; st.LastGC != lpe {
   108  		t.Fatalf("LastGC(%d) != last PauseEnd(%d)", st.LastGC, lpe)
   109  	}
   110  
   111  	var pauseTotal uint64
   112  	for _, pause := range st.PauseNs {
   113  		pauseTotal += pause
   114  	}
   115  	if int(st.NumGC) < len(st.PauseNs) {
   116  		// We have all pauses, so this should be exact.
   117  		if st.PauseTotalNs != pauseTotal {
   118  			t.Fatalf("PauseTotalNs(%d) != sum PauseNs(%d)", st.PauseTotalNs, pauseTotal)
   119  		}
   120  		for i := int(st.NumGC); i < len(st.PauseNs); i++ {
   121  			if st.PauseNs[i] != 0 {
   122  				t.Fatalf("Non-zero PauseNs[%d]: %+v", i, st)
   123  			}
   124  			if st.PauseEnd[i] != 0 {
   125  				t.Fatalf("Non-zero PauseEnd[%d]: %+v", i, st)
   126  			}
   127  		}
   128  	} else {
   129  		if st.PauseTotalNs < pauseTotal {
   130  			t.Fatalf("PauseTotalNs(%d) < sum PauseNs(%d)", st.PauseTotalNs, pauseTotal)
   131  		}
   132  	}
   133  
   134  	if st.NumForcedGC > st.NumGC {
   135  		t.Fatalf("NumForcedGC(%d) > NumGC(%d)", st.NumForcedGC, st.NumGC)
   136  	}
   137  }
   138  
   139  func TestStringConcatenationAllocs(t *testing.T) {
   140  	n := testing.AllocsPerRun(1e3, func() {
   141  		b := make([]byte, 10)
   142  		for i := 0; i < 10; i++ {
   143  			b[i] = byte(i) + '0'
   144  		}
   145  		s := "foo" + string(b)
   146  		if want := "foo0123456789"; s != want {
   147  			t.Fatalf("want %v, got %v", want, s)
   148  		}
   149  	})
   150  	// Only string concatenation allocates.
   151  	if n != 1 {
   152  		t.Fatalf("want 1 allocation, got %v", n)
   153  	}
   154  }
   155  
   156  func TestTinyAlloc(t *testing.T) {
   157  	const N = 16
   158  	var v [N]unsafe.Pointer
   159  	for i := range v {
   160  		v[i] = unsafe.Pointer(new(byte))
   161  	}
   162  
   163  	chunks := make(map[uintptr]bool, N)
   164  	for _, p := range v {
   165  		chunks[uintptr(p)&^7] = true
   166  	}
   167  
   168  	if len(chunks) == N {
   169  		t.Fatal("no bytes allocated within the same 8-byte chunk")
   170  	}
   171  }
   172  
   173  var (
   174  	tinyByteSink   *byte
   175  	tinyUint32Sink *uint32
   176  	tinyObj12Sink  *obj12
   177  )
   178  
   179  type obj12 struct {
   180  	a uint64
   181  	b uint32
   182  }
   183  
   184  func TestTinyAllocIssue37262(t *testing.T) {
   185  	// Try to cause an alignment access fault
   186  	// by atomically accessing the first 64-bit
   187  	// value of a tiny-allocated object.
   188  	// See issue 37262 for details.
   189  
   190  	// GC twice, once to reach a stable heap state
   191  	// and again to make sure we finish the sweep phase.
   192  	runtime.GC()
   193  	runtime.GC()
   194  
   195  	// Make 1-byte allocations until we get a fresh tiny slot.
   196  	aligned := false
   197  	for i := 0; i < 16; i++ {
   198  		tinyByteSink = new(byte)
   199  		if uintptr(unsafe.Pointer(tinyByteSink))&0xf == 0xf {
   200  			aligned = true
   201  			break
   202  		}
   203  	}
   204  	if !aligned {
   205  		t.Fatal("unable to get a fresh tiny slot")
   206  	}
   207  
   208  	// Create a 4-byte object so that the current
   209  	// tiny slot is partially filled.
   210  	tinyUint32Sink = new(uint32)
   211  
   212  	// Create a 12-byte object, which fits into the
   213  	// tiny slot. If it actually gets place there,
   214  	// then the field "a" will be improperly aligned
   215  	// for atomic access on 32-bit architectures.
   216  	// This won't be true if issue 36606 gets resolved.
   217  	tinyObj12Sink = new(obj12)
   218  
   219  	// Try to atomically access "x.a".
   220  	atomic.StoreUint64(&tinyObj12Sink.a, 10)
   221  
   222  	// Clear the sinks.
   223  	tinyByteSink = nil
   224  	tinyUint32Sink = nil
   225  	tinyObj12Sink = nil
   226  }
   227  
   228  func TestPageCacheLeak(t *testing.T) {
   229  	defer GOMAXPROCS(GOMAXPROCS(1))
   230  	leaked := PageCachePagesLeaked()
   231  	if leaked != 0 {
   232  		t.Fatalf("found %d leaked pages in page caches", leaked)
   233  	}
   234  }
   235  
   236  func TestPhysicalMemoryUtilization(t *testing.T) {
   237  	got := runTestProg(t, "testprog", "GCPhys")
   238  	want := "OK\n"
   239  	if got != want {
   240  		t.Fatalf("expected %q, but got %q", want, got)
   241  	}
   242  }
   243  
   244  func TestScavengedBitsCleared(t *testing.T) {
   245  	var mismatches [128]BitsMismatch
   246  	if n, ok := CheckScavengedBitsCleared(mismatches[:]); !ok {
   247  		t.Errorf("uncleared scavenged bits")
   248  		for _, m := range mismatches[:n] {
   249  			t.Logf("\t@ address 0x%x", m.Base)
   250  			t.Logf("\t|  got: %064b", m.Got)
   251  			t.Logf("\t| want: %064b", m.Want)
   252  		}
   253  		t.FailNow()
   254  	}
   255  }
   256  
   257  type acLink struct {
   258  	x [1 << 20]byte
   259  }
   260  
   261  var arenaCollisionSink []*acLink
   262  
   263  func TestArenaCollision(t *testing.T) {
   264  	testenv.MustHaveExec(t)
   265  
   266  	// Test that mheap.sysAlloc handles collisions with other
   267  	// memory mappings.
   268  	if os.Getenv("TEST_ARENA_COLLISION") != "1" {
   269  		cmd := testenv.CleanCmdEnv(exec.Command(os.Args[0], "-test.run=TestArenaCollision", "-test.v"))
   270  		cmd.Env = append(cmd.Env, "TEST_ARENA_COLLISION=1")
   271  		out, err := cmd.CombinedOutput()
   272  		if race.Enabled {
   273  			// This test runs the runtime out of hint
   274  			// addresses, so it will start mapping the
   275  			// heap wherever it can. The race detector
   276  			// doesn't support this, so look for the
   277  			// expected failure.
   278  			if want := "too many address space collisions"; !strings.Contains(string(out), want) {
   279  				t.Fatalf("want %q, got:\n%s", want, string(out))
   280  			}
   281  		} else if !strings.Contains(string(out), "PASS\n") || err != nil {
   282  			t.Fatalf("%s\n(exit status %v)", string(out), err)
   283  		}
   284  		return
   285  	}
   286  	disallowed := [][2]uintptr{}
   287  	// Drop all but the next 3 hints. 64-bit has a lot of hints,
   288  	// so it would take a lot of memory to go through all of them.
   289  	KeepNArenaHints(3)
   290  	// Consume these 3 hints and force the runtime to find some
   291  	// fallback hints.
   292  	for i := 0; i < 5; i++ {
   293  		// Reserve memory at the next hint so it can't be used
   294  		// for the heap.
   295  		start, end := MapNextArenaHint()
   296  		disallowed = append(disallowed, [2]uintptr{start, end})
   297  		// Allocate until the runtime tries to use the hint we
   298  		// just mapped over.
   299  		hint := GetNextArenaHint()
   300  		for GetNextArenaHint() == hint {
   301  			ac := new(acLink)
   302  			arenaCollisionSink = append(arenaCollisionSink, ac)
   303  			// The allocation must not have fallen into
   304  			// one of the reserved regions.
   305  			p := uintptr(unsafe.Pointer(ac))
   306  			for _, d := range disallowed {
   307  				if d[0] <= p && p < d[1] {
   308  					t.Fatalf("allocation %#x in reserved region [%#x, %#x)", p, d[0], d[1])
   309  				}
   310  			}
   311  		}
   312  	}
   313  }
   314  
   315  var mallocSink uintptr
   316  
   317  func BenchmarkMalloc8(b *testing.B) {
   318  	var x uintptr
   319  	for i := 0; i < b.N; i++ {
   320  		p := new(int64)
   321  		x ^= uintptr(unsafe.Pointer(p))
   322  	}
   323  	mallocSink = x
   324  }
   325  
   326  func BenchmarkMalloc16(b *testing.B) {
   327  	var x uintptr
   328  	for i := 0; i < b.N; i++ {
   329  		p := new([2]int64)
   330  		x ^= uintptr(unsafe.Pointer(p))
   331  	}
   332  	mallocSink = x
   333  }
   334  
   335  func BenchmarkMallocTypeInfo8(b *testing.B) {
   336  	var x uintptr
   337  	for i := 0; i < b.N; i++ {
   338  		p := new(struct {
   339  			p [8 / unsafe.Sizeof(uintptr(0))]*int
   340  		})
   341  		x ^= uintptr(unsafe.Pointer(p))
   342  	}
   343  	mallocSink = x
   344  }
   345  
   346  func BenchmarkMallocTypeInfo16(b *testing.B) {
   347  	var x uintptr
   348  	for i := 0; i < b.N; i++ {
   349  		p := new(struct {
   350  			p [16 / unsafe.Sizeof(uintptr(0))]*int
   351  		})
   352  		x ^= uintptr(unsafe.Pointer(p))
   353  	}
   354  	mallocSink = x
   355  }
   356  
   357  type LargeStruct struct {
   358  	x [16][]byte
   359  }
   360  
   361  func BenchmarkMallocLargeStruct(b *testing.B) {
   362  	var x uintptr
   363  	for i := 0; i < b.N; i++ {
   364  		p := make([]LargeStruct, 2)
   365  		x ^= uintptr(unsafe.Pointer(&p[0]))
   366  	}
   367  	mallocSink = x
   368  }
   369  
   370  var n = flag.Int("n", 1000, "number of goroutines")
   371  
   372  func BenchmarkGoroutineSelect(b *testing.B) {
   373  	quit := make(chan struct{})
   374  	read := func(ch chan struct{}) {
   375  		for {
   376  			select {
   377  			case _, ok := <-ch:
   378  				if !ok {
   379  					return
   380  				}
   381  			case <-quit:
   382  				return
   383  			}
   384  		}
   385  	}
   386  	benchHelper(b, *n, read)
   387  }
   388  
   389  func BenchmarkGoroutineBlocking(b *testing.B) {
   390  	read := func(ch chan struct{}) {
   391  		for {
   392  			if _, ok := <-ch; !ok {
   393  				return
   394  			}
   395  		}
   396  	}
   397  	benchHelper(b, *n, read)
   398  }
   399  
   400  func BenchmarkGoroutineForRange(b *testing.B) {
   401  	read := func(ch chan struct{}) {
   402  		for range ch {
   403  		}
   404  	}
   405  	benchHelper(b, *n, read)
   406  }
   407  
   408  func benchHelper(b *testing.B, n int, read func(chan struct{})) {
   409  	m := make([]chan struct{}, n)
   410  	for i := range m {
   411  		m[i] = make(chan struct{}, 1)
   412  		go read(m[i])
   413  	}
   414  	b.StopTimer()
   415  	b.ResetTimer()
   416  	GC()
   417  
   418  	for i := 0; i < b.N; i++ {
   419  		for _, ch := range m {
   420  			if ch != nil {
   421  				ch <- struct{}{}
   422  			}
   423  		}
   424  		time.Sleep(10 * time.Millisecond)
   425  		b.StartTimer()
   426  		GC()
   427  		b.StopTimer()
   428  	}
   429  
   430  	for _, ch := range m {
   431  		close(ch)
   432  	}
   433  	time.Sleep(10 * time.Millisecond)
   434  }
   435  
   436  func BenchmarkGoroutineIdle(b *testing.B) {
   437  	quit := make(chan struct{})
   438  	fn := func() {
   439  		<-quit
   440  	}
   441  	for i := 0; i < *n; i++ {
   442  		go fn()
   443  	}
   444  
   445  	GC()
   446  	b.ResetTimer()
   447  
   448  	for i := 0; i < b.N; i++ {
   449  		GC()
   450  	}
   451  
   452  	b.StopTimer()
   453  	close(quit)
   454  	time.Sleep(10 * time.Millisecond)
   455  }