| 1 | (* Memory: Allocator, the interface every allocator offers, and pages |
| 2 | from the system. NEW(p, a) calls a^.alloc. *) |
| 3 | module Mem; |
| 4 | import Sys, Rt; |
| 5 | import SYSTEM; |
| 6 | |
| 7 | type |
| 8 | Allocator* = record |
| 9 | alloc*: proc(a: ^Allocator; size, align: INT): ^U8; (* or nil *) |
| 10 | free*: proc(a: ^Allocator; p: ^U8); |
| 11 | end; |
| 12 | |
| 13 | const |
| 14 | (* The size of a page of memory, in bytes. *) |
| 15 | Page* = 4096; |
| 16 | |
| 17 | (* size bytes, rounded up to whole pages, zeroed; or nil. *) |
| 18 | proc pages*(size: INT): ^U8; |
| 19 | begin |
| 20 | return Sys.mmap((size + Page - 1) div Page * Page); |
| 21 | end; |
| 22 | |
| 23 | (* Gives back to the system the pages that pages gave as p, given the |
| 24 | same size. *) |
| 25 | proc unmap*(p: ^U8; size: INT); |
| 26 | begin |
| 27 | Sys.munmap(p, (size + Page - 1) div Page * Page); |
| 28 | end; |
| 29 | |
| 30 | (* a^.alloc(a, size, align): size bytes from a, at a multiple of |
| 31 | align; or nil. *) |
| 32 | proc alloc*(a: ^Allocator; size, align: INT): ^U8; |
| 33 | begin |
| 34 | return a^.alloc(a, size, align); |
| 35 | end; |
| 36 | |
| 37 | (* a^.free(a, p): gives p back to a, which gave it. *) |
| 38 | proc free*(a: ^Allocator; p: ^U8); |
| 39 | begin |
| 40 | a^.free(a, p); |
| 41 | end; |
| 42 | |
| 43 | (* The module's test. *) |
| 44 | proc main*; |
| 45 | var p: ^U8; i: INT; |
| 46 | begin |
| 47 | p := pages(10000); |
| 48 | if p = nil then Rt.stop("Mem.pages"); end; |
| 49 | for i := 0 to 12287 do |
| 50 | if p[i] # 0 then Rt.stop("Mem.pages: not zeroed"); end; |
| 51 | end; |
| 52 | p[12287] := 1; |
| 53 | unmap(p, 10000); |
| 54 | end; |
| 55 | |
| 56 | end Mem. |