github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/runtime/mallocrand.go (about) 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. 4 5 // +build ignore 6 7 // Random malloc test. 8 9 package main 10 11 import ( 12 "flag" 13 "math/rand" 14 "runtime" 15 "unsafe" 16 ) 17 18 var chatty = flag.Bool("v", false, "chatty") 19 20 var footprint uint64 21 var allocated uint64 22 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) 30 } 31 if footprint > 1e9 { 32 println("too big") 33 panic("fail") 34 } 35 } 36 } 37 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) 45 } 46 for i := uintptr(0); i < 256; i++ { 47 b := runtime.Alloc(i << 12) 48 runtime.Free(b) 49 } 50 } 51 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 56 } 57 } 58 59 func main() { 60 flag.Parse() 61 // prime() 62 var blocks [1]struct { 63 base *byte 64 siz uintptr 65 } 66 for i := 0; i < 1<<10; i++ { 67 if i%(1<<10) == 0 && *chatty { 68 println(i) 69 } 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 77 } 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() 92 } 93 }