| | @@ -7,7 +7,7 @@ |
| 7 | 7 | twice, or freeing what the heap never gave out, stops the program. |
| 8 | 8 | One lock keeps it whole across threads. *) |
| 9 | 9 | module Heap; |
| 10 | | -import Mem, Lock, Rt; |
| 10 | +import Mem, Lock, Rt, Sys; |
| 11 | 11 | |
| 12 | 12 | const |
| 13 | 13 | Classes = 9; |
| | @@ -25,9 +25,13 @@ |
| 25 | 25 | cur: ^U8; (* where the next new small block comes from *) |
| 26 | 26 | left: INT; |
| 27 | 27 | lock: Lock.Lock; |
| 28 | | - std: Mem.Allocator; |
| 28 | + std, surer: Mem.Allocator; |
| 29 | 29 | (* The heap, for NEW(p, Heap.heap) and Mem's procedures. *) |
| 30 | 30 | heap*: ^Mem.Allocator; |
| 31 | + (* The heap, but running out of memory stops the program, as |
| 32 | + Buf.add does, instead of giving nil: for NEW where nil would be |
| 33 | + a bug nobody checks for. *) |
| 34 | + sure*: ^Mem.Allocator; |
| 31 | 35 | |
| 32 | 36 | (* The block p, with size for its header, given out. *) |
| 33 | 37 | proc give(p: ^U8; size: INT): ^U8; |
| | @@ -107,10 +111,24 @@ |
| 107 | 111 | end; |
| 108 | 112 | end; |
| 109 | 113 | |
| 114 | +(* The heap's alloc, but with no room the program stops, with the |
| 115 | + calls under way. *) |
| 116 | +proc allocSure(a: ^Mem.Allocator; size, align: INT): ^U8; |
| 117 | +var p: ^U8; |
| 118 | +begin |
| 119 | + p := alloc(a, size, align); |
| 120 | + if p = nil then |
| 121 | + _ := Sys.write(Sys.stderr, "Heap: out of memory\n"); |
| 122 | + Rt.trace; |
| 123 | + Rt.exit(2); |
| 124 | + end; |
| 125 | + return p; |
| 126 | +end; |
| 127 | + |
| 110 | 128 | (* The module's test: blocks of every class and big ones, written, |
| 111 | 129 | freed and taken again. *) |
| 112 | 130 | proc main*; |
| 113 | | -var p: [40]^U8; i, j, n: INT; again: ^U8; |
| 131 | +var p: [40]^U8; i, j, n: INT; again: ^U8; q: ^INT; |
| 114 | 132 | begin |
| 115 | 133 | for i := 0 to 39 do |
| 116 | 134 | n := (i * i * 37) mod 9000 + 1; |
| | @@ -129,6 +147,10 @@ |
| 129 | 147 | again := Mem.alloc(heap, (25 * 37) mod 9000 + 1, 8); |
| 130 | 148 | if again # p[5] then Rt.stop("Heap: a freed block isn't taken again"); end; |
| 131 | 149 | for i := 0 to 39 do Mem.free(heap, p[i]); end; |
| 150 | + NEW(q, sure); |
| 151 | + if (q = nil) or (INT(q) mod 8 # 0) then Rt.stop("Heap: sure"); end; |
| 152 | + q^ := 7; |
| 153 | + Mem.free(sure, ^U8(q)); |
| 132 | 154 | if Mem.alloc(heap, -1, 8) # nil then Rt.stop("Heap: negative size"); end; |
| 133 | 155 | if Mem.alloc(heap, 7FFFFFFFFFFFFFFFH - 4, 8) # nil then Rt.stop("Heap: huge size"); end; |
| 134 | 156 | end; |
| | @@ -136,4 +158,6 @@ |
| 136 | 158 | begin |
| 137 | 159 | std := {alloc: alloc, free: free}; |
| 138 | 160 | heap := ADR(std); |
| 161 | + surer := {alloc: allocSure, free: free}; |
| 162 | + sure := ADR(surer); |
| 139 | 163 | end Heap. |