blob: 2d6e36ae839214158cde8d1e1e42f0110a1bd992 [file] [log] [blame]
Russ Cox3f8aa662008-12-05 15:24:18 -08001// 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#include "runtime.h"
Russ Cox0d3a0432009-03-30 00:01:07 -07006#include "defs.h"
Russ Cox3f8aa662008-12-05 15:24:18 -08007
8// Stubs for memory management.
9// In a separate file so they can be overridden during testing of gc.
10
11enum
12{
13 NHUNK = 20<<20,
Russ Cox3f8aa662008-12-05 15:24:18 -080014};
15
Russ Cox3f8aa662008-12-05 15:24:18 -080016// Convenient wrapper around mmap.
17static void*
18brk(uint32 n)
19{
20 byte *v;
21
Russ Cox0f4f2a62009-02-06 13:46:56 -080022 v = sys_mmap(nil, n, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_ANON|MAP_PRIVATE, 0, 0);
Russ Cox3f8aa662008-12-05 15:24:18 -080023 m->mem.nmmap += n;
24 return v;
25}
26
27// Allocate n bytes of memory. Note that this gets used
28// to allocate new stack segments, so at each call to a function
29// you have to ask yourself "would it be okay to call mal recursively
30// right here?" The answer is yes unless we're in the middle of
31// editing the malloc state in m->mem.
32void*
Russ Coxda0a7d72008-12-19 03:13:39 -080033oldmal(uint32 n)
Russ Cox3f8aa662008-12-05 15:24:18 -080034{
35 byte* v;
36
37 // round to keep everything 64-bit aligned
38 n = rnd(n, 8);
39
40 // be careful. calling any function might invoke
41 // mal to allocate more stack.
42 if(n > NHUNK) {
43 v = brk(n);
44 } else {
45 // allocate a new hunk if this one is too small
46 if(n > m->mem.nhunk) {
47 // here we're in the middle of editing m->mem
48 // (we're about to overwrite m->mem.hunk),
49 // so we can't call brk - it might call mal to grow the
50 // stack, and the recursive call would allocate a new
51 // hunk, and then once brk returned we'd immediately
52 // overwrite that hunk with our own.
53 // (the net result would be a memory leak, not a crash.)
Ian Lance Taylor9b8da822009-01-13 09:55:24 -080054 // so we have to call sys_mmap directly - it is written
Russ Cox3f8aa662008-12-05 15:24:18 -080055 // in assembly and tagged not to grow the stack.
56 m->mem.hunk =
Russ Cox0f4f2a62009-02-06 13:46:56 -080057 sys_mmap(nil, NHUNK, PROT_READ|PROT_WRITE|PROT_EXEC,
Russ Cox3f8aa662008-12-05 15:24:18 -080058 MAP_ANON|MAP_PRIVATE, 0, 0);
59 m->mem.nhunk = NHUNK;
60 m->mem.nmmap += NHUNK;
61 }
62 v = m->mem.hunk;
63 m->mem.hunk += n;
64 m->mem.nhunk -= n;
65 }
66 m->mem.nmal += n;
67 return v;
68}
69
70void
Russ Cox150a6452009-06-30 20:01:59 -070071sysยทmal(uint32 n, uint8 *ret)
Russ Cox3f8aa662008-12-05 15:24:18 -080072{
73 ret = mal(n);
74 FLUSH(&ret);
75}