Debian Codegraph @

libgo/go/runtime/malloc_test.go

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