raz / site / public / advanced / allocators.html

206 lines · 13.0 KiB · raw · history · last change de634aad

1<!doctype html>
2<html lang="en">
3<head>
4<meta charset="utf-8">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<title>Writing an allocator - More Raz</title>
7<meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux.">
8<meta name="theme-color" content="#E07A5F">
9<meta property="og:title" content="Writing an allocator - More Raz">
10<meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report.">
11<meta property="og:image" content="https://raz.lucela.org/social.png">
12<meta name="twitter:card" content="summary_large_image">
13<link rel="icon" href="../favicon.svg" type="image/svg+xml">
14<link rel="icon" href="../favicon-32.png" type="image/png" sizes="32x32">
15<link rel="apple-touch-icon" href="../apple-touch-icon.png">
16<link rel="stylesheet" href="../style.css">
17</head>
18<body>
19<header><nav><a class="mark" href="../index.html"><img src="../logo.svg" width="26" height="26" alt="">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header>
20<main>
21<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'>
22<li><a href="fmt.html">Output and formatting</a></li>
23<li><a href="bytes.html">Strings and bytes</a></li>
24<li><a href="collections.html">Lists, arrays, maps and sorting</a></li>
25<li><a href="files.html">Files and the command line</a></li>
26<li><a href="processes.html">Time, randomness and other programs</a></li>
27<li><a href="allocators.html" aria-current="page">Writing an allocator</a></li>
28</ol>
29<h3>Standing alone</h3><ol start='7'>
30<li><a href="static.html">A program with no run time</a></li>
31<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li>
32<li><a href="lifecycle.html">Starting, ending, and signals</a></li>
33<li><a href="targets.html">One module, one file per target</a></li>
34</ol>
35<h3>The machine</h3><ol start='11'>
36<li><a href="asm.html">Procedures in assembly</a></li>
37<li><a href="syscalls.html">System calls</a></li>
38<li><a href="listing.html">What the compiler makes</a></li>
39</ol>
40<h3>Shared memory</h3><ol start='14'>
41<li><a href="volatile.html">Volatile</a></li>
42<li><a href="atomics.html">Atomics</a></li>
43<li><a href="ordering.html">Ordering and publication</a></li>
44<li><a href="lockfree.html">A lock-free stack</a></li>
45<li><a href="ring.html">A ring buffer between threads</a></li>
46</ol></aside><article><p class="kicker">The library &middot; lesson 6 of 18</p><h1>Writing an allocator</h1>
47<p>An allocator is a record of two procedures, and that is all <code>Mem.Allocator</code> is:</p>
48<pre class="code"><code>type Allocator* = record
49 alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* nil if out of room *)
50 free*: proc(a: ^Allocator; p: ^U8);
51end;</code></pre>
52<p><code>NEW(p, a)</code> calls <code>a^.alloc(a, SIZE(T), alignment)</code> and zeroes what it gets. <code>Buf</code>, <code>List</code> and <code>Map</code> call the same procedures. So anything that fills in these two fields is an allocator, and everything in the library works with it.</p>
53<h2>An allocator over a fixed array</h2>
54<p>Here is one that needs no system calls at all: it hands out memory from an array in the program, a bump allocator. This is the kind a program with no operating system, or no room for a heap, uses. <code>free</code> has nothing to do; <code>reset</code> forgets everything.</p>
55<p>The trick that lets one procedure find its state is the same one <code>Arena</code> uses: the record puts <code>base: Mem.Allocator</code> first, so a <code>^Mem.Allocator</code> and a <code>^Bump</code> are the same address, and the procedure converts one to the other.</p>
56<div class="file"><span>Bump.raz</span></div><pre class="code"><code><span class="kw">module</span> Bump;
57<span class="kw">import</span> Mem;
58<span class="kw">import</span> SYSTEM;
59
60<span class="kw">type</span>
61 Bump* = <span class="kw">record</span>
62 base*: Mem.Allocator; <span class="comment">(* first, so that ^Bump(a) finds the rest *)</span>
63 mem: ^<span class="ty">U8</span>;
64 size, used*: <span class="ty">INT</span>;
65 <span class="kw">end</span>;
66
67<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>;
68<span class="kw">var</span> b: ^Bump; at: <span class="ty">INT</span>;
69<span class="kw">begin</span>
70 b := ^Bump(a);
71 at := (b^.used + align - <span class="number">1</span>) <span class="kw">div</span> align * align; <span class="comment">(* round up to align *)</span>
72 <span class="kw">if</span> (size &lt; <span class="number">0</span>) <span class="kw">or</span> (at + size &gt; b^.size) <span class="kw">then</span> <span class="kw">return</span> <span class="ty">nil</span>; <span class="kw">end</span>;
73 b^.used := at + size;
74 <span class="kw">return</span> b^.mem + at;
75<span class="kw">end</span>;
76
77<span class="kw">proc</span> free(_a: ^Mem.Allocator; _p: ^<span class="ty">U8</span>);
78<span class="kw">begin</span>
79<span class="kw">end</span>;
80
81<span class="comment">(* a bump allocator over the size bytes at mem *)</span>
82<span class="kw">proc</span> init*(b: ^Bump; mem: ^<span class="ty">U8</span>; size: <span class="ty">INT</span>);
83<span class="kw">begin</span>
84 b^.base := {alloc: alloc, free: free};
85 b^.mem := mem;
86 b^.size := size;
87 b^.used := <span class="number">0</span>;
88<span class="kw">end</span>;
89
90<span class="comment">(* everything forgotten, the memory used again *)</span>
91<span class="kw">proc</span> reset*(b: ^Bump);
92<span class="kw">begin</span>
93 b^.used := <span class="number">0</span>;
94<span class="kw">end</span>;
95
96<span class="kw">end</span> Bump.</code></pre>
97<div class="file"><span>Bumping.raz</span></div><pre class="code"><code><span class="kw">module</span> Bumping;
98<span class="kw">import</span> Out, Bump;
99<span class="kw">import</span> SYSTEM;
100
101<span class="kw">type</span> Point = <span class="kw">record</span> x, y: <span class="ty">INT</span>; <span class="kw">end</span>;
102
103<span class="kw">var</span> arena: [<span class="number">256</span>]<span class="ty">U8</span>; <span class="comment">(* the allocator&#x27;s whole world *)</span>
104
105<span class="kw">proc</span> main*;
106<span class="kw">var</span> b: Bump.Bump; p, q: ^Point; many: <span class="ty">INT</span>; r: ^Point;
107<span class="kw">begin</span>
108 Bump.init(SYSTEM.<span class="ty">ADR</span>(b), SYSTEM.<span class="ty">ADR</span>(arena[<span class="number">0</span>]), <span class="number">256</span>);
109 <span class="ty">NEW</span>(p, SYSTEM.<span class="ty">ADR</span>(b.base));
110 <span class="ty">NEW</span>(q, SYSTEM.<span class="ty">ADR</span>(b.base));
111 p^.x := <span class="number">1</span>; q^.y := <span class="number">2</span>;
112 Out.int(b.used); Out.str(<span class="string">&quot; bytes used by two points\n&quot;</span>);
113 many := <span class="number">2</span>;
114 <span class="kw">repeat</span>
115 <span class="ty">NEW</span>(r, SYSTEM.<span class="ty">ADR</span>(b.base));
116 <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(many); <span class="kw">end</span>;
117 <span class="kw">until</span> r = <span class="ty">nil</span>;
118 Out.int(many); Out.str(<span class="string">&quot; points fit in 256 bytes\n&quot;</span>);
119 Bump.reset(SYSTEM.<span class="ty">ADR</span>(b));
120 <span class="ty">NEW</span>(r, SYSTEM.<span class="ty">ADR</span>(b.base));
121 <span class="kw">if</span> r # <span class="ty">nil</span> <span class="kw">then</span> Out.str(<span class="string">&quot;room again after a reset\n&quot;</span>); <span class="kw">end</span>;
122<span class="kw">end</span>;
123
124<span class="kw">end</span> Bumping.</code></pre>
125<pre class="output"><code>32 bytes used by two points
12616 points fit in 256 bytes
127room again after a reset
128</code></pre>
129<p>An allocator that runs out says so with <code>nil</code>, and the caller decides what that means. Nothing else in the program is touched.</p>
130<h2>An allocator that counts</h2>
131<p>An allocator can wrap another. This one forwards to whatever it is given and keeps count, which is how to find out what a piece of code allocates, or to prove that a path allocates nothing.</p>
132<div class="file"><span>Counted.raz</span></div><pre class="code"><code><span class="kw">module</span> Counted;
133<span class="kw">import</span> Mem;
134<span class="kw">import</span> SYSTEM;
135
136<span class="kw">type</span>
137 Counted* = <span class="kw">record</span>
138 base*: Mem.Allocator; <span class="comment">(* first *)</span>
139 inner: ^Mem.Allocator;
140 allocs*, frees*, bytes*: <span class="ty">INT</span>;
141 <span class="kw">end</span>;
142
143<span class="kw">proc</span> alloc(a: ^Mem.Allocator; size, align: <span class="ty">INT</span>): ^<span class="ty">U8</span>;
144<span class="kw">var</span> c: ^Counted; p: ^<span class="ty">U8</span>;
145<span class="kw">begin</span>
146 c := ^Counted(a);
147 p := Mem.alloc(c^.inner, size, align);
148 <span class="kw">if</span> p # <span class="ty">nil</span> <span class="kw">then</span> <span class="ty">INC</span>(c^.allocs); <span class="ty">INC</span>(c^.bytes, size); <span class="kw">end</span>;
149 <span class="kw">return</span> p;
150<span class="kw">end</span>;
151
152<span class="kw">proc</span> free(a: ^Mem.Allocator; p: ^<span class="ty">U8</span>);
153<span class="kw">var</span> c: ^Counted;
154<span class="kw">begin</span>
155 c := ^Counted(a);
156 <span class="ty">INC</span>(c^.frees);
157 Mem.free(c^.inner, p);
158<span class="kw">end</span>;
159
160<span class="comment">(* a counting allocator in front of inner *)</span>
161<span class="kw">proc</span> init*(c: ^Counted; inner: ^Mem.Allocator);
162<span class="kw">begin</span>
163 c^.base := {alloc: alloc, free: free};
164 c^.inner := inner;
165 c^.allocs := <span class="number">0</span>;
166 c^.frees := <span class="number">0</span>;
167 c^.bytes := <span class="number">0</span>;
168<span class="kw">end</span>;
169
170<span class="kw">end</span> Counted.</code></pre>
171<div class="file"><span>Audit.raz</span></div><pre class="code"><code><span class="kw">module</span> Audit;
172<span class="kw">import</span> Fmt, Heap, Mem, Buf, Counted, Names := List([]<span class="kw">const</span> <span class="ty">U8</span>);
173<span class="kw">import</span> SYSTEM;
174
175<span class="kw">proc</span> main*;
176<span class="kw">var</span> c: Counted.Counted; b: Buf.Buf; l: Names.List; i: <span class="ty">INT</span>; p: ^<span class="ty">U8</span>;
177<span class="kw">begin</span>
178 Counted.init(SYSTEM.<span class="ty">ADR</span>(c), Heap.heap);
179 Buf.init(b, SYSTEM.<span class="ty">ADR</span>(c.base));
180 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">200</span> <span class="kw">do</span> Buf.str(b, <span class="string">&quot;0123456789&quot;</span>); <span class="kw">end</span>;
181 Fmt.print(<span class="string">&quot;a buffer of {} bytes took {} allocations\n&quot;</span>,
182 [Fmt.int(b.len), Fmt.int(c.allocs)]);
183 Buf.done(b);
184
185 Names.init(l, SYSTEM.<span class="ty">ADR</span>(c.base));
186 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">10</span> <span class="kw">do</span> _ := Names.push(l, <span class="string">&quot;x&quot;</span>); <span class="kw">end</span>;
187 Fmt.print(<span class="string">&quot;{} allocations in all, {} frees so far\n&quot;</span>, [Fmt.int(c.allocs), Fmt.int(c.frees)]);
188 Names.clear(l);
189 Fmt.print(<span class="string">&quot;{} frees after clear\n&quot;</span>, [Fmt.int(c.frees)]);
190
191 p := Mem.alloc(SYSTEM.<span class="ty">ADR</span>(c.base), <span class="number">64</span>, <span class="number">8</span>);
192 Mem.free(SYSTEM.<span class="ty">ADR</span>(c.base), p);
193<span class="kw">end</span>;
194
195<span class="kw">end</span> Audit.</code></pre>
196<pre class="output"><code>a buffer of 2000 bytes took 6 allocations
19716 allocations in all, 6 frees so far
19816 frees after clear
199</code></pre>
200<p>A <code>Buf</code> grows by doubling, so two thousand bytes took a handful of allocations and not two hundred. That is the sort of thing a counting allocator is for.</p>
201<h2>What to take from this</h2>
202<ul><li>An allocator is a value, so it is passed, wrapped, swapped in a test and replaced by a bump allocator in a program with no heap.</li><li>A library function that needs memory takes the allocator as a parameter, so its caller owns the policy.</li><li>An allocator can use the record-first trick to carry any state it needs, because converting a pointer to a record's first field and back is the same address.</li></ul><p class="tryit">Save a program under its module&rsquo;s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="processes.html">&larr; Time, randomness and other programs</a><a href="index.html">Contents</a><a class="next" href="static.html">A program with no run time &rarr;</a></div></article></div>
203</main>
204<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer>
205</body>
206</html>