2013-09-26 Richard Biener <rguenther@suse.de>
[official-gcc.git] / libgo / go / runtime / mallocrand.go
blobf1bcb89cfa43881b04c9f173a73cad9c02950581
1 // Copyright 2009 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.
5 // +build ignore
7 // Random malloc test.
9 package main
11 import (
12 "flag"
13 "math/rand"
14 "runtime"
15 "unsafe"
18 var chatty = flag.Bool("v", false, "chatty")
20 var footprint uint64
21 var allocated uint64
23 func bigger() {
24 memstats := new(runtime.MemStats)
25 runtime.ReadMemStats(memstats)
26 if f := memstats.Sys; footprint < f {
27 footprint = f
28 if *chatty {
29 println("Footprint", footprint, " for ", allocated)
31 if footprint > 1e9 {
32 println("too big")
33 panic("fail")
38 // Prime the data structures by allocating one of
39 // each block in order. After this, there should be
40 // little reason to ask for more memory from the OS.
41 func prime() {
42 for i := 0; i < 16; i++ {
43 b := runtime.Alloc(1 << uint(i))
44 runtime.Free(b)
46 for i := uintptr(0); i < 256; i++ {
47 b := runtime.Alloc(i << 12)
48 runtime.Free(b)
52 func memset(b *byte, c byte, n uintptr) {
53 np := uintptr(n)
54 for i := uintptr(0); i < np; i++ {
55 *(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(b)) + i)) = c
59 func main() {
60 flag.Parse()
61 // prime()
62 var blocks [1]struct {
63 base *byte
64 siz uintptr
66 for i := 0; i < 1<<10; i++ {
67 if i%(1<<10) == 0 && *chatty {
68 println(i)
70 b := rand.Int() % len(blocks)
71 if blocks[b].base != nil {
72 // println("Free", blocks[b].siz, blocks[b].base)
73 runtime.Free(blocks[b].base)
74 blocks[b].base = nil
75 allocated -= uint64(blocks[b].siz)
76 continue
78 siz := uintptr(rand.Int() >> (11 + rand.Uint32()%20))
79 base := runtime.Alloc(siz)
80 // ptr := uintptr(syscall.BytePtr(base))+uintptr(siz/2)
81 // obj, size, ref, ok := allocator.find(ptr)
82 // if obj != base || *ref != 0 || !ok {
83 // println("find", siz, obj, ref, ok)
84 // panic("fail")
85 // }
86 blocks[b].base = base
87 blocks[b].siz = siz
88 allocated += uint64(siz)
89 // println("Alloc", siz, base)
90 memset(base, 0xbb, siz)
91 bigger()