blob: b933f6be450efb2dfec7c609803e3ba6d8b13890 [file] [log] [blame]
Russ Coxe29ce172008-12-18 15:42:28 -08001// $G $D/$F.go && $L $F.$A && ./$A.out
2
3// Copyright 2009 The Go Authors. All rights reserved.
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7// Random malloc test.
8
9package main
10
11import (
12 "flag";
13 "malloc";
14 "rand";
15 "unsafe";
16)
17
Rob Pikec45d2a72009-01-09 13:42:46 -080018var chatty = flag.Bool("v", false, "chatty");
Russ Coxe29ce172008-12-18 15:42:28 -080019
20var footprint uint64;
21var allocated uint64;
22func bigger() {
Russ Coxf48cbfd2009-01-16 16:12:14 -080023 if f := malloc.GetStats().Sys; footprint < f {
Russ Coxe29ce172008-12-18 15:42:28 -080024 footprint = f;
Rob Pikec45d2a72009-01-09 13:42:46 -080025 if *chatty {
Russ Coxe29ce172008-12-18 15:42:28 -080026 println("Footprint", footprint, " for ", allocated);
27 }
28 if footprint > 1e9 {
29 panicln("too big");
30 }
31 }
32}
33
34// Prime the data structures by allocating one of
35// each block in order. After this, there should be
36// little reason to ask for more memory from the OS.
37func prime() {
38 for i := 0; i < 16; i++ {
39 b := malloc.Alloc(1<<uint(i));
40 malloc.Free(b);
41 }
42 for i := uint64(0); i < 256; i++ {
43 b := malloc.Alloc(i<<12);
44 malloc.Free(b);
45 }
46}
47
48func memset(b *byte, c byte, n uint64) {
49 np := uintptr(n);
50 for i := uintptr(0); i < np; i++ {
Russ Coxbe2edb52009-03-03 08:39:12 -080051 *(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(b))+i)) = c;
Russ Coxe29ce172008-12-18 15:42:28 -080052 }
53}
54
55func main() {
56 flag.Parse();
57// prime();
58 var blocks [1] struct { base *byte; siz uint64; };
59 for i := 0; i < 1<<12; i++ {
Rob Pikec45d2a72009-01-09 13:42:46 -080060 if i%(1<<10) == 0 && *chatty {
Russ Coxe29ce172008-12-18 15:42:28 -080061 println(i);
62 }
Russ Coxf48cbfd2009-01-16 16:12:14 -080063 b := rand.Int() % len(blocks);
Russ Coxe29ce172008-12-18 15:42:28 -080064 if blocks[b].base != nil {
65 // println("Free", blocks[b].siz, blocks[b].base);
66 malloc.Free(blocks[b].base);
67 blocks[b].base = nil;
68 allocated -= blocks[b].siz;
69 continue
70 }
Russ Coxf48cbfd2009-01-16 16:12:14 -080071 siz := uint64(rand.Int() >> (11 + rand.Uint32() % 20));
Russ Coxe29ce172008-12-18 15:42:28 -080072 base := malloc.Alloc(siz);
73 // ptr := uint64(syscall.BytePtr(base))+uint64(siz/2);
74 // obj, size, ref, ok := allocator.find(ptr);
75 // if obj != base || *ref != 0 || !ok {
76 // panicln("find", siz, obj, ref, ok);
77 // }
78 blocks[b].base = base;
79 blocks[b].siz = siz;
80 allocated += siz;
81 // println("Alloc", siz, base);
82 memset(base, 0xbb, siz);
83 bigger();
84 }
85}