| | @@ -0,0 +1,1917 @@ |
| 1 | +# MEM_PROPOSAL: a memory-safe raz |
| 2 | + |
| 3 | +**Status.** A proposal, drafted 2026-10-17 for the owner's review. |
| 4 | +Nothing in it is built. It assumes that anything may change: the |
| 5 | +language, the library, the compiler, and the programs written for |
| 6 | +them. It builds on two entries of `PROPOSALS.md`, "Less that is |
| 7 | +undefined" and part 3 of "What a call does with its arguments" (`ret` |
| 8 | +and `keep`), and goes further than either: it puts them together into |
| 9 | +one promise, closes the holes they leave open, and counts the cost. |
| 10 | + |
| 11 | +**In one paragraph.** Raz checks where memory is (an index against a |
| 12 | +length, `nil`, zeroed variables) but not when it is still there, and |
| 13 | +anything that can break memory may stand in any module. This proposal |
| 14 | +splits modules in two. An `unsafe;` module may do what raz allows today. |
| 15 | +Every other module is safe: the compiler holds it to rules under which |
| 16 | +it can't read or write memory that isn't a live variable of the right |
| 17 | +type. The rules are four: |
| 18 | + |
| 19 | +1. Pointer arithmetic, casts, `ADR`, C and code procedures go behind |
| 20 | + `unsafe;`. |
| 21 | +2. A slice or pointer *lent* by a variable can't outlive that |
| 22 | + variable. Most of this is checked when compiling, and it takes |
| 23 | + PROPOSALS' `ret` and `keep`. |
| 24 | +3. A container that hands out slices of its memory *counts* them, |
| 25 | + and won't free a block while one is held. |
| 26 | +4. Safe code doesn't free heap memory by hand. It keeps that memory |
| 27 | + for the life of the program, or holds it in a container or a |
| 28 | + `Pool` that frees it. |
| 29 | + |
| 30 | +The library's own unsafe modules are trusted to keep the promise, as |
| 31 | +a safe program is trusted to keep its logic. The cost, measured below: |
| 32 | + |
| 33 | +- **Programs:** nothing for code that keeps to slices and records. 1.5 |
| 34 | + to 2 times for chasing a linked structure through checked handles |
| 35 | + instead of raw pointers, where a program chooses handles. |
| 36 | +- **Compiler:** about 5% more instructions, if its scanner checks its |
| 37 | + buffer instead of reading it through a pointer. |
| 38 | +- **Ergonomics:** a record can't keep a slice into a buffer that |
| 39 | + belongs to someone else. |
| 40 | + |
| 41 | +--- |
| 42 | + |
| 43 | +## Contents |
| 44 | + |
| 45 | +1. Motivation |
| 46 | +2. What the code we have does: a survey |
| 47 | +3. The guarantee |
| 48 | +4. The design, in brief |
| 49 | +5. Part A: the fence, `unsafe;` |
| 50 | +6. Part B: lending, `ret` and `keep` |
| 51 | +7. Part C: owners that count what they lend |
| 52 | +8. Part D: the heap without `free` |
| 53 | +9. Part E: threads |
| 54 | +10. Part F: the small mends |
| 55 | +11. Part G: a debugging heap |
| 56 | +12. Raz beside other languages |
| 57 | +13. Performance |
| 58 | +14. Ergonomics |
| 59 | +15. What breaks |
| 60 | +16. Changes to the report |
| 61 | +17. Changes to the library |
| 62 | +18. Changes to the compiler |
| 63 | +19. Alternatives considered |
| 64 | +20. Order of work |
| 65 | +21. Open questions |
| 66 | +- Appendix 1: the survey's numbers |
| 67 | +- Appendix 2: the benchmarks |
| 68 | +- Appendix 3: the five programs of section 1 |
| 69 | + |
| 70 | +--- |
| 71 | + |
| 72 | +## 1. Motivation |
| 73 | + |
| 74 | +### 1.1 What raz promises today |
| 75 | + |
| 76 | +| Check | Today | |
| 77 | +|---|---| |
| 78 | +| Index and slice bounds | checked, unless `check off;` | |
| 79 | +| `nil` dereference, `nil` procedure | stops the program | |
| 80 | +| Division by zero, `low / -1` | stops the program | |
| 81 | +| Stack overflow | stops the program | |
| 82 | +| Variables start at zero | always | |
| 83 | +| Integer overflow | wraps, defined | |
| 84 | +| A variant's fields read only through `match` | always | |
| 85 | +| A view's bytes stay inside its variable | checked | |
| 86 | +| Integer to enumeration conversion | checked | |
| 87 | +| A slice returned from its own frame | an error, but only for a direct `return` (7.3) | |
| 88 | +| Use after free, after `Arena.reset`, after a `Vec` grows | nothing | |
| 89 | +| A slice kept past its frame by any other route | nothing | |
| 90 | +| A slice of a call's array kept past its statement | nothing | |
| 91 | +| Pointer arithmetic, `p[i]` | unchecked, anywhere | |
| 92 | +| Integer to pointer, pointer to pointer | allowed, anywhere | |
| 93 | +| `ADR` of a local, kept | allowed, anywhere | |
| 94 | +| C, code procedures, `SYSCALL` | allowed, anywhere | |
| 95 | +| A race tearing a slice or a variant | the report says nothing becomes undefined (7.6); it does | |
| 96 | + |
| 97 | +This is close to Oberon's or Pascal's promise, without a garbage |
| 98 | +collector behind it. Spatial safety (indexes, lengths, `nil`) is |
| 99 | +mostly there. Temporal safety (whether memory is still there) isn't |
| 100 | +there at all. Nothing marks the code that can break memory, so any |
| 101 | +module may. |
| 102 | + |
| 103 | +### 1.2 Five programs that compile with no warning |
| 104 | + |
| 105 | +Each is complete, compiled by today's compiler with no warning, and run. |
| 106 | +The full texts are in appendix 3. |
| 107 | + |
| 108 | +**Appending a buffer to itself.** |
| 109 | + |
| 110 | +``` |
| 111 | +Buf.init(b, Heap.heap); |
| 112 | +for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) |
| 113 | +Buf.str(b, Buf.bytes(b)); (* doubles it, or should *) |
| 114 | +``` |
| 115 | + |
| 116 | +`Buf.str` grows `b` first: it allocates a new block, copies the bytes |
| 117 | +and frees the old block. It then copies from `s`, which still points at |
| 118 | +the old block. It prints 24 `a`s, as it should, because the heap didn't |
| 119 | +reuse the freed block in time. With another allocator, or another |
| 120 | +thread using the heap, it prints garbage. Nothing tells the programmer |
| 121 | +that this line is wrong. A test passes. |
| 122 | + |
| 123 | +**A slice kept across a `Vec`'s growth.** |
| 124 | + |
| 125 | +``` |
| 126 | +first := Vec.all(v); (* good until v next grows *) |
| 127 | +p := Vec.add(v); (* grows: first now points at freed memory *) |
| 128 | +... |
| 129 | +p^ := -1; (* after another growth: writes into a block the heap took back *) |
| 130 | +Out.int(first[0]); (* prints 1, as if nothing were wrong *) |
| 131 | +``` |
| 132 | + |
| 133 | +The library's comments say "good until the array next grows". The |
| 134 | +compiler doesn't know that comment. |
| 135 | + |
| 136 | +**A slice of the frame, through a call.** |
| 137 | + |
| 138 | +``` |
| 139 | +proc head(var h: Hex): []U8; begin return h[0..8]; end; (* allowed *) |
| 140 | +proc short: []U8; var h: Hex; |
| 141 | +begin ... return head(h); end; (* not caught *) |
| 142 | +``` |
| 143 | + |
| 144 | +The caller prints `########`, the bytes the next call left in the dead |
| 145 | +frame. 7.3 catches `return h[0..8]` in `short` but not the same slice |
| 146 | +handed back through `head`. |
| 147 | + |
| 148 | +**A map keeping a slice of a frame.** |
| 149 | + |
| 150 | +``` |
| 151 | +proc remember(n: INT); |
| 152 | +var buf: [8]U8; |
| 153 | +begin |
| 154 | + buf := "name-000"; buf[7] := U8('0' + n); |
| 155 | + _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) |
| 156 | +end; |
| 157 | +``` |
| 158 | + |
| 159 | +After `remember(1); remember(2);` both `name-001` and `name-002` are |
| 160 | +"missing": the map's keys point at a frame that is gone. Every caller |
| 161 | +of `Map([]U8, ...).put` must know, from the documentation alone, that |
| 162 | +the key is kept. |
| 163 | + |
| 164 | +**A slice of a call's array, kept.** |
| 165 | + |
| 166 | +``` |
| 167 | +a := named('a')[0..8]; |
| 168 | +b := named('b')[0..8]; |
| 169 | +Out.str(a); Out.str(" "); Out.str(b); |
| 170 | +``` |
| 171 | + |
| 172 | +It prints `name-..b ^A^@^@^@^@^@^@^@`. Both arrays used the same |
| 173 | +temporary, so `a` shows `b`'s bytes and `b` shows whatever came after. |
| 174 | +Section 8 says this is undefined, and nothing catches it. |
| 175 | + |
| 176 | +None of these is exotic. Three are what the library's own |
| 177 | +documentation warns of; two are what 7.3 and 8 warn of. Each runs to |
| 178 | +the end with status 0. |
| 179 | + |
| 180 | +### 1.3 Why it matters for raz in particular |
| 181 | + |
| 182 | +- **Raz's audience.** CLAUDE.md asks that the compiler be "a model of |
| 183 | + plain code that a beginner can follow". A beginner can't follow a |
| 184 | + rule that lives only in a comment ("good until it next grows"). A |
| 185 | + language that checks every index and then lets a slice outlive its |
| 186 | + buffer teaches a false sense of safety: the checks cover the easy |
| 187 | + half. |
| 188 | +- **Undefined behaviour passes tests.** In four of the five programs |
| 189 | + above the output is plausible, or right. The heap's free lists keep |
| 190 | + freed bytes for a while; a dead frame keeps its bytes until the |
| 191 | + next call. A program can carry such a bug for years. |
| 192 | +- **No fence means no audit.** Today, to know whether a program can |
| 193 | + corrupt memory, you read all of it. With a fence, you read the |
| 194 | + modules that say `unsafe;`, and `grep` finds them. The survey |
| 195 | + (section 2) shows how few modules would need to say it. |
| 196 | +- **The library is growing.** Each container added (`Vec`, `Map`, `Buf`, |
| 197 | + `List`, and `Svec` in sauce) adds rules of the "good until" kind. Those |
| 198 | + rules should be the compiler's to check. |
| 199 | +- **Threads.** `Thread` and `Lock` are in the library, and rnet and |
| 200 | + rsqlite use them. A race on a slice reaches any memory today, though |
| 201 | + 7.6 promises it can't. |
| 202 | + |
| 203 | +--- |
| 204 | + |
| 205 | +## 2. What the code we have does: a survey |
| 206 | + |
| 207 | +### 2.1 How it was measured |
| 208 | + |
| 209 | +For an exact count, not an estimate from `grep`, the compiler itself |
| 210 | +was changed in a scratch copy. It printed one line for each operation |
| 211 | +this proposal would fence, where it compiled one: a pointer indexed or |
| 212 | +sliced, pointer arithmetic, a conversion to or from a pointer, `ADR`, |
| 213 | +`PTR`, `SYSCALL`, a view, `NEW` and every dereference. Each program |
| 214 | +and each library module's test was compiled with it. The places are |
| 215 | +counted once each, whatever number of programs compiled them. The |
| 216 | +hooks stand where most of the fence's checks would go (section 18). |
| 217 | + |
| 218 | +Code surveyed: |
| 219 | + |
| 220 | +| Code | Version | Lines | How | |
| 221 | +|---|---|---|---| |
| 222 | +| raz `src/` (the compiler) | main | 14,323 | compiler-counted | |
| 223 | +| raz `lib/` | main | 10,291 | compiler-counted | |
| 224 | +| raz `tools/`, `examples/`, `test/libc` | main | 2,207+ | compiler-counted | |
| 225 | +| rnet (HTTP, DNS, TLS seams) | raz 0.15.0 | 5,111 | compiler-counted, with 0.15.0's `lib/` | |
| 226 | +| rjson | raz 0.15.0 | 1,882 | compiler-counted, with 0.15.0's `lib/` | |
| 227 | +| rflate (inflate) | raz 0.15.0 | 1,319 | compiler-counted, with 0.15.0's `lib/` | |
| 228 | +| rsqlite (SQLite over C) | raz 0.18.0 | 705 | compiler-counted, with 0.18.0's `lib/` | |
| 229 | +| rterm | raz 0.15.0 | 101 | compiler-counted | |
| 230 | +| rmacs (an editor, archived) | raz v0.5.0+7 | 4,932 | `grep`: written before `INT`, today's compiler refuses it | |
| 231 | +| ravite (an editor) | raz v0.5.0+7 | 2,460 | `grep`, as rmacs | |
| 232 | +| rlX11 (X11 over a socket) | raz v0.3.0+52 | 7,026 | `grep`, as rmacs | |
| 233 | + |
| 234 | +About 50,000 lines in all. Code written for an older raz was compiled |
| 235 | +by today's compiler against the library of the version it was written |
| 236 | +for. The full tables are in appendix 1. |
| 237 | + |
| 238 | +### 2.2 What it found |
| 239 | + |
| 240 | +**Nobody uses `check off;`.** Not one module in 50,000 lines. Bounds |
| 241 | +checks are cheap enough that no one has wanted them off. |
| 242 | + |
| 243 | +**Almost every `ADR` is an argument to the library.** Of rnet's 572 |
| 244 | +`ADR`s, 571 are arguments, and so are 556 of rmacs's 560 and all 77 of |
| 245 | +rjson's. They are the library's old pointer parameters, which report |
| 246 | +2026-10.33 made `var` and `const`; code written for v0.19.0 and later |
| 247 | +has lost them already. `src/`, which has been ported, keeps 27, and |
| 248 | +none of them needs to be an `ADR`: |
| 249 | + |
| 250 | +| What `src/` does with `ADR` and pointer casts | Sites | The safe form | |
| 251 | +|---|---|---| |
| 252 | +| a grown array: `^Chunk(Scan.regrab(^U8(chunks), ...))` | 35 | `Vec(Chunk)`, or a slice and `Mem`'s growth, in one trusted module | |
| 253 | +| a real's bits: `p := ^F64(ADR(x.val))` | 6 | a view, `x.val.(F64)`, safe today | |
| 254 | +| a slice passed as two words: `Scan.intern(ADR(s[0]), LEN(s))` | 7 | `Scan.intern(s)`: a slice parameter | |
| 255 | +| out-parameters: `isReg(w, ADR(r), ADR(size))` | 5 | `var r, size` | |
| 256 | +| a pointer to a local record: `curLoop := ADR(lp)` | 1 | a field index, or `var` | |
| 257 | +| `SYSCALL(4, ...)`: `stat` | 1 | `Sys.info` | |
| 258 | + |
| 259 | +**Pointer indexing is buffers.** `src/` indexes a pointer 277 times |
| 260 | +and slices one 30 times, nearly all in six modules: `Scan` (76), `Link` |
| 261 | +(63), `Chunk` (53), `X64` (23), `Elf` (17) and `Diag` (15). Each keeps |
| 262 | +a byte or record buffer that it grows by hand: `text[pc + i] := ...`, |
| 263 | +`lp[lpLen] := ...`, `buf[at + i] := ...`. That is `Vec` and `Buf` |
| 264 | +written out again, for speed, without checks. The scanner reads its |
| 265 | +source through `buf: ^U8`, past the end to a sentinel zero. |
| 266 | + |
| 267 | +**Dereferences are everywhere and harmless.** 1,015 in `src/` (`Parse` |
| 268 | +517, `Item` 256, `Sym` 106): `o^.typ`, `t^.base`. Every one is a pointer |
| 269 | +from `NEW` on the heap, which the compiler never frees. Under part D |
| 270 | +they stay as they are, unchecked and free of cost. |
| 271 | + |
| 272 | +**The library is where the unsafe code is.** `Sys` (287 operations, |
| 273 | +129 of them `SYSCALL`), `Rt` (111), `Thread` (33), `Heap` (16) and `Map` |
| 274 | +(19). It is the code that should be trusted and read twice. `Math`, |
| 275 | +`Out`, `Sort` and `Width` have none; `Str`, `Fmt`, `Opt`, `Files` and |
| 276 | +`Lock` have two to five each, all of them avoidable. |
| 277 | + |
| 278 | +**Slices held from containers.** 35 places assign `Buf.bytes`, |
| 279 | +`Vec.all` or `Windows.all` to a variable and use it over several |
| 280 | +statements; the rest pass it straight on. Some places store one in a |
| 281 | +record: |
| 282 | + |
| 283 | +``` |
| 284 | +m^.body := Buf.bytes(ADR(m^.data)); (* rnet Http.readWhole *) |
| 285 | +m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}; (* l is a slice of m^.head's bytes *) |
| 286 | +res^.body := Buf.bytes(ADR(text)); (* rnet's test server: a module Buf, reset per request *) |
| 287 | +``` |
| 288 | + |
| 289 | +`Http.Message` holds slices into two buffers of its own. It is right, |
| 290 | +as long as nobody grows `m^.head` after the headers are read and |
| 291 | +nobody uses the headers after `Http.done`. The compiler knows neither |
| 292 | +condition. Section 14 shows what this pattern costs under the |
| 293 | +proposal. |
| 294 | + |
| 295 | +**Records that hold slices** (each one is a place where something must |
| 296 | +decide how long the slice lives): `src/` 10, `lib/` 22, rnet 12, rjson 8, |
| 297 | +ravite 5, rmacs 4, `tools/` 4, rlX11 3, rflate 2, rsqlite 1. |
| 298 | + |
| 299 | +**Threads are rare.** Two of the eight other repositories spawn |
| 300 | +threads (rnet's server, rsqlite's test). `src/`, the tools and the |
| 301 | +editors have none. |
| 302 | + |
| 303 | +**Freeing is rare too.** `Mem.free`, `Heap`'s `free` or `Str.free` by |
| 304 | +hand: `src/` 7 (all in grown arrays), rmacs 9, rjson 6, ravite 2, |
| 305 | +rlX11 1, rnet, rflate and rsqlite 0. Programs free memory through |
| 306 | +`done` on a container (rnet 30, rmacs 16) far more than by hand: 54 |
| 307 | +`done`s to 26 frees, outside the library. |
| 308 | + |
| 309 | +### 2.3 What the survey says about the design |
| 310 | + |
| 311 | +1. A fence costs little. Outside the library and the compiler's |
| 312 | + buffers, the operations it fences are almost all `ADR`s that the |
| 313 | + v0.19.0 library already removed. In `src/`, the fenced |
| 314 | + operations are buffers and small habits, each with a safe form. |
| 315 | +2. Leaving pointers unchecked costs nothing as long as nothing frees |
| 316 | + them. The compiler's 1,015 dereferences are of heap memory that |
| 317 | + lives as long as the program. Making `free` unsafe, and giving |
| 318 | + containers the job of freeing (part D), keeps those dereferences |
| 319 | + free of cost. |
| 320 | +3. The hard case is a slice of a container's memory held while the |
| 321 | + container changes. It is found in rmacs, ravite, rnet and the |
| 322 | + library itself (`Fmt`, `Opt`), and nothing today checks it. Part C |
| 323 | + is aimed at it. |
| 324 | +4. Threads can wait for a weaker rule than Rust's (part E), since few |
| 325 | + programs use them. |
| 326 | + |
| 327 | +--- |
| 328 | + |
| 329 | +## 3. The guarantee |
| 330 | + |
| 331 | +The proposal puts one paragraph into section 10 of the report, in |
| 332 | +place of today's list of what isn't defined: |
| 333 | + |
| 334 | +> **The guarantee.** A program is *safe* if none of its modules says |
| 335 | +> `unsafe;`, the library's aside, and its threads race (7.6) only on |
| 336 | +> variables of a basic, pointer, procedure or slice type. A safe |
| 337 | +> program reads and writes only variables that exist, each as a value |
| 338 | +> of its own type, and calls only procedures. It does what this report |
| 339 | +> says, or stops with status 2 and says where and why. The library's |
| 340 | +> unsafe modules are trusted to keep this promise for every use a safe |
| 341 | +> program can make of what they export. |
| 342 | + |
| 343 | +What the guarantee covers: |
| 344 | + |
| 345 | +- **Spatial:** no read or write outside a variable: indexes and views |
| 346 | + checked, as now; pointers in safe code made only by `NEW` and by the |
| 347 | + library, never by arithmetic or conversion. |
| 348 | +- **Temporal:** no read or write of memory that has been freed or |
| 349 | + reused: slices and pointers lent by a frame or a container can't |
| 350 | + outlive it (B, C); the heap is never freed under a pointer safe code |
| 351 | + holds (D). |
| 352 | +- **Type:** no value read as another type: views of pointers and |
| 353 | + conversions to pointers fenced; variants only through `match`; enums |
| 354 | + and `BOOL` only from their values. |
| 355 | +- **Initialization:** as now, every variable starts at zero. |
| 356 | +- **Races:** within the bounds above (part E). |
| 357 | + |
| 358 | +What it doesn't cover, on purpose: |
| 359 | + |
| 360 | +- **Leaks.** A safe program may keep memory it no longer needs, as a |
| 361 | + garbage-collected one may. |
| 362 | +- **Running out of memory or stack.** These stop the program, as now. |
| 363 | +- **Logic.** A stale handle into a `Pool` stops the program; it doesn't |
| 364 | + fix the bug. A slice of a buffer that was cleared shows the buffer's |
| 365 | + new contents, safely. |
| 366 | +- **Deadlock**, and a race on a whole record, variant or container. |
| 367 | + The second is undefined, as in Go, and part E says why. |
| 368 | +- **The unsafe modules themselves.** They are trusted, as `unsafe` |
| 369 | + code is in Rust and `UNSAFE MODULE`s are in Modula-3. |
| 370 | + |
| 371 | +The guarantee is stated once and is the same on every target. |
| 372 | +Appendix A keeps only how it is carried out: whether the machine or |
| 373 | +the code catches a fault, and how a slice is read in one access. |
| 374 | + |
| 375 | +--- |
| 376 | + |
| 377 | +## 4. The design, in brief |
| 378 | + |
| 379 | +| Part | What it does | Checked | Cost at run time | |
| 380 | +|---|---|---|---| |
| 381 | +| A. The fence | `unsafe;` modules alone may use `ADR`, pointer arithmetic and indexing, casts, views of pointers, `check off`, `extern`, `link`, code procedures, `SYSCALL`, `PTR`, or call an `unsafe proc` | compiling | none | |
| 382 | +| B. Lending | every slice or pointer is *lasting* or *lent* by a variable of the procedure; a lent one can't be stored where it outlives its lender, nor returned unless the heading says `ret`; `keep` parameters take only lasting ones | compiling, one pass | none | |
| 383 | +| C. Owners | a record with a `LENDS` field is an *owner*; what it lends is counted while a local holds it; an owner doesn't free a block while its count is above zero, and `done` with the count above zero stops; owners aren't copied | compiling, and a count at run time | an add and a subtract per lend held | |
| 384 | +| D. The heap | `free` is unsafe; `NEW` gives memory that lasts; a `Pool(T)` holds what must be freed, by checked handles; containers own and free their memory | compiling, and checks in `Pool` | none, or a compare per `Pool` access | |
| 385 | +| E. Threads | slices read and written in one access; containers and variants shared only under a lock, or the guarantee doesn't hold; `Task(T)` spawns safely; atomics take variables | partly | none on x86-64 with AVX | |
| 386 | +| F. Small mends | an array a call returns lives to the end of its procedure; writing a string's bytes stops or changes them | compiling | a larger frame | |
| 387 | +| G. Debugging | `Heap` in a mode that poisons and holds back freed blocks | at run time, when chosen | when chosen | |
| 388 | + |
| 389 | +A program that is safe today, which is to say every program that |
| 390 | +keeps to slices, records and the library, mostly stays as it is. Section 15 counts |
| 391 | +what breaks. |
| 392 | + |
| 393 | +--- |
| 394 | + |
| 395 | +## 5. Part A: the fence, `unsafe;` |
| 396 | + |
| 397 | +### 5.1 The rule |
| 398 | + |
| 399 | +A module that says `unsafe;`, after its imports, links and `check` |
| 400 | +line, may do everything raz allows today. A module that doesn't is |
| 401 | +*safe*, and it is an error for it to do any of the following: |
| 402 | + |
| 403 | +| Operation | Why it's fenced | |
| 404 | +|---|---| |
| 405 | +| `ADR(x)` | a pointer to anything, a local included, that outlives nothing | |
| 406 | +| `p + i`, `p - i`, `p[i]`, `p[lo..hi]` on a pointer | no length to check against | |
| 407 | +| a conversion to a pointer or procedure type, from an integer or another pointer or procedure type | makes a pointer to anything, of any type | |
| 408 | +| a conversion from a pointer or procedure to an integer | not unsafe in itself, but needed only by unsafe code; fenced so `grep unsafe` finds address games | |
| 409 | +| `PTR(s)` | the first word of a slice, unchecked | |
| 410 | +| a view `v.(T)` whose `T` holds a pointer, procedure or slice | makes one from bytes | |
| 411 | +| writing through a view of a variable that holds a pointer, procedure, slice, variant, enumeration or `BOOL` | changes those bytes behind their type | |
| 412 | +| `check off;` | indexes unchecked | |
| 413 | +| `extern`, `link` | C can do anything | |
| 414 | +| a code procedure, `SYSCALL` | the machine can do anything | |
| 415 | +| `ARGV()` | a `^^U8` from C; `Files.arg` gives a slice | |
| 416 | +| a call of an `unsafe proc`, or of a value of an `unsafe proc` type | the procedure says it can break the promise | |
| 417 | + |
| 418 | +What stays safe, though it involves pointers: `p^`, `p^.f`, `p^[i]` (an |
| 419 | +array through a pointer is indexed and checked), `nil`, comparing |
| 420 | +pointers, `p - q` (an integer), `NEW`, and passing and storing a |
| 421 | +pointer as any value. A pointer in safe code is only ever `nil`, from |
| 422 | +`NEW`, or handed out by the library. Part B says how long each one |
| 423 | +lives. |
| 424 | + |
| 425 | +The message names the mending: |
| 426 | + |
| 427 | +``` |
| 428 | +Window.raz:41:13: error: ADR is for unsafe modules |
| 429 | + 41 | XNextEvent(dpy, ADR(ev)); |
| 430 | + | ^^^^^^^ |
| 431 | + help: say "unsafe;" after the module's imports, or pass ev as a var |
| 432 | +``` |
| 433 | + |
| 434 | +### 5.2 Unsafe procedures |
| 435 | + |
| 436 | +Some of the library's procedures can break the promise whatever safe |
| 437 | +code does: `Mem.free`, `Heap`'s `free`, `Str.free`, `Sys.mmap`, |
| 438 | +`Sys.munmap`, `Thread.spawn` with its `^U8`. They are declared |
| 439 | + |
| 440 | +``` |
| 441 | +unsafe proc free*(a: ^Allocator; p: ^U8); |
| 442 | +``` |
| 443 | + |
| 444 | +and only an unsafe module may call one. A procedure type may say |
| 445 | +`unsafe proc(...)`; a value of that type may be called only from an |
| 446 | +unsafe module, and a safe procedure may stand where an unsafe type is |
| 447 | +wanted, not the other way. `Mem.Allocator`'s two fields are of unsafe |
| 448 | +types: safe code may pass an allocator to the library but can't call |
| 449 | +it. |
| 450 | + |
| 451 | +`unsafe`, like `static` in `link static;`, is a word only where it |
| 452 | +stands: before `proc`, and as the module's line. Elsewhere it is a |
| 453 | +name. |
| 454 | + |
| 455 | +### 5.3 The trust |
| 456 | + |
| 457 | +A safe module may import an unsafe one. What the unsafe module |
| 458 | +exports, other than its `unsafe proc`s, it promises safe to use: for |
| 459 | +any arguments a safe module can make, its procedures keep the |
| 460 | +guarantee. This is Modula-3's rule for an `UNSAFE MODULE` that |
| 461 | +implements a safe `INTERFACE`, and Rust's for a safe function built |
| 462 | +on `unsafe` blocks. What the promise demands of an unsafe module, in |
| 463 | +the report (section 16): |
| 464 | + |
| 465 | +1. What it returns as lasting (part B) lasts: its memory is never |
| 466 | + freed or reused while the program runs. |
| 467 | +2. What it returns through `ret` lives no longer than the argument it |
| 468 | + says. If the argument is an owner, the module doesn't free memory |
| 469 | + it lent while the owner's `LENDS` count is above zero (part C). |
| 470 | +3. What it keeps (`keep` parameters) it may hold for as long as it |
| 471 | + likes; what it doesn't mark `keep`, it doesn't hold past the call. |
| 472 | +4. Its exported types hide whatever a safe module could misuse: a |
| 473 | + container's pointer fields aren't exported. |
| 474 | +5. Its procedures given to other threads, or shared by them, are safe |
| 475 | + to call from several threads at once, or say otherwise. |
| 476 | + |
| 477 | +So `grep -l '^unsafe;'` lists every module whose bugs could corrupt |
| 478 | +memory, and the library's are among them, as they are today. |
| 479 | + |
| 480 | +### 5.4 Which modules would say it |
| 481 | + |
| 482 | +From the survey, as the code stands: |
| 483 | + |
| 484 | +- **The library:** `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, |
| 485 | + `Thread`, `Lock`, `C`, `CAbi`, and the containers `Buf`, `Vec`, `Map`, |
| 486 | + `List`, which hold raw blocks and grow them. `Str`, `Fmt`, `Opt` and |
| 487 | + `Files` can drop their two to five fenced operations and be safe. |
| 488 | + `Math`, `Out`, `Sort` and `Width` are safe already. |
| 489 | +- **`src/`:** all eleven modules today. Mended as section 2.2's |
| 490 | + table says, with the six buffer modules' grown arrays made `Vec`s or |
| 491 | + slices, `src/` keeps one unsafe module: `Scan`, for its allocator |
| 492 | + (`grab`) and, if it keeps it, the pointer through its source buffer. |
| 493 | + `Elf` writes the executable through `Sys.write` and needs none. |
| 494 | +- **`examples/`:** `Args` (it reads `ARGV()`, which `Files.arg` does |
| 495 | + for it), `Cpu` (a code procedure), `Pthreads`, `Printf`, `Window` |
| 496 | + (C), `Volatile` (a device's address), `Sh` and `Workers` (`ADR` at |
| 497 | + calls: mended by `var`). Five stay unsafe (`Cpu`, `Pthreads`, |
| 498 | + `Printf`, `Window`, `Volatile`), as an example of each kind of |
| 499 | + unsafety should be. |
| 500 | +- **Elsewhere:** rsqlite's `Sqlite` (C); rlX11's three casts look like |
| 501 | + work for views; rnet needs it only to keep `Http.Message` as it is |
| 502 | + (section 14). |
| 503 | + |
| 504 | +--- |
| 505 | + |
| 506 | +## 6. Part B: lending, `ret` and `keep` |
| 507 | + |
| 508 | +Part B is PROPOSALS' part 3 (`ret`, `keep`) with two changes. Pointers |
| 509 | +are followed, not only slices, and a third kind of lender, the owner, |
| 510 | +comes from part C. What is said there of "frame-bound", "outliving the |
| 511 | +call" and the checks stands. This section gives the rules in the |
| 512 | +terms the guarantee needs. |
| 513 | + |
| 514 | +### 6.1 Lasting and lent |
| 515 | + |
| 516 | +Every value that holds a slice or a pointer (a *reference*) is, for |
| 517 | +the compiler, either: |
| 518 | + |
| 519 | +- **lasting:** it points at memory that lives to the end of the |
| 520 | + program: `nil`, `[]`, a string constant, a module variable or a part |
| 521 | + of one, memory from `NEW` on the heap (part D), and what the library |
| 522 | + returns as lasting (a result with no `ret` parameter); |
| 523 | +- **lent** by one or more *lenders* of the procedure it is in: |
| 524 | + - **the frame**: a slice of a local array, of a value parameter's |
| 525 | + array, or of an array literal; an array a call returned (part F); |
| 526 | + - **a parameter `p`**: a slice parameter's value, what a `var` or |
| 527 | + `const` parameter's arrays hold or its references point at; and |
| 528 | + the parameter's own variable, for `var` and `const`; |
| 529 | + - **an owner `o`** (part C): what `o` lent through a `ret`. |
| 530 | + |
| 531 | +A value made from others is lent by every lender of its parts: a slice, |
| 532 | +a field, an element of `x`; a record, variant or array literal of |
| 533 | +parts; a call's result, from its arguments for `ret` parameters. A |
| 534 | +local variable holding references is lent by everything assigned to |
| 535 | +it anywhere in its procedure. That is PROPOSALS' rule, and the reason |
| 536 | +some checks wait for the procedure's `end`. |
| 537 | + |
| 538 | +### 6.2 What may be done with a lent reference |
| 539 | + |
| 540 | +A lent reference may be: |
| 541 | + |
| 542 | +- read, indexed, sliced, compared, and passed to any parameter not |
| 543 | + marked `keep`; |
| 544 | +- held in a local variable, or in a field or element of one (owner-lent |
| 545 | + values only in a local of slice or pointer type: see 7.3); |
| 546 | +- returned, if each of its lenders is a parameter marked `ret`. |
| 547 | + |
| 548 | +It may not be: |
| 549 | + |
| 550 | +- stored in a module variable, through a pointer (`p^.f := s`), or into |
| 551 | + a `var` parameter or part of one; |
| 552 | +- given to a `keep` parameter; |
| 553 | +- returned while lent by the frame, an owner, or a parameter not |
| 554 | + marked `ret`; |
| 555 | +- given to `Task.spawn` (part E). |
| 556 | + |
| 557 | +The rules are PROPOSALS' checks 1 to 3, with "frame-bound" read as |
| 558 | +"lent". Every check needs only the procedure in hand and the headings |
| 559 | +of what it calls, so a one-pass compiler can make it: the checks on a |
| 560 | +local wait for the procedure's `end`, as PROPOSALS describes. |
| 561 | + |
| 562 | +### 6.3 Marks |
| 563 | + |
| 564 | +``` |
| 565 | +proc trim*(ret s: []U8): []U8; (* the result may point where s does *) |
| 566 | +proc bytes*(ret const b: Buf): []U8; (* the result is lent by b, an owner *) |
| 567 | +proc put*(var m: Map; keep k: K; keep v: V): BOOL; (* k and v must last *) |
| 568 | +``` |
| 569 | + |
| 570 | +`ret` and `keep` stand before `var` or `const`, and are words only |
| 571 | +there. A mark that lends nothing (`keep n: INT`) is allowed, so a |
| 572 | +generic module can mark `keep v: T` for every `T`. PROPOSALS covers |
| 573 | +procedure values, generics, `extern` (no marks; unsafe anyway) and |
| 574 | +code procedures (trusted; unsafe anyway). |
| 575 | + |
| 576 | +Marks at the call (PROPOSALS' part 1) are not part of this proposal: |
| 577 | +the checks hold whether or not the call repeats them. |
| 578 | + |
| 579 | +### 6.4 Examples |
| 580 | + |
| 581 | +``` |
| 582 | +proc greet: []U8; |
| 583 | +var line: [80]U8; n: INT; |
| 584 | +begin |
| 585 | + n := Sys.read(Sys.stdin, line); |
| 586 | + Out.str(Str.trim(line[0..n])); (* fine: lent by the frame, used here *) |
| 587 | + return Str.trim(line[0..n]); (* error: lent by the frame *) |
| 588 | +end; |
| 589 | + |
| 590 | +proc first(ret s: []U8): []U8; |
| 591 | +begin |
| 592 | + return s[0..1]; (* fine: s is ret *) |
| 593 | +end; |
| 594 | + |
| 595 | +proc remember(n: INT); |
| 596 | +var buf: [8]U8; k: []U8; ok: BOOL; |
| 597 | +begin |
| 598 | + buf := "name-000"; buf[7] := U8('0' + n); |
| 599 | + _ := Names.put(table, buf[0..8], n); (* error: put keeps k, and this is lent by the frame *) |
| 600 | + k, ok := Str.copy(Heap.heap, buf[0..8]); (* lasting: a copy on the heap *) |
| 601 | + if ok then _ := Names.put(table, k, n); end; (* fine *) |
| 602 | +end; |
| 603 | +``` |
| 604 | + |
| 605 | +The messages: |
| 606 | + |
| 607 | +``` |
| 608 | +Kept.raz:10:30: error: Names.put keeps its key, and buf[0..8] is lent by this call's frame |
| 609 | + 10 | _ := Names.put(table, buf[0..8], n); |
| 610 | + | ^^^^^^^^^ |
| 611 | + help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) |
| 612 | +``` |
| 613 | + |
| 614 | +``` |
| 615 | +Escape.raz:14:12: error: head(h) is lent by h, a local of short, and can't be returned |
| 616 | + 14 | return head(h); |
| 617 | + | ^^^^^^^ |
| 618 | + help: head's result points into what it is given (ret h); return a copy, or take h as a var parameter of short |
| 619 | +``` |
| 620 | + |
| 621 | +### 6.5 Pointers |
| 622 | + |
| 623 | +PROPOSALS' marks follow slices only and leave pointers to the promise |
| 624 | +of section 10. Here pointers are references too. In a safe module the only |
| 625 | +pointers are lasting (from `NEW` on the heap, or from the library) or |
| 626 | +lent by an owner (`Vec.add`, `Pool.at`). `ADR` is fenced, so a safe |
| 627 | +module can't make a pointer to the frame. A pointer lent by an |
| 628 | +owner follows the same rules as a slice. |
| 629 | + |
| 630 | +### 6.6 What it closes |
| 631 | + |
| 632 | +- A slice of the frame returned or stored by any route (today's 7.3 |
| 633 | + catches one route). |
| 634 | +- A slice of a parameter's array stored past the call, or returned |
| 635 | + unmarked. |
| 636 | +- A map, list or vector keeping a slice that doesn't last. |
| 637 | +- `Opt.init` keeping a table built on the frame (it becomes `keep |
| 638 | + table`, and `examples/Sh.raz` passes a constant, as PROPOSALS shows). |
| 639 | + |
| 640 | +--- |
| 641 | + |
| 642 | +## 7. Part C: owners that count what they lend |
| 643 | + |
| 644 | +### 7.1 The problem part B can't solve |
| 645 | + |
| 646 | +`Buf.bytes(b)` returns a slice of heap memory, so by PROPOSALS' rule it |
| 647 | +points "nowhere that ends", and part B would call it lasting. It |
| 648 | +isn't: the next `Buf.add` may free that memory. The slice is lent by |
| 649 | +`b`, and how long it stays good depends on what happens to `b`, at run |
| 650 | +time, often through a pointer: `Buf.bytes(x^.path)`. |
| 651 | + |
| 652 | +There are two ways to check that when compiling. One is Rust's: no |
| 653 | +change to `b` while any slice of it is live, found by liveness and |
| 654 | +the exclusivity of `&mut`. The other is flow analysis in one pass: |
| 655 | +mark a slice stale when its lender is passed as `var`, and refuse to |
| 656 | +read it after that. Both fail raz's limits. Rust's needs lifetimes in |
| 657 | +types and borrow regions. The one-pass flow analysis can't see a |
| 658 | +loop's second iteration before it compiles the first: |
| 659 | + |
| 660 | +``` |
| 661 | +s := Buf.bytes(b); |
| 662 | +while more do |
| 663 | + Out.str(s); (* compiled before the add below; but the second time round s is stale *) |
| 664 | + Buf.add(b, c); |
| 665 | +end; |
| 666 | +``` |
| 667 | + |
| 668 | +and through a pointer every call may change the lender, so every call |
| 669 | +would make the slice stale, which is false alarms everywhere. |
| 670 | + |
| 671 | +So part C checks at run time, as raz checks an index. The cost is an |
| 672 | +add when a lent slice is taken into a variable and a subtract when the |
| 673 | +variable lets go of it. |
| 674 | + |
| 675 | +### 7.2 Owners |
| 676 | + |
| 677 | +A record type with a field of the new built-in type `LENDS` is an |
| 678 | +*owner*: |
| 679 | + |
| 680 | +``` |
| 681 | +type |
| 682 | + Buf* = record |
| 683 | + lends: LENDS; (* how many slices of data are held *) |
| 684 | + a: ^Mem.Allocator; |
| 685 | + data: ^U8; |
| 686 | + len*, cap: INT; |
| 687 | + end; |
| 688 | +``` |
| 689 | + |
| 690 | +`LENDS` is an `INT` that only the compiler changes: the owner's own |
| 691 | +module may read it, and nothing may assign it. An owner is lent from |
| 692 | +only through a `ret` parameter of its type, `var` or `const`: |
| 693 | + |
| 694 | +``` |
| 695 | +proc bytes*(ret const b: Buf): []U8; |
| 696 | +proc all*(ret const v: Vec): []T; |
| 697 | +proc add*(ret var v: Vec): ^T; |
| 698 | +proc spare*(ret var b: Buf; n: INT): []U8; |
| 699 | +``` |
| 700 | + |
| 701 | +A record that holds an owner, `Http.Message` with its two `Buf`s, is |
| 702 | +not an owner itself. What its `Buf`s lend is counted on each `Buf`. |
| 703 | + |
| 704 | +### 7.3 Counting |
| 705 | + |
| 706 | +Where a call returns a reference lent by an owner `o`: |
| 707 | + |
| 708 | +- **Used in its statement** (`Out.str(Buf.bytes(b))`, `Buf.str(c, |
| 709 | + Buf.bytes(b))`): `o.lends` is raised by one as the call returns and |
| 710 | + lowered at the end of the statement. |
| 711 | +- **Assigned to a local** of slice or pointer type, `s := Buf.bytes(b)`: |
| 712 | + the local gets a hidden word, its *hold*, which records the address of |
| 713 | + `o.lends`. Assigning the local again lowers the old count and raises |
| 714 | + the new; when the procedure returns, by any path, each hold still set |
| 715 | + lowers its count, as a `defer` would. `s := []` lets go. |
| 716 | +- **Anywhere else**: stored in a record, an array, a module variable, |
| 717 | + through a pointer, or returned. This is an error by part B, since |
| 718 | + the reference is lent by an owner. A local record holding one is |
| 719 | + also an error, so that each hold covers one reference: |
| 720 | + |
| 721 | +``` |
| 722 | +Fmt.raz:140:5: error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable |
| 723 | +``` |
| 724 | + |
| 725 | +A reference passed to another procedure needs no count of its own: |
| 726 | +the caller holds it, by a statement's count or a local's hold, for the |
| 727 | +whole call. A `ret` result lent by a lent value (`t := Str.trim(s)`, |
| 728 | +with `s` lent by `b`) is lent by `b` too, and its local gets its own |
| 729 | +hold. |
| 730 | + |
| 731 | +The owner's address is fixed while it is lent. An owner is either a |
| 732 | +local, a parameter, or a variable reached through a lasting pointer, |
| 733 | +and part B keeps the lent value from outliving a local or parameter |
| 734 | +owner. So the hold's address stays good until it is let go. |
| 735 | + |
| 736 | +### 7.4 What an owner does with its count |
| 737 | + |
| 738 | +The owner's module, which is unsafe and trusted, reads `lends` |
| 739 | +before it frees memory it has lent: |
| 740 | + |
| 741 | +- **Growing:** if `lends` is 0, free the old block, as now. If not, |
| 742 | + keep it on a list of *retired* blocks, and free those at the next |
| 743 | + growth, `reset` or `done` that finds `lends` 0. A slice held across |
| 744 | + the growth keeps pointing at the old block, which stays allocated: |
| 745 | + it reads what the buffer held when the slice was taken. This is Go's |
| 746 | + `append`: the old slice still sees the old array. |
| 747 | +- **`done`**, which gives everything back: if `lends` is above 0, the |
| 748 | + program stops: |
| 749 | + |
| 750 | + ``` |
| 751 | + Buf.done while 1 slice it lent is still held |
| 752 | + ``` |
| 753 | + |
| 754 | + and the calls under way are shown, as a failed check shows them. |
| 755 | + `done` can't wait, and can't leave the memory to the slice without |
| 756 | + leaking it for good. |
| 757 | +- **`reset`** keeps the block, so it is always safe: a slice held |
| 758 | + reads the new bytes as they are written over the old. |
| 759 | + |
| 760 | +With this, the self-append of 1.2 is right: `Buf.str(b, Buf.bytes(b))` |
| 761 | +holds a count across the call, the growth retires the old block, and |
| 762 | +`COPY` reads the old block, still allocated. The `Vec` example reads |
| 763 | +`1 2` because the memory is still there. The stale `p^ := -1` writes |
| 764 | +into a retired block: lost, but harmless. Section 11's debugging heap |
| 765 | +can say so. |
| 766 | + |
| 767 | +### 7.5 What it costs |
| 768 | + |
| 769 | +- **Run time:** two adds per lend held: on x86-64, `inc qword [r]` and |
| 770 | + `dec qword [r]`, about two cycles each. In a program that uses |
| 771 | + `Thread` they are `lock xadd`, about 20 cycles each (part E). Lends |
| 772 | + are rare next to element accesses: `Fmt.format` lends once per call, |
| 773 | + and a loop over `Buf.bytes(b)` lends once. |
| 774 | +- **Memory:** a word per owner, a word per local that holds a lend, |
| 775 | + and at most the retired blocks, which add up to less than the |
| 776 | + current block (each was half the next). |
| 777 | +- **Compiler:** the hold slots, the raise and lower code, and the |
| 778 | + epilogue's let-go. The epilogue reuses the machinery `defer` already |
| 779 | + has. |
| 780 | + |
| 781 | +### 7.6 Owners aren't copied |
| 782 | + |
| 783 | +Copying a `Buf` today makes two records that both own one block. |
| 784 | +Freeing it twice, or growing one while the other reads, breaks |
| 785 | +memory. rnet's `Http.reset` does exactly this, safely by luck: |
| 786 | +`head := m^.head; ...; m^ := {..., head: head}`. In a safe module, a |
| 787 | +value of an owner type, or of a type that holds one, may not be: |
| 788 | + |
| 789 | +- assigned from another variable, returned, passed as a value |
| 790 | + parameter, or put in a literal. A literal may still leave it out, so |
| 791 | + that it is zero (`{}`), the empty owner; |
| 792 | +- compared, or viewed. |
| 793 | + |
| 794 | +It is passed as `var` or `const`, and moved by the library: `Buf.swap(var |
| 795 | +a, b)`, `Buf.take(var from, to)`. The message: |
| 796 | + |
| 797 | +``` |
| 798 | +Http.raz:153:5: error: a Buf.Buf owns memory, and can't be copied |
| 799 | + help: Buf.take(m^.data, data) moves it, leaving m^.data empty |
| 800 | +``` |
| 801 | + |
| 802 | +### 7.7 Who is an owner |
| 803 | + |
| 804 | +`Buf`, `Vec`, `Map` (it lends nothing, but owns its table; `LENDS` |
| 805 | +stops a copy), `List`, `Pool`, `Arena` and the owned-string map of |
| 806 | +part D. A program's own record may be an owner too, if an unsafe |
| 807 | +module of the program frees what it lends. |
| 808 | + |
| 809 | +--- |
| 810 | + |
| 811 | +## 8. Part D: the heap without `free` |
| 812 | + |
| 813 | +### 8.1 The rule |
| 814 | + |
| 815 | +In a safe module: |
| 816 | + |
| 817 | +- `NEW(p, a)` with `a` lasting (`Heap.heap`) gives a lasting `p`. |
| 818 | + `Heap.heap` never frees it under safe code, because only unsafe code |
| 819 | + can call `free`. |
| 820 | +- `NEW(p, a)` with `a` lent by an owner (an arena, part C) gives a |
| 821 | + `p` lent by that owner, counted like a slice. |
| 822 | +- `Mem.free`, `Heap`'s `free`, `Str.free` and `Mem.unmap` are `unsafe |
| 823 | + proc`s. |
| 824 | + |
| 825 | +So a safe program frees memory in one of three ways: |
| 826 | + |
| 827 | +1. **Through a container** that owns it: `Buf.done`, `Vec.done`, |
| 828 | + `Map.done`, `List.clear`, `Pool.free`. Most programs do this already: |
| 829 | + outside the library, the survey's `done` calls outnumber its hand |
| 830 | + frees 54 to 26. |
| 831 | +2. **Through a `Pool(T)`**, for records that come and go one by one |
| 832 | + (8.2). |
| 833 | +3. **By ending the program.** A compiler, a tool or a short-lived |
| 834 | + server process frees nothing by hand, and `src/` frees only its |
| 835 | + grown arrays, which become `Vec`s. |
| 836 | + |
| 837 | +The 1,015 dereferences in `src/` stay as they are, with no check and |
| 838 | +no cost: every pointer behind them is lasting. |
| 839 | + |
| 840 | +### 8.2 `Pool(T)`: handles with a generation |
| 841 | + |
| 842 | +``` |
| 843 | +module Pool(T); |
| 844 | + |
| 845 | +type |
| 846 | + Handle* = record i, gen: INT; end; (* zero: no record *) |
| 847 | + Pool* = record lends: LENDS; ... end; |
| 848 | + |
| 849 | +proc init*(var p: Pool; a: ^Mem.Allocator); |
| 850 | +proc add*(var p: Pool; keep x: T): Handle; (* a new record, x copied in *) |
| 851 | +proc get*(const p: Pool; h: Handle): T; (* a copy; stops if h is stale *) |
| 852 | +proc set*(var p: Pool; h: Handle; keep x: T); (* stops if h is stale *) |
| 853 | +proc at*(ret var p: Pool; h: Handle): ^T; (* in place, lent by p, counted *) |
| 854 | +proc valid*(const p: Pool; h: Handle): BOOL; |
| 855 | +proc free*(var p: Pool; h: Handle); (* the record gone; h, and every copy, stale *) |
| 856 | +proc done*(var p: Pool); |
| 857 | +``` |
| 858 | + |
| 859 | +Each slot holds a `T` and a generation. `free` raises the slot's |
| 860 | +generation and puts the slot on a free list. `get`, `set` and `at` check |
| 861 | +the handle's generation against the slot's, and the index against the |
| 862 | +pool's length, and stop the program if they differ: |
| 863 | + |
| 864 | +``` |
| 865 | +Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) |
| 866 | +``` |
| 867 | + |
| 868 | +A slot is used only for a `T`, so even a pointer from `at` kept past |
| 869 | +`free` points at a `T`: a wrong record, perhaps, but never memory |
| 870 | +of another type. `at`'s count also keeps the pool from moving its slots |
| 871 | +while the pointer is held (7.4). |
| 872 | + |
| 873 | +This is the generational arena of Rust's `slotmap` and |
| 874 | +`generational-arena`, and the handle pattern Zig and game engines use; |
| 875 | +Vale builds the same check into every reference. Measured cost |
| 876 | +(section 13): a list chased through handles takes 1.5 times as long as |
| 877 | +one chased through raw pointers when it is too big for the caches, and |
| 878 | +2 times when it fits in L1. Part of the first is that each slot is 32 |
| 879 | +bytes, not 16. |
| 880 | + |
| 881 | +### 8.3 Owned strings |
| 882 | + |
| 883 | +`Str.copy` gives a lasting copy, which a safe program can't free. For a |
| 884 | +long-running program that makes and drops strings (an editor's buffer |
| 885 | +names, a server's paths), the library adds: |
| 886 | + |
| 887 | +- `Buf` as the string a program owns: `Buf.str(name, s)`, freed by |
| 888 | + `Buf.done`; |
| 889 | +- `Names(V)`, a map from strings to `V` that copies each key in on |
| 890 | + `put` and frees it on `remove` and `done`: `Map([]U8, V, ...)` with |
| 891 | + its keys owned, for those who would otherwise `Str.copy` and leak. |
| 892 | + |
| 893 | +### 8.4 Arenas |
| 894 | + |
| 895 | +An arena hands out memory and frees it all at once, so what it gives |
| 896 | +is lent by the arena: |
| 897 | + |
| 898 | +``` |
| 899 | +var ar: Arena.Arena; t: ^Tree; |
| 900 | +... |
| 901 | +NEW(t, Arena.allocator(ar)); (* lent by ar *) |
| 902 | +... |
| 903 | +Arena.reset(ar); (* stops the program if t is still held *) |
| 904 | +``` |
| 905 | + |
| 906 | +`Arena.allocator(ret var ar): ^Mem.Allocator` gives the allocator, |
| 907 | +lent by `ar`; `NEW` from it gives a `t` lent by `ar`, counted. Lent |
| 908 | +values can't be stored in records (part B), so an arena in safe code |
| 909 | +holds no linked structure: the pointer to a tree's root may live in |
| 910 | +a local, but the tree's own links can't. A program that builds |
| 911 | +linked structures in an arena does it in an unsafe module, or with |
| 912 | +indexes into a `Vec`. Section 14 weighs this. |
| 913 | + |
| 914 | +--- |
| 915 | + |
| 916 | +## 9. Part E: threads |
| 917 | + |
| 918 | +### 9.1 What races can break |
| 919 | + |
| 920 | +7.6 says a variable that two threads touch without ordering "holds a |
| 921 | +value it had or was given, or a mixture of their bytes" and that |
| 922 | +"nothing else of the program becomes undefined". The second half is |
| 923 | +wrong today: |
| 924 | + |
| 925 | +- a **slice** torn between two writes, one's address with the other's |
| 926 | + length, is checked against the wrong length and reaches any memory; |
| 927 | +- a **variant** torn between two cases reads one case's bytes as the |
| 928 | + other's fields: an integer as a pointer; |
| 929 | +- a **container** written by two threads at once (`Buf.add` in each) |
| 930 | + races on its length and its block: one thread writes past the end of |
| 931 | + the block the other just freed. |
| 932 | + |
| 933 | +Go has the same hole: its memory model says that a race on a |
| 934 | +multi-word value (an interface, a slice, a string) "can lead to |
| 935 | +arbitrary memory corruption". Rust closes it with `Send` and `Sync`, |
| 936 | +traits that the type system checks. Java closes it by tearing only |
| 937 | +`long` and `double`, never a reference. |
| 938 | + |
| 939 | +### 9.2 The proposal |
| 940 | + |
| 941 | +1. **A slice is one access.** On every target, a slice is read and |
| 942 | + written in one access that can't tear, as a word is. On x86-64 a |
| 943 | + slice is aligned to 16 bytes and moved with `movdqa`, which Intel |
| 944 | + and AMD guarantee single-copy atomic on processors with AVX. On |
| 945 | + x86-64 without AVX, the implementation uses `lock cmpxchg16b`, or |
| 946 | + refuses the target, as appendix A says. ARMv8.4 has 16-byte |
| 947 | + atomic `LDP`/`STP` (FEAT_LSE2). A program that hands slices from |
| 948 | + thread to thread, publishing a buffer for others to read, is then |
| 949 | + safe with no lock. |
| 950 | +2. **The guarantee holds for races on basic, pointer, procedure and |
| 951 | + slice variables, and no others.** A race on a variant, or on a |
| 952 | + whole record or array copied at once, or calls of one container's |
| 953 | + procedures from two threads at once without a lock, is outside |
| 954 | + it: undefined, as in Go. Section 3 says so, and 7.6 is rewritten |
| 955 | + to say so. |
| 956 | +3. **A safe way to start a thread.** `Thread.spawn(p, arg: ^U8)` becomes |
| 957 | + an `unsafe proc`. A generic `Task(T)` takes its place for safe |
| 958 | + modules: |
| 959 | + |
| 960 | + ``` |
| 961 | + module Task(T); |
| 962 | + proc spawn*(p: proc(var x: T); keep x: T): (^Thread.Thread, ERROR); |
| 963 | + ``` |
| 964 | + |
| 965 | + `x` is copied into the new thread's stack before `spawn` returns. |
| 966 | + Its references must be lasting (`keep`), so a thread never holds |
| 967 | + a slice of its spawner's frame. |
| 968 | +4. **Atomics take a variable.** `CAS(x, old, new)`, `XCHG(x, v)` and |
| 969 | + `XADD(x, k)` take a variable, as `INC` does; through a pointer, `XADD(p^, |
| 970 | + 1)`. A safe module can then use them, with no `ADR`. |
| 971 | +5. **Counts are atomic where there are threads.** Part C's raise and |
| 972 | + lower are `lock xadd` in a program that imports `Thread`, so that two |
| 973 | + threads lending from one locked `Buf` keep its count right. A |
| 974 | + program without `Thread` gets the plain `inc` and `dec`. |
| 975 | +6. **`Lock.Guarded(T)`**, a value with its lock, for sharing a |
| 976 | + container: |
| 977 | + |
| 978 | + ``` |
| 979 | + g: Guarded(Names.Map); |
| 980 | + Guarded.with(g, addName); (* addName(var m: Names.Map) runs under the lock *) |
| 981 | + ``` |
| 982 | + |
| 983 | + It makes the safe pattern the easy one, as Rust's `Mutex<T>` does, |
| 984 | + though nothing stops a program from sharing a container without it. |
| 985 | + |
| 986 | +### 9.3 Why not Rust's way |
| 987 | + |
| 988 | +A static rule that a container can be reached from two threads only |
| 989 | +under a lock needs, at the least, marks on types for what may cross |
| 990 | +threads (`Send`) and be shared (`Sync`), and a way to see that module |
| 991 | +variables are shared. Module variables are reachable from every thread, |
| 992 | +and raz has no thread-local storage to put them in instead. It would |
| 993 | +add a second type system to the language for a feature two |
| 994 | +repositories out of eight use. Section 19 keeps it as a later step. |
| 995 | + |
| 996 | +--- |
| 997 | + |
| 998 | +## 10. Part F: the small mends |
| 999 | + |
| 1000 | +### 10.1 An array a call returns lives to the end of its procedure |
| 1001 | + |
| 1002 | +"Less that is undefined", piece 1. The temporary's slot in the frame is |
| 1003 | +reserved for the rest of the procedure, as a deferred statement's slots |
| 1004 | +already are, so `s := f('a')[0..4]` is lent by the frame, not by the |
| 1005 | +statement: defined until the procedure returns, and part B keeps it |
| 1006 | +from going further. In a loop the slot holds the latest call's array. |
| 1007 | +1.2's last program then prints `name-..a name-..b`, since each call has |
| 1008 | +a slot of its own. |
| 1009 | + |
| 1010 | +The same for a `const` parameter's temporary (section 8): its slot is |
| 1011 | +reserved to the end of the procedure. |
| 1012 | + |
| 1013 | +Cost: a frame bigger by each such call's array. That is not measured |
| 1014 | +here; in `src/`, arrays returned by calls are small (`Str.fromInt`'s |
| 1015 | +20 bytes, `Str.encode`'s 4), so the estimate is tens of bytes per |
| 1016 | +frame. |
| 1017 | + |
| 1018 | +### 10.2 A string's bytes |
| 1019 | + |
| 1020 | +"Less that is undefined", piece 2. Writing a string constant's bytes, |
| 1021 | +through a slice of it, either stops the program (a bad address, as now |
| 1022 | +on Linux, since constants are in read-only data) or changes the |
| 1023 | +constant for the rest of the run. Which one is the target's choice |
| 1024 | +(appendix A). Either is defined, and neither touches another |
| 1025 | +variable. A later `[]const U8` (PROPOSALS) would make it a compile-time |
| 1026 | +error. |
| 1027 | + |
| 1028 | +### 10.3 Views |
| 1029 | + |
| 1030 | +A view reading any variable's bytes as an integer type is safe: it |
| 1031 | +reveals an address, but it can't make one. Writing through a view of a |
| 1032 | +variable that holds a pointer, slice, procedure, variant, enumeration |
| 1033 | +or `BOOL` is fenced (5.1), since it would make one of those from |
| 1034 | +arbitrary bytes. Views of plain data, the survey's every use outside |
| 1035 | +`Rt`, stay safe. |
| 1036 | + |
| 1037 | +### 10.4 `match` on a lent variant |
| 1038 | + |
| 1039 | +A `match` on a variant whose case holds references gives names that |
| 1040 | +are lent as the variant is: a field of a local variant lent by the frame |
| 1041 | +is lent by the frame. Part B's rules follow. |
| 1042 | + |
| 1043 | +--- |
| 1044 | + |
| 1045 | +## 11. Part G: a debugging heap |
| 1046 | + |
| 1047 | +Unsafe modules are trusted, and trust must be tested. `Heap` gets a |
| 1048 | +second mode, chosen when the program starts (`RAZ_HEAP=debug` in the |
| 1049 | +environment, or `Heap.debug(true)` before the first allocation): |
| 1050 | + |
| 1051 | +- every freed block is filled with `0DEH` and kept off the free lists |
| 1052 | + for the next 1,024 frees (a quarantine), so a stale read sees junk |
| 1053 | + and a stale write is found when the block leaves the quarantine and |
| 1054 | + its bytes are checked; |
| 1055 | +- each block gets eight guard bytes after it, checked when it is freed; |
| 1056 | +- `Buf`, `Vec` and `Pool` fill a retired block with `0DEH` too, so a |
| 1057 | + slice held across a growth reads junk in the debugging heap and the |
| 1058 | + old bytes otherwise. |
| 1059 | + |
| 1060 | +A break is reported as a failed check is: where, and the calls under |
| 1061 | +way. `make check` runs the library's tests and `test/run` in both modes. |
| 1062 | +This is Zig's debug allocator, glibc's `MALLOC_PERTURB_`, and Chrome's |
| 1063 | +MiraclePtr quarantine, without their reach. It costs nothing unless |
| 1064 | +chosen. It is the one part that changes no rule and could come first. |
| 1065 | + |
| 1066 | +--- |
| 1067 | + |
| 1068 | +## 12. Raz beside other languages |
| 1069 | + |
| 1070 | +| Language | Spatial | Temporal | Forged pointers | Races | Fence | What it costs | |
| 1071 | +|---|---|---|---|---|---|---| |
| 1072 | +| C | none | none | anything | UB | none | nothing | |
| 1073 | +| C++, hardened | hardened `std` containers; `-fbounds-safety` for C (clang) | none | anything | UB | none | a little | |
| 1074 | +| Zig | checked in Debug and ReleaseSafe | the debug allocator finds use after free and double frees at run time; nothing in release | `@ptrCast`, `@intToPtr` anywhere | UB | none, but builtins are visible | a check per index | |
| 1075 | +| Odin, Hare, C3 | checked | none | anywhere | UB | none | a check per index | |
| 1076 | +| Go | checked | a garbage collector | only through `unsafe` | a race on a multi-word value corrupts memory | `import "unsafe"` | a GC, write barriers, a runtime | |
| 1077 | +| Java, C# | checked | a garbage collector | none | references never tear; `long` may in Java | C#: `unsafe` blocks | a GC, a runtime | |
| 1078 | +| Swift | checked | reference counting; exclusivity checked at compile and run time | only through `Unsafe*` types | Swift 6: `Sendable`, checked | `Unsafe` in names | refcounting traffic | |
| 1079 | +| Rust | checked | the borrow checker, at compile time | only in `unsafe` | `Send`/`Sync`, at compile time | `unsafe` blocks and functions | lifetimes, learning, compile time | |
| 1080 | +| Ada, SPARK | checked | accessibility levels: an access can't outlive its object's level; `Unchecked_Deallocation` named as unsafe; SPARK adds ownership | `Unchecked_Conversion` | protected objects | the word "unchecked" | a check per index; some dynamic accessibility checks | |
| 1081 | +| Modula-3 | checked | a garbage collector for traced references; `DISPOSE` only in unsafe modules | only in `UNSAFE MODULE` | not promised | `UNSAFE MODULE`, `UNSAFE INTERFACE` | a GC | |
| 1082 | +| Oberon | checked | a garbage collector | only through `SYSTEM` | n/a | `IMPORT SYSTEM` | a GC | |
| 1083 | +| Vale | checked | generational references: each object carries a generation, each reference the one it expects, checked at each dereference; regions skip the check | none | regions | `unsafe` | wider references, a check per dereference | |
| 1084 | +| Cyclone | fat pointers | regions, checked statically | none | n/a | none | annotations, wider pointers | |
| 1085 | +| Fil-C, CHERI | every pointer carries its bounds (compiler or hardware) | Fil-C: a GC; CHERI: revocation | none | Fil-C: atomic capabilities | none | Fil-C: a few times slower; CHERI: hardware | |
| 1086 | +| **raz, proposed** | checked | lending checked at compile time; owners count lends at run time; no `free` in safe code; `Pool` handles checked | only in `unsafe;` modules | slices and words atomic; containers and variants under a lock or UB | `unsafe;` modules, `unsafe proc` | an add and a subtract per lend held; a compare per `Pool` access | |
| 1087 | + |
| 1088 | +What raz takes from each: |
| 1089 | + |
| 1090 | +- **From Modula-3:** the fence by module, and the trust in an unsafe |
| 1091 | + module's safe interface. The unit of review is a file, as Wirth's |
| 1092 | + languages always had it. |
| 1093 | +- **From Ada:** a static rule that a reference can't outlive its |
| 1094 | + object's level, with no lifetime variables in types. Ada's |
| 1095 | + accessibility levels are part B's frame, parameters and lasting |
| 1096 | + memory, nearly exactly. Ada also names deallocation as unchecked. |
| 1097 | +- **From Rust:** `ret` is lifetime elision written out; `keep` is |
| 1098 | + `'static`. What raz doesn't take is lifetimes in records, which is |
| 1099 | + what lets Rust check `Http.Message` and what costs Rust its |
| 1100 | + learning curve. |
| 1101 | +- **From Swift:** checking exclusivity at run time where the compiler |
| 1102 | + can't, as part C counts lends. |
| 1103 | +- **From Go:** a slice held across a growth sees the old array; and an |
| 1104 | + honest statement about races. |
| 1105 | +- **From Vale, `slotmap` and Zig's handle idiom:** generations, |
| 1106 | + but in a container (`Pool`), not in every pointer, so that the 99% of |
| 1107 | + pointers that are never freed pay nothing. |
| 1108 | +- **From Zig:** the debugging allocator as the first line of defence |
| 1109 | + for unsafe code. |
| 1110 | + |
| 1111 | +Where raz ends up: about as safe as Go or Modula-3 for a program that |
| 1112 | +uses no threads, with no garbage collector and no run time beyond a |
| 1113 | +count per lend; less expressive than Rust (no record may borrow); and |
| 1114 | +far simpler to learn and to compile. |
| 1115 | + |
| 1116 | +--- |
| 1117 | + |
| 1118 | +## 13. Performance |
| 1119 | + |
| 1120 | +All measurements are on the session's machine, 4 cores of an x86-64 |
| 1121 | +virtual machine, using today's compiler. Wall-clock times are the |
| 1122 | +best of several runs; on this machine they vary by 10 to 20% between |
| 1123 | +runs, so where it matters instruction counts from `valgrind |
| 1124 | +--tool=callgrind` are given, which don't vary. |
| 1125 | + |
| 1126 | +### 13.1 The compiler's speed |
| 1127 | + |
| 1128 | +The largest cost of the proposal to `src/` itself would be checking the |
| 1129 | +scanner's buffer, if `Scan` stops being unsafe. To measure it, `Scan`'s |
| 1130 | +`buf: ^U8` was made a checked `[]U8` (with the sentinel inside its |
| 1131 | +length) and everything else left as it was. Five lines changed: |
| 1132 | + |
| 1133 | +| Compile | Pointer (today) | Checked slice | More | |
| 1134 | +|---|---|---|---| |
| 1135 | +| `src/Raz.raz`, the compiler itself | 240,851,288 instructions | 251,595,933 | **+4.5%** | |
| 1136 | +| the generated benchmark, 58,025 lines | 40,305,841 | 42,519,299 | +5.5% | |
| 1137 | + |
| 1138 | +`make bench`'s 348,025 lines compile in 625 to 660 ms here, about |
| 1139 | +530,000 to 557,000 lines a second; 5.5% more is about 500,000 to 528,000, inside the 400,000-line |
| 1140 | +floor and inside `make prev-bench`'s tenth. Most of the cost is the |
| 1141 | +scanner's inner loops, `while (c = ' ') ... c := buf[p]`, checking |
| 1142 | +each byte. Section 21 asks whether `Scan` stays unsafe instead, |
| 1143 | +leaving the compiler as fast as it is. |
| 1144 | + |
| 1145 | +The other changes to `src/` (grown arrays to `Vec`, `intern(s)`, views) |
| 1146 | +cost nothing measurable: `Vec`'s access through `all` is a slice index, |
| 1147 | +which is the same check the hand-grown arrays don't have, on paths |
| 1148 | +much cooler than the scanner's. |
| 1149 | + |
| 1150 | +The compiler's own checks (part B, C, the fence) are flags on items |
| 1151 | +and modules and run while each expression is compiled: no measurable |
| 1152 | +compile time. |
| 1153 | + |
| 1154 | +### 13.2 Kernels |
| 1155 | + |
| 1156 | +`MemBench.raz` and `GenBench.raz` (appendix 2): |
| 1157 | + |
| 1158 | +| Kernel | Run 1 | Run 2 | What it shows | |
| 1159 | +|---|---|---|---| |
| 1160 | +| chase a 1,000,000-node list (16-byte nodes), raw pointers | 8,312 ms | 7,515 ms | the baseline | |
| 1161 | +| the same through `Pool`-style handles (32-byte slots, index and generation checked) | 12,336 ms | 11,992 ms | **1.5–1.6×**: half of it the larger slot | |
| 1162 | +| chase a 1,000-node list (in L1), raw pointers | 857 ms | 810 ms | | |
| 1163 | +| the same through handles | 1,631 ms | 1,643 ms | **1.9–2.0×**: the checks themselves | |
| 1164 | +| chase 1,000,000 32-byte nodes, raw pointers | 14,001 ms | 13,725 ms | the larger node alone, against row 1: **+70–85%** | |
| 1165 | +| the same through fat (address, generation) pointers, generation in the node | 8,672 ms | 10,145 ms | the check is free here: in the node's own cache line | |
| 1166 | +| 1,000 32-byte nodes, raw | 870 ms | 917 ms | | |
| 1167 | +| 1,000 32-byte nodes, fat pointers | 830 ms | 1,047 ms | within noise to +15% | |
| 1168 | +| sum 16,000,000 bytes through `^U8`, 50 times | 305 ms | 342 ms | | |
| 1169 | +| the same through a checked `[]U8` | 271 ms | 434 ms | within noise: the check hides behind the loads | |
| 1170 | +| sum 4,000 bytes (in L1), 200,000 times, `^U8` | 261 ms | 265 ms | | |
| 1171 | +| the same, checked `[]U8` | 256 ms | 306 ms | 0–15% | |
| 1172 | + |
| 1173 | +What they say: |
| 1174 | + |
| 1175 | +- **Bounds checks are cheap.** On sequential access the check is |
| 1176 | + hidden by the loads it guards. This is why nobody uses `check off;`. |
| 1177 | +- **A generation check is cheap when it is in the object's cache line** |
| 1178 | + (the fat-pointer rows). **Wider references are not cheap:** doubling a |
| 1179 | + node from 16 to 32 bytes costs 70 to 85% when the structure doesn't fit |
| 1180 | + in the caches. This is the main argument against making every `^T` |
| 1181 | + a fat generational pointer (section 19). It is also why `Pool`'s |
| 1182 | + handles cost half again: the 32-byte slots, not the check. |
| 1183 | +- **Handles cost 1.5–2× where pointer chasing dominates**, which is |
| 1184 | + linked lists and trees. A safe program pays it only for the records |
| 1185 | + it frees one by one; everything else stays a lasting `^T` with no |
| 1186 | + check. |
| 1187 | + |
| 1188 | +### 13.3 What each part costs a program |
| 1189 | + |
| 1190 | +| Part | Cost | Where | |
| 1191 | +|---|---|---| |
| 1192 | +| A, the fence | none | compile time | |
| 1193 | +| B, lending | none | compile time | |
| 1194 | +| C, counts | `inc`/`dec` per lend held, or `lock xadd` with threads; a word per holding local | once per `Buf.bytes`, `Vec.all`, `Vec.add`: not per element | |
| 1195 | +| C, retired blocks | memory: at most the current block again, only while a lend is held across a growth | rare | |
| 1196 | +| D, no `free` | none for lasting pointers; handles where chosen, 1.5–2× on chasing | `Pool` users only | |
| 1197 | +| E, atomic slices | none: two 8-byte moves become one 16-byte one; records holding slices may grow by padding to 16 | `src/` has 10 such fields | |
| 1198 | +| E, atomic counts | about 20 cycles per lend, with threads only | | |
| 1199 | +| F, temporaries | frame size | | |
| 1200 | +| G, the debugging heap | none unless chosen | | |
| 1201 | + |
| 1202 | +--- |
| 1203 | + |
| 1204 | +## 14. Ergonomics |
| 1205 | + |
| 1206 | +### 14.1 What doesn't change |
| 1207 | + |
| 1208 | +Most raz is already safe under this proposal: the survey's `Parse`, |
| 1209 | +`Item`, `Sym` and `Gen`, `tools/`, rjson's parser, rflate's inflater, |
| 1210 | +rterm. They use records, slices, `var`, `const` and pointers from |
| 1211 | +`NEW`, and they don't free. For them the change is a few `ret`s in the |
| 1212 | +library's headings, which the caller never writes. |
| 1213 | + |
| 1214 | +### 14.2 What a programmer meets |
| 1215 | + |
| 1216 | +**A slice of a buffer kept in a record.** rnet's `Http.Message` keeps |
| 1217 | +`headers[i].name` as slices of `m^.head`'s bytes and `body` as a slice |
| 1218 | +of `m^.data`. Under part B and C these are lent by owners and can't be |
| 1219 | +stored in a record. The choices: |
| 1220 | + |
| 1221 | +1. Offsets instead of slices: |
| 1222 | + |
| 1223 | + ``` |
| 1224 | + Header* = record name, value: Span; end; (* Span = record at, len: INT; end *) |
| 1225 | + proc name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by m *) |
| 1226 | + ``` |
| 1227 | + |
| 1228 | + which is safe, a little longer, and survives `m^.head` growing. It |
| 1229 | + is how Rust programs without lifetimes in structs do it. |
| 1230 | +2. `Http` says `unsafe;`, and keeps its invariant by hand, as it does |
| 1231 | + today. It becomes one of the modules a reviewer reads twice. |
| 1232 | + |
| 1233 | +The proposal recommends the first for libraries, since it is what |
| 1234 | +the guarantee is for. |
| 1235 | + |
| 1236 | +**A slice held across a call that might change its owner.** This is |
| 1237 | +allowed. Part C counts it, and the owner retires instead of freeing. |
| 1238 | +rmacs's `save`, with its `path := Buf.bytes(x^.path)` held across |
| 1239 | +`Buf.reset(tmp)` and `Buf.str(tmp, path)`, compiles and runs as |
| 1240 | +before. |
| 1241 | + |
| 1242 | +**`done` with a slice still held.** This stops the program at run time: |
| 1243 | + |
| 1244 | +``` |
| 1245 | +proc report(x: ^Buffer); |
| 1246 | +var name: []U8; |
| 1247 | +begin |
| 1248 | + name := Buf.bytes(x^.name); |
| 1249 | + Buf.done(x^.name); (* stops: name still holds a lend *) |
| 1250 | + ... |
| 1251 | +end; |
| 1252 | +``` |
| 1253 | + |
| 1254 | +The cure is `name := []` before `done`, or not holding it. It is a |
| 1255 | +false alarm only when `name` is never read again. Since a stop is |
| 1256 | +loud and the cure is one line, the proposal accepts it. |
| 1257 | + |
| 1258 | +**Owners can't be copied.** `head := m^.head` in rnet becomes |
| 1259 | +`Buf.take(m^.head, head)`. The survey didn't count such copies; rnet's |
| 1260 | +`Http.reset` is the one found by reading. |
| 1261 | + |
| 1262 | +**Records that come and go.** An editor's windows, freed when closed, |
| 1263 | +become a `Pool(Window)` with `Handle`s where rmacs had `^Window` and |
| 1264 | +`Mem.free`. Each access is `Windows.at(pool, h)^.field` or `get`. This is |
| 1265 | +longer than `w^.field`, and 1.5–2× slower in a pointer-chasing loop, |
| 1266 | +which an editor doesn't have. |
| 1267 | + |
| 1268 | +**An arena with links.** A tree built in an arena with `^Node` links |
| 1269 | +can't be safe (8.4): links are stored in records, and lent pointers |
| 1270 | +can't be. It becomes indexes into a `Vec(Node)`, which is often faster |
| 1271 | +(smaller, contiguous), or stays in an unsafe module. |
| 1272 | + |
| 1273 | +**Strings that must be freed.** `Str.copy` and `Str.free` become |
| 1274 | +`Names(V)` or a `Buf` per string (8.3). |
| 1275 | + |
| 1276 | +**Threads.** `Thread.spawn(work, ^U8(ADR(job)))` becomes |
| 1277 | +`Jobs.spawn(work, job)`, with `import Jobs := Task(Job)`. That is |
| 1278 | +shorter. |
| 1279 | + |
| 1280 | +### 14.3 What the compiler says |
| 1281 | + |
| 1282 | +Each new error names the rule and the mending, in the house style: |
| 1283 | + |
| 1284 | +``` |
| 1285 | +error: ADR is for unsafe modules |
| 1286 | + help: pass x as a var parameter, or say "unsafe;" after the module's imports |
| 1287 | +error: Names.put keeps its key, and buf[0..8] is lent by this call's frame |
| 1288 | + help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) |
| 1289 | +error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable |
| 1290 | +error: a Buf.Buf owns memory, and can't be copied |
| 1291 | + help: Buf.take(from, to) moves it |
| 1292 | +error: Str.trim(s) is lent by s, which isn't marked ret |
| 1293 | + help: mark the parameter "ret s: []U8" to return what points into it |
| 1294 | +error: Mem.free is an unsafe procedure |
| 1295 | + help: free through the container that owns the memory, or say "unsafe;" |
| 1296 | +``` |
| 1297 | + |
| 1298 | +and two new run-time stops: |
| 1299 | + |
| 1300 | +``` |
| 1301 | +Buf.done while 1 slice it lent is still held |
| 1302 | +Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) |
| 1303 | +``` |
| 1304 | + |
| 1305 | +--- |
| 1306 | + |
| 1307 | +## 15. What breaks |
| 1308 | + |
| 1309 | +Everything breaks that uses a fenced operation in a module that |
| 1310 | +doesn't say `unsafe;`, or stores a lent reference, or copies an |
| 1311 | +owner. By codebase: |
| 1312 | + |
| 1313 | +| Code | What breaks | The mending | |
| 1314 | +|---|---|---| |
| 1315 | +| `lib/` | every module with a fenced operation: `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, `Thread`, `Lock`, `C`, `CAbi`, `Buf`, `Vec`, `Map`, `List` | `unsafe;` | |
| 1316 | +| | `Str`, `Fmt`, `Opt`, `Files` | drop two to five operations each; they become safe | |
| 1317 | +| | headings: `ret` on `Str.trim`, `trimLeft`, `trimRight`, `cut`, `field`, `Buf.bytes`, `spare`, `Vec.all`, `add`, `Sys.nextEntry`; `keep` on `Map.put`, `List.push`, `Vec.push`, `tryPush`, `Opt.init`, `scope` | marks | |
| 1318 | +| | `Buf`, `Vec`, `Map`, `List`, `Arena`: a `LENDS` field, retiring, `done`'s stop, `take`, `swap` | about 15 lines each | |
| 1319 | +| | new: `Pool`, `Task`, `Names`, `Lock.Guarded`, `Arena.allocator`; `Heap`'s debugging mode | about 400 lines in all | |
| 1320 | +| | `unsafe proc`: `Mem.free`, `Mem.unmap`, `Heap`'s `free`, `Str.free`, `Sys.mmap`, `Sys.munmap`, `Thread.spawn`, the `Sys` calls that take a raw pointer; `Mem.Allocator`'s fields | a word each | |
| 1321 | +| `src/` | all eleven modules (section 2.2) | grown arrays to `Vec` (35 sites), `intern(s)` (7), views (6), `var` (6), `Sys.info` (1); `Scan` stays `unsafe;` | |
| 1322 | +| `tools/` | nothing fenced; any `Map.put` of a frame slice | none found | |
| 1323 | +| `examples/` | `Args`, `Cpu`, `Pthreads`, `Printf`, `Window`, `Volatile`, `Sh`, `Workers` | `Args`, `Sh`, `Workers` mended; the other five say `unsafe;`, as examples of it | |
| 1324 | +| `test/run`, `test/libc`, `conform/` | the tests of `ADR`, pointers, C | `unsafe;` in each; new tests in `conform/` for the guarantee: what is an error, and what stops | |
| 1325 | +| rnet | `Http.Message` keeps lent slices; `reset` copies `Buf`s; `Thread.spawn` | spans and accessors; `take`; `Task` | |
| 1326 | +| rjson | `Str.free` and `Mem.free` (6); a few casts | `Names` or `Buf`; views | |
| 1327 | +| rflate | none beyond `ADR` at calls (gone with v0.19.0's library) | none | |
| 1328 | +| rsqlite | C | `unsafe;` on `Sqlite` | |
| 1329 | +| rmacs, ravite | `ADR` at calls (gone with v0.19.0); `Mem.free` (9 and 2) of windows and buffers | `Pool` | |
| 1330 | +| rlX11 | casts on X11 replies | views; one unsafe module for the socket's bytes | |
| 1331 | +| rmacs's and ravite's `Scan` use | `tools/Scan.raz` | nothing fenced | |
| 1332 | + |
| 1333 | +Every break is found when compiling, with a message that names its |
| 1334 | +mending, except a `done` while a lend is held, which shows up at run |
| 1335 | +time with a message. No program changes meaning without an error. |
| 1336 | + |
| 1337 | +A `raz -fix` (or `tools/Mutate.raz` taught the rewrites) can make |
| 1338 | +the mechanical ones: `ADR(x)` at a `var` parameter, `^F64(ADR(x))` to |
| 1339 | +a view, `intern(ADR(s[0]), LEN(s))` to `intern(s)`, `unsafe;` where a |
| 1340 | +module keeps a fenced operation after those. |
| 1341 | + |
| 1342 | +--- |
| 1343 | + |
| 1344 | +## 16. Changes to the report |
| 1345 | + |
| 1346 | +The report grows by about three pages, from 32 to 35, inside its |
| 1347 | +40. By section: |
| 1348 | + |
| 1349 | +**1. A first look.** One paragraph: what is safe, what `unsafe;` |
| 1350 | +means, where to read more. |
| 1351 | + |
| 1352 | +**3. Modules.** The grammar takes the line: |
| 1353 | + |
| 1354 | +``` |
| 1355 | +Module = "module" ident [ "(" ModParams ")" ] ";" |
| 1356 | + { Import } { Link } [ Check ] [ Unsafe ] { Declaration } |
| 1357 | + [ "begin" Statements ] "end" ident "." . |
| 1358 | +Unsafe = "unsafe" ";" . |
| 1359 | +``` |
| 1360 | + |
| 1361 | +A new paragraph, **`unsafe;`**, says what it allows (the table of |
| 1362 | +5.1), and that `link` and `check off;` need it. **Generic modules**: |
| 1363 | +an instance is safe or unsafe as its generic module is, as with |
| 1364 | +`check`. |
| 1365 | + |
| 1366 | +**5.3 Slices.** "A slice is aligned to twice an address's |
| 1367 | +alignment, and read and written in one access (7.6)." |
| 1368 | + |
| 1369 | +**5.4 Pointers.** A paragraph: in a safe module a pointer is `nil`, |
| 1370 | +from `NEW`, or from the library; section 8.x says how long it lives. |
| 1371 | + |
| 1372 | +**5.5 Records.** **Owners**: a record with a `LENDS` field; it can't |
| 1373 | +be copied in a safe module (7.6 of this proposal). `LENDS` joins the |
| 1374 | +basic types in 5.1, as a type only a record's field may have. |
| 1375 | + |
| 1376 | +**5.9 Procedure types.** `unsafe proc`, and the marks `ret` and `keep`, |
| 1377 | +which a procedure type carries; what may stand where (PROPOSALS). |
| 1378 | + |
| 1379 | +**6.4 Pointers.** `p + i`, `p - i`, `p[i]` and `p[lo..hi]`: "only in an |
| 1380 | +unsafe module". |
| 1381 | + |
| 1382 | +**6.7 Conversions.** The pointer rows: "only in an unsafe module". |
| 1383 | + |
| 1384 | +**6.8 Built-in procedures.** `ADR`, `PTR`, `SYSCALL` and `ARGV`: "only in |
| 1385 | +an unsafe module". `NEW` (part D): what it gives lasts, or is lent by |
| 1386 | +its allocator's owner. `CAS`, `XCHG` and `XADD` take a variable. |
| 1387 | + |
| 1388 | +**6.9 Views.** Writing a view of a variable that holds a pointer, |
| 1389 | +slice, procedure, variant, enumeration or `BOOL`, and a view as a |
| 1390 | +pointer type, are for unsafe modules. |
| 1391 | + |
| 1392 | +**7.3 Return.** The paragraph on slices of the frame is replaced by a |
| 1393 | +reference to the new section 8.x, which covers every route. |
| 1394 | + |
| 1395 | +**7.6 Volatile.** "Nothing else of the program becomes undefined by |
| 1396 | +it" becomes: a race on a variable of a basic, pointer, procedure or |
| 1397 | +slice type gives a value it had or was given, never a mixture; a race |
| 1398 | +on anything else, or on a container's procedures called at once, is |
| 1399 | +outside the guarantee (10). |
| 1400 | + |
| 1401 | +**8. Procedures.** The marks `ret` and `keep` in the grammar, |
| 1402 | +`Params = [ "ret" ] [ "keep" ] [ "var" | "const" ] ...`, and |
| 1403 | +`ProcDeclaration` takes `[ "unsafe" ]` before `proc`. A new section, |
| 1404 | +**8.x Lending**, about two pages, with part B's rules (lasting, |
| 1405 | +lent, by whom; what may be done with each) and part C's counting, |
| 1406 | +and the examples of 6.4 of this proposal. An array a call returns, and a |
| 1407 | +`const` parameter's temporary, live to the end of the procedure |
| 1408 | +(part F). The paragraph "kept past its statement ... the exception of |
| 1409 | +section 10" goes. |
| 1410 | + |
| 1411 | +**9. Calling C.** "`extern` and `link` only in an unsafe module." |
| 1412 | + |
| 1413 | +**10. Programs.** **Defined behaviour** becomes **The guarantee** |
| 1414 | +(section 3), and the list of exceptions shrinks to one sentence: an |
| 1415 | +unsafe module, a code procedure and C may break memory, and what |
| 1416 | +follows isn't defined; a safe program can't. The stops stay as they |
| 1417 | +are, and the two new run-time stops are added: an owner's `done` with |
| 1418 | +lends held, and a library container's own checks (a stale handle). **Errors**: a |
| 1419 | +fenced operation outside an unsafe module, a lent value where it can't |
| 1420 | +go, a copied owner, a call of an `unsafe proc` from a safe module. |
| 1421 | + |
| 1422 | +**Appendix A.** How slices are made one access (16-byte moves, or a |
| 1423 | +lock, or a refused target); whether writing a string constant stops or |
| 1424 | +changes it; how the debugging heap is chosen. |
| 1425 | + |
| 1426 | +**Appendix B.** The grammar's new lines. |
| 1427 | + |
| 1428 | +**The library volume.** `unsafe proc` and `ret`/`keep` in every |
| 1429 | +heading; `Pool`, `Task`, `Names`, `Lock.Guarded`; owners' `take`, |
| 1430 | +`swap` and their stop; `Heap`'s debugging mode. `Mem.Allocator` |
| 1431 | +described as an unsafe interface. Which modules are unsafe, and their |
| 1432 | +promise. |
| 1433 | + |
| 1434 | +**`doc/report-history.md`**, **`doc/compiler.md`** (each rule, where in |
| 1435 | +the compiler, with code before and after), **raz(7)**, the tutorial and |
| 1436 | +`STANDARDS.md` ("a parameter is a value, `var`, `const`, or `keep`; a |
| 1437 | +pointer only in an unsafe module or where `NEW` gave it"). |
| 1438 | + |
| 1439 | +--- |
| 1440 | + |
| 1441 | +## 17. Changes to the library |
| 1442 | + |
| 1443 | +| Module | Change | |
| 1444 | +|---|---| |
| 1445 | +| `Mem` | `Allocator`'s fields `unsafe proc`; `free`, `unmap`, `pages` `unsafe proc`s | |
| 1446 | +| `Heap` | `free` unsafe; the debugging mode (part G); big blocks' address ranges kept reserved after `free` in debugging mode | |
| 1447 | +| `Arena` | an owner; `allocator(ret var ar)`; `reset` and `done` stop if lends are held | |
| 1448 | +| `Buf` | an owner; `bytes`, `spare` `ret`; retiring; `done` stops; `take`, `swap` | |
| 1449 | +| `Vec` | an owner; `all`, `add`, `tryAdd` `ret`; `push`, `tryPush` `keep x`; retiring; `done` stops; `take`, `swap` | |
| 1450 | +| `Map` | an owner (it counts no lends, but isn't copied); `put` `keep k`, `keep v` | |
| 1451 | +| `List` | an owner; `push` `keep v` | |
| 1452 | +| `Str` | `trim`, `trimLeft`, `trimRight`, `cut`, `field` `ret`; `free` unsafe; `copy` documented as lasting; safe module | |
| 1453 | +| `Fmt`, `Opt`, `Files` | made safe; `Opt.init`, `scope` `keep` | |
| 1454 | +| `Sys` | the raw-pointer calls `unsafe proc`; `nextEntry` `ret`; the rest safe to call | |
| 1455 | +| `Thread` | `spawn` unsafe; `Mutex` taken by `var`, as now | |
| 1456 | +| `Lock` | `Guarded(T)` | |
| 1457 | +| new `Pool(T)` | 8.2 | |
| 1458 | +| new `Task(T)` | 9.2 | |
| 1459 | +| new `Names(V)` | 8.3 | |
| 1460 | + |
| 1461 | +--- |
| 1462 | + |
| 1463 | +## 18. Changes to the compiler |
| 1464 | + |
| 1465 | +Where each part goes in `src/`, and about how big each is. The |
| 1466 | +budget is 14,000 lines of code and the compiler is about 11,500 today. |
| 1467 | + |
| 1468 | +| Part | Where | Lines | |
| 1469 | +|---|---|---| |
| 1470 | +| A. The fence | a flag on the module, set by `unsafe;` in `Parse`; a check at each place the survey's counting build hooked (`Item.index`, `slice`, `op2`, `convert`, `view`, `indexView`; `Parse`'s `ADR`, `PTR`, `SYSCALL`) and at `ARGV`, `extern`, `link`, `check` and code procedures; `unsafe proc` on `Obj` and on procedure types | 120 | |
| 1471 | +| B. Lending | PROPOSALS' estimate: a set of lenders on each `Item` in place of today's `frame: BOOL` (`Item.raz:58`), the same on each local, the checks, the list that waits for `end`; plus pointers followed as slices are | 300–450 | |
| 1472 | +| C. Owners | `LENDS` as a type; `Sym`'s owner flag; the hold slots, the raise and lower in `Gen`, the let-go in the epilogue (reusing `defer`'s); the copy checks | 200 | |
| 1473 | +| D. `NEW`'s provenance | lasting or lent by its allocator | 20 | |
| 1474 | +| E. Atomic slices | 16-byte alignment in `Sym`, `movdqa` in `X64`'s slice moves; atomics taking variables; `lock xadd` counts when `Thread` is imported | 80 | |
| 1475 | +| F. Temporaries | the slot reserved to the end, as `defer`'s are | 20 | |
| 1476 | +| Messages, with help | | 100 | |
| 1477 | +| **In all** | | **840–990** | |
| 1478 | + |
| 1479 | +So the compiler grows to about 12,400–12,500 lines, inside the budget, |
| 1480 | +with room for the documentation the house style demands. The |
| 1481 | +rewrite of `src/` to be safe (section 15) takes lines away: 35 grown |
| 1482 | +arrays made `Vec`s. |
| 1483 | + |
| 1484 | +Each rule is explained in `doc/compiler.md` where it is done, with the |
| 1485 | +code before and after, as CLAUDE.md asks. |
| 1486 | + |
| 1487 | +--- |
| 1488 | + |
| 1489 | +## 19. Alternatives considered |
| 1490 | + |
| 1491 | +**A garbage collector.** It would make `free` and part C unneeded, as in |
| 1492 | +Go, Java and Oberon. It is rejected: raz promises "a static executable |
| 1493 | +with no run time besides the code it uses" (10). A collector needs |
| 1494 | +stack maps, barriers or pauses, and a heap the language owns, and it |
| 1495 | +would end raz as a systems language with a C-like footprint. |
| 1496 | + |
| 1497 | +**Rust's borrow checker.** It closes everything, races included, at |
| 1498 | +compile time. It is rejected for raz: lifetimes in types, regions |
| 1499 | +inferred over whole procedures (non-lexical lifetimes are a fixpoint |
| 1500 | +over the control flow, not one pass), and a learning curve that is |
| 1501 | +the opposite of "a beginner can follow". The proposal takes from it |
| 1502 | +`ret` (elision, written) and `keep` (`'static`), and leaves out |
| 1503 | +lifetimes in records, knowing what that costs (14.2). |
| 1504 | + |
| 1505 | +**Fat generational pointers for every `^T`** (Vale). Every `^T` would |
| 1506 | +become (address, generation), and `free` would be safe and checked at |
| 1507 | +every dereference. Measured (13.2): the check costs little, since the |
| 1508 | +generation sits in the object's cache line, but doubling a pointer |
| 1509 | +cost 70–85% on a structure past the caches. Records with pointers grow, |
| 1510 | +C interop needs a second, raw pointer type, and the 1,015 dereferences |
| 1511 | +in `src/`, of memory never freed, would pay for a check they can't fail. |
| 1512 | +It is kept as a fallback if part D proves too narrow: `Pool` is the |
| 1513 | +same mechanism, where it is paid for only by what is freed. |
| 1514 | + |
| 1515 | +**Statically killing a lent slice when its owner changes.** One-pass |
| 1516 | +flow analysis can't see a loop's back edge, and through a pointer |
| 1517 | +every call may change the owner (7.1). It would need a second pass, or |
| 1518 | +a rule so strict ("a lent slice dies at the end of its statement") |
| 1519 | +that `s := Buf.bytes(b)` over several lines, 35 places in the survey, |
| 1520 | +would all break. |
| 1521 | + |
| 1522 | +**Stop on growth while lent, instead of retiring.** It is simpler to |
| 1523 | +explain, and it finds the stale-pointer bug in 1.2 at once. But it also |
| 1524 | +stops `Buf.str(b, Buf.bytes(b))`, which is right and common in other |
| 1525 | +languages (Go's `append(s, s...)`). Retiring keeps right programs |
| 1526 | +running, and the debugging heap (part G) shows the stale ones. |
| 1527 | + |
| 1528 | +**Thread-local module variables, or `Send`/`Sync`.** They are needed |
| 1529 | +for a static race guarantee. They are left for later (9.3): they |
| 1530 | +cost a second type system for a feature little used. If they come, |
| 1531 | +part E's statement grows to cover every program, and nothing else in |
| 1532 | +this proposal changes. |
| 1533 | + |
| 1534 | +**Hardware: memory tagging (ARM MTE) and CHERI.** They catch use |
| 1535 | +after free and out-of-bounds by tagging memory and pointers. They |
| 1536 | +help unsafe modules and C, they aren't on x86-64, and they are |
| 1537 | +probabilistic (MTE's four bits). They would make part G stronger, |
| 1538 | +not replace B to D. |
| 1539 | + |
| 1540 | +**Only the fence (PROPOSALS' piece 4).** It is cheap and gives a list |
| 1541 | +of modules to audit, but what it leaves undefined in safe code is |
| 1542 | +exactly 1.2's first four programs. A fence around code that is still |
| 1543 | +unsafe would mislead the reader. That is why this proposal exists. |
| 1544 | + |
| 1545 | +--- |
| 1546 | + |
| 1547 | +## 20. Order of work |
| 1548 | + |
| 1549 | +Each step is a release, and each leaves `make check` passing and every |
| 1550 | +program building, with warnings where a later step will make errors. |
| 1551 | + |
| 1552 | +1. **The debugging heap (G).** It changes no rule, and finds bugs in |
| 1553 | + today's code, the library's above all, before the rules arrive. |
| 1554 | + Run `make check` under it. |
| 1555 | +2. **Temporaries to the end of the procedure (F.1), strings (F.2).** |
| 1556 | + No program breaks. |
| 1557 | +3. **Atomic slices, and 7.6 rewritten (E.1, E.2).** No program breaks. |
| 1558 | +4. **`ret` and `keep` (B), as warnings,** then errors a release later. |
| 1559 | + Mark the library. This is PROPOSALS' part 3, extended to |
| 1560 | + pointers. |
| 1561 | +5. **Owners (C).** `LENDS` in the containers, retiring, counting, |
| 1562 | + `take` and `swap`; the copy check as a warning, then an error. |
| 1563 | +6. **The heap (D).** `Pool`, `Names`, `Task`; `free` an `unsafe |
| 1564 | + proc`, warned of first. |
| 1565 | +7. **The fence (A),** last, as a warning for one release, then an |
| 1566 | + error, once everything it would flag has a safe form. `src/` comes |
| 1567 | + to it, keeping `Scan` unsafe, or not, by the owner's word (21). |
| 1568 | +8. **The report's guarantee (section 10),** stated when step 7 makes |
| 1569 | + it true. |
| 1570 | + |
| 1571 | +`src/` must build with the release `BOOT` names, so it takes up each |
| 1572 | +step one release after the step ships. |
| 1573 | + |
| 1574 | +--- |
| 1575 | + |
| 1576 | +## 21. Open questions |
| 1577 | + |
| 1578 | +1. **Does `Scan` stay unsafe?** Checking its buffer costs the |
| 1579 | + compiler 4.5% (13.1). Leaving it unsafe keeps the speed, and the |
| 1580 | + compiler then has one unsafe module, which is easy to read. |
| 1581 | +2. **`LENDS` as a type, or a mark on the record** (`owner record`)? |
| 1582 | + The field makes the count visible to the module that reads it, and |
| 1583 | + needs no new word; a mark would be more explicit. |
| 1584 | +3. **Should `done` with a lend held leak instead of stopping?** It |
| 1585 | + would mean no false alarms, but a silent leak that can grow. |
| 1586 | +4. **Is a local record holding an owner-lent slice worth allowing?** |
| 1587 | + (7.3 forbids it.) It needs one hold per reference in the record, and |
| 1588 | + a let-go when the record is reassigned. `Fmt.Arg` arrays are the |
| 1589 | + case: `[Fmt.str(Buf.bytes(b))]` is fine inside a statement, but not |
| 1590 | + held in a local array. |
| 1591 | +5. **Is the race guarantee enough?** A cheap dynamic check would close |
| 1592 | + the container case in programs with threads: each owner records |
| 1593 | + the thread that last changed it, and changes from another thread |
| 1594 | + without the lock stop the program, as Swift's exclusivity checks do. |
| 1595 | +6. **`Pool`'s handle**: two words, or one, with 40 bits of index and 24 |
| 1596 | + of generation? One word fits in a register and halves `Pool`'s |
| 1597 | + memory for handles, and generations would wrap after 16 million |
| 1598 | + frees of one slot. |
| 1599 | +7. **`unsafe` per procedure, not per module?** Rust's `unsafe` blocks |
| 1600 | + are finer. A module is raz's unit of review, and a module can be |
| 1601 | + split, but `Sys` would need a split into a safe and an unsafe half |
| 1602 | + for readers to see the difference. |
| 1603 | + |
| 1604 | +--- |
| 1605 | + |
| 1606 | +## Appendix 1: the survey's numbers |
| 1607 | + |
| 1608 | +Places of each operation, counted once each, by the instrumented |
| 1609 | +compiler. `deref` and `new` are shown for scale; they stay safe, as |
| 1610 | +does `p - q`, which the module table below counts with the rest. |
| 1611 | + |
| 1612 | +| Code | `ADR` | deref | `p[i]` | `p[a..b]` | `p ± i` | `p - q` | ptr cast | int→ptr | ptr→int | view | `NEW` | `SYSCALL` | |
| 1613 | +|---|---|---|---|---|---|---|---|---|---|---|---|---| |
| 1614 | +| raz `src/` | 27 | 1,015 | 277 | 30 | 3 | 0 | 42 | 0 | 0 | 0 | 5 | 3 | |
| 1615 | +| raz `lib/` | 144 | 93 | 88 | 14 | 49 | 2 | 52 | 13 | 4 | 2 | 1 | 140 | |
| 1616 | +| raz `examples/` | 15 | 46 | 2 | 1 | 0 | 0 | 5 | 0 | 0 | 3 | 1 | 0 | |
| 1617 | +| raz `test/libc` | 110 | 15 | 35 | 11 | 18 | 0 | 64 | 1 | 6 | 0 | 1 | 0 | |
| 1618 | +| rnet | 471 | 359 | 0 | 0 | 0 | 0 | 9 | 1 | 1 | 0 | 0 | 0 | |
| 1619 | +| rjson | 91 | 105 | 0 | 7 | 1 | 0 | 13 | 0 | 0 | 0 | 0 | 0 | |
| 1620 | +| rflate | 61 | 102 | 0 | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 2 | 0 | |
| 1621 | +| rsqlite | 38 | 12 | 1 | 3 | 0 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | |
| 1622 | + |
| 1623 | +The fenced operations of each module of `src/` and `lib/`: |
| 1624 | + |
| 1625 | +| Module | Fenced | Of which | |
| 1626 | +|---|---|---| |
| 1627 | +| `src/Scan` | 99 | `p[i]` 76, casts 12, `p[a..b]` 6, `ADR` 3, `p ± i` 2 | |
| 1628 | +| `src/Link` | 71 | `p[i]` 63, `p[a..b]` 4, casts 4 | |
| 1629 | +| `src/Chunk` | 65 | `p[i]` 53, casts 10, `p[a..b]` 1, `ADR` 1 | |
| 1630 | +| `src/X64` | 31 | `p[i]` 23, `ADR` 5, casts 3 | |
| 1631 | +| `src/Diag` | 23 | `p[i]` 15, `p[a..b]` 3, casts 3, `ADR` 2 | |
| 1632 | +| `src/Elf` | 23 | `p[i]` 17, `p[a..b]` 3, `ADR` 3 | |
| 1633 | +| `src/Parse` | 21 | `p[a..b]` 8, `ADR` 5, `p[i]` 5, casts 2, `SYSCALL` 1 | |
| 1634 | +| `src/Sym` | 17 | `p[i]` 12, casts 3, `ADR` 2 | |
| 1635 | +| `src/Item` | 16 | `p[i]` 5, `p[a..b]` 4, casts 4, `ADR` 3 | |
| 1636 | +| `src/Gen` | 8 | `p[i]` 5, `ADR` 2, casts 1 | |
| 1637 | +| `src/Raz` | 8 | `p[i]` 3, `SYSCALL` 2, `ADR` 1, `p[a..b]` 1, `p ± i` 1 | |
| 1638 | +| `lib/Sys` | 287 | `SYSCALL` 129, `ADR` 98, `p[i]` 31, casts 12, `p ± i` 8, `p[a..b]` 6 | |
| 1639 | +| `lib/Rt` | 111 | `p ± i` 32, `p[i]` 31, casts 20, `ADR` 10, int→ptr 10, `SYSCALL` 6 | |
| 1640 | +| `lib/Thread` | 33 | `ADR` 16, casts 6, `SYSCALL` 5, `p[i]` 3, `p ± i` 3 | |
| 1641 | +| `lib/Map` | 19 | `p[i]` 16, casts 3 | |
| 1642 | +| `lib/Heap` | 16 | `p ± i` 4, casts 4, ptr→int 4, `p[i]` 2 | |
| 1643 | +| `lib/Bytes` | 10 | `ADR` 5, casts 5 | |
| 1644 | +| `lib/Buf` | 6 | `p[a..b]` 4, `p[i]` 1, `ADR` 1 | |
| 1645 | +| `lib/Opt` | 5 | `ADR` 5 | |
| 1646 | +| `lib/Arena` | 4 | `p ± i` 2, `ADR` 1, cast 1 | |
| 1647 | +| `lib/Fmt` | 4 | `ADR` 4 | |
| 1648 | +| `lib/Files`, `lib/Str` | 3 each | | |
| 1649 | +| `lib/Lock`, `lib/Mem` | 2 each | | |
| 1650 | +| `lib/List` | 1 | | |
| 1651 | +| `lib/Math`, `Out`, `Sort`, `Width` | 0 | | |
| 1652 | + |
| 1653 | +`Vec` (generic, and instantiated by no program surveyed) has 11 by |
| 1654 | +`grep`. `C` and `CAbi` are `extern` declarations (96 and 2). |
| 1655 | + |
| 1656 | +By `grep`, for the code today's compiler refuses (written before |
| 1657 | +`INT`): |
| 1658 | + |
| 1659 | +| Code | Lines of code | `ADR` | at a call | casts | frees | `done` | `reset` | |
| 1660 | +|---|---|---|---|---|---|---|---| |
| 1661 | +| rmacs | 4,323 | 560 | 556 | 9 | 9 | 16 | 66 | |
| 1662 | +| ravite | 2,185 | 202 | 200 | 3 | 2 | 1 | 15 | |
| 1663 | +| rlX11 | 5,226 | 89 | 87 | 3 | 1 | 0 | 0 | |
| 1664 | + |
| 1665 | +## Appendix 2: the benchmarks |
| 1666 | + |
| 1667 | +Built with `raz -o MemBench MemBench.raz` and run as they are. Both |
| 1668 | +are in the session's scratch space and can be added to `test/bench` |
| 1669 | +if the proposal goes ahead. |
| 1670 | + |
| 1671 | +``` |
| 1672 | +module MemBench; |
| 1673 | +import Out, Sys; |
| 1674 | + |
| 1675 | +const |
| 1676 | + Big = 1000000; (* past the caches *) |
| 1677 | + Small = 1000; (* in L1 *) |
| 1678 | + Bytes = 16000000; |
| 1679 | + |
| 1680 | +type |
| 1681 | + Node = record next: ^Node; val: INT; end; |
| 1682 | + H = record i: INT; gen: INT; end; |
| 1683 | + Slot = record next: H; val: INT; gen: INT; end; |
| 1684 | + |
| 1685 | +var |
| 1686 | + nodes: [Big]Node; |
| 1687 | + slots: [Big]Slot; |
| 1688 | + perm: [Big]INT; |
| 1689 | + bytes: [Bytes]U8; |
| 1690 | + sink: INT; |
| 1691 | + |
| 1692 | +(* A random cycle through the first n nodes, the same in both arrays *) |
| 1693 | +proc build(n: INT); |
| 1694 | +var i, j, t: INT; seed: U64; |
| 1695 | +begin |
| 1696 | + seed := 7; |
| 1697 | + for i := 0 to n - 1 do perm[i] := i; end; |
| 1698 | + for i := n - 1 to 1 by -1 do |
| 1699 | + seed := seed * 6364136223846793005 + 1442695040888963407; |
| 1700 | + j := INT(seed shr 33) mod (i + 1); |
| 1701 | + t := perm[i]; perm[i] := perm[j]; perm[j] := t; |
| 1702 | + end; |
| 1703 | + for i := 0 to n - 1 do |
| 1704 | + j := perm[(i + 1) mod n]; |
| 1705 | + nodes[perm[i]] := {next: ADR(nodes[j]), val: i}; |
| 1706 | + slots[perm[i]] := {next: {i: j, gen: 3}, val: i, gen: 3}; |
| 1707 | + end; |
| 1708 | +end; |
| 1709 | + |
| 1710 | +proc chasePtr(steps: INT): INT; |
| 1711 | +var p: ^Node; s, k: INT; |
| 1712 | +begin |
| 1713 | + p := ADR(nodes[perm[0]]); |
| 1714 | + for k := 1 to steps do s := s + p^.val; p := p^.next; end; |
| 1715 | + return s; |
| 1716 | +end; |
| 1717 | + |
| 1718 | +(* As a checked Pool.get would: the generation, and the index *) |
| 1719 | +proc chaseHandle(steps: INT): INT; |
| 1720 | +var h: H; s, k: INT; |
| 1721 | +begin |
| 1722 | + h := {i: perm[0], gen: 3}; |
| 1723 | + for k := 1 to steps do |
| 1724 | + if slots[h.i].gen # h.gen then Sys.exit(3); end; |
| 1725 | + s := s + slots[h.i].val; |
| 1726 | + h := slots[h.i].next; |
| 1727 | + end; |
| 1728 | + return s; |
| 1729 | +end; |
| 1730 | + |
| 1731 | +proc sumPtr(p: ^U8; n, reps: INT): INT; |
| 1732 | +var s, i, r: INT; |
| 1733 | +begin |
| 1734 | + for r := 1 to reps do |
| 1735 | + for i := 0 to n - 1 do s := s + INT(p[i]); end; |
| 1736 | + end; |
| 1737 | + return s; |
| 1738 | +end; |
| 1739 | + |
| 1740 | +proc sumSlice(b: []U8; reps: INT): INT; |
| 1741 | +var s, i, r: INT; |
| 1742 | +begin |
| 1743 | + for r := 1 to reps do |
| 1744 | + for i := 0 to LEN(b) - 1 do s := s + INT(b[i]); end; |
| 1745 | + end; |
| 1746 | + return s; |
| 1747 | +end; |
| 1748 | +``` |
| 1749 | + |
| 1750 | +`main` builds `Big`, times each chase for 100,000,000 steps, builds |
| 1751 | +`Small`, times each for 500,000,000, then the sums: 16,000,000 bytes 50 |
| 1752 | +times and 4,000 bytes 200,000 times. `GenBench.raz` is the same chase |
| 1753 | +with 32-byte records on both sides: |
| 1754 | + |
| 1755 | +``` |
| 1756 | +type |
| 1757 | + Node = record next: ^Node; val, pad1, pad2: INT; end; |
| 1758 | + GP = record p: ^GNode; gen: INT; end; |
| 1759 | + GNode = record gen: INT; next: GP; val: INT; end; |
| 1760 | + |
| 1761 | +proc chaseGen(steps: INT): INT; |
| 1762 | +var g: GP; s, k: INT; |
| 1763 | +begin |
| 1764 | + g := {p: ADR(gnodes[perm[0]]), gen: 5}; |
| 1765 | + for k := 1 to steps do |
| 1766 | + if g.p^.gen # g.gen then Sys.exit(3); end; |
| 1767 | + s := s + g.p^.val; |
| 1768 | + g := g.p^.next; |
| 1769 | + end; |
| 1770 | + return s; |
| 1771 | +end; |
| 1772 | +``` |
| 1773 | + |
| 1774 | +The compiler's instruction counts: `valgrind --tool=callgrind raz -I src |
| 1775 | +-I build/src -o /dev/null src/Raz.raz`, the same compiler built twice |
| 1776 | +from `src/`, once with `Scan.State.buf: ^U8` and once with `[]U8`. The |
| 1777 | +five lines changed were the field's type, `grab(n + 1)[0..n + 1]`, |
| 1778 | +`Diag.addFile(path, PTR(cur.buf), n)`, the local `buf` in `next`, and |
| 1779 | +`intern(PTR(buf) + start, p - start)`. The second compiler builds |
| 1780 | +itself. |
| 1781 | + |
| 1782 | +## Appendix 3: the five programs of section 1 |
| 1783 | + |
| 1784 | +``` |
| 1785 | +module SelfAppend; |
| 1786 | +import Buf, Heap, Out; |
| 1787 | + |
| 1788 | +proc main*; |
| 1789 | +var b: Buf.Buf; i: INT; |
| 1790 | +begin |
| 1791 | + Buf.init(b, Heap.heap); |
| 1792 | + for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) |
| 1793 | + Buf.str(b, Buf.bytes(b)); (* doubles it: or should *) |
| 1794 | + Out.str(Buf.bytes(b)[56..80]); Out.ln; |
| 1795 | +end; |
| 1796 | + |
| 1797 | +end SelfAppend. |
| 1798 | +``` |
| 1799 | + |
| 1800 | +Prints `aaaaaaaaaaaaaaaaaaaaaaaa`, status 0: right, by luck. |
| 1801 | + |
| 1802 | +``` |
| 1803 | +module Stale; |
| 1804 | +import Vec := Vec(INT), Heap, Out; |
| 1805 | + |
| 1806 | +proc main*; |
| 1807 | +var v: Vec.Vec; first: []INT; i: INT; p: ^INT; |
| 1808 | +begin |
| 1809 | + Vec.init(v, Heap.heap); |
| 1810 | + for i := 1 to 16 do Vec.push(v, i); end; |
| 1811 | + first := Vec.all(v); (* good until v next grows *) |
| 1812 | + p := Vec.add(v); (* grows: first now points at freed memory *) |
| 1813 | + p^ := 99; |
| 1814 | + for i := 0 to 15 do Vec.push(v, 1000 + i); end; (* grows again: p is stale *) |
| 1815 | + p^ := -1; (* writes into a block the heap has taken back *) |
| 1816 | + Out.int(first[0]); Out.str(" "); Out.int(first[1]); Out.ln; |
| 1817 | +end; |
| 1818 | + |
| 1819 | +end Stale. |
| 1820 | +``` |
| 1821 | + |
| 1822 | +Prints `1 2`, status 0: it read and wrote freed memory, and looks right. |
| 1823 | + |
| 1824 | +``` |
| 1825 | +module Escape; |
| 1826 | +import Out; |
| 1827 | + |
| 1828 | +type Hex = [16]U8; |
| 1829 | + |
| 1830 | +proc head(var h: Hex): []U8; |
| 1831 | +begin |
| 1832 | + return h[0..8]; (* allowed: h is the caller's *) |
| 1833 | +end; |
| 1834 | + |
| 1835 | +proc short: []U8; |
| 1836 | +var h: Hex; i: INT; |
| 1837 | +begin |
| 1838 | + for i := 0 to 15 do h[i] := 'x'; end; |
| 1839 | + return head(h); (* a slice of short's frame: not caught *) |
| 1840 | +end; |
| 1841 | + |
| 1842 | +proc noise; |
| 1843 | +var junk: [64]U8; i: INT; |
| 1844 | +begin |
| 1845 | + for i := 0 to 63 do junk[i] := '#'; end; |
| 1846 | +end; |
| 1847 | + |
| 1848 | +proc main*; |
| 1849 | +var s: []U8; |
| 1850 | +begin |
| 1851 | + s := short(); |
| 1852 | + noise; |
| 1853 | + Out.str(s); Out.ln; |
| 1854 | +end; |
| 1855 | + |
| 1856 | +end Escape. |
| 1857 | +``` |
| 1858 | + |
| 1859 | +Prints `########`, status 0: `noise`'s bytes, read through a slice of |
| 1860 | +a dead frame. |
| 1861 | + |
| 1862 | +``` |
| 1863 | +module Kept; |
| 1864 | +import Names := Map([]U8, INT, Str.hash, Str.eq), Str, Heap, Out; |
| 1865 | + |
| 1866 | +var table: Names.Map; |
| 1867 | + |
| 1868 | +proc remember(n: INT); |
| 1869 | +var buf: [8]U8; |
| 1870 | +begin |
| 1871 | + buf := "name-000"; |
| 1872 | + buf[7] := U8('0' + n); |
| 1873 | + _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) |
| 1874 | +end; |
| 1875 | + |
| 1876 | +proc main*; |
| 1877 | +var v: INT; ok: BOOL; |
| 1878 | +begin |
| 1879 | + Names.init(table, Heap.heap); |
| 1880 | + remember(1); |
| 1881 | + remember(2); |
| 1882 | + v, ok := Names.get(table, "name-001"); |
| 1883 | + Out.str("name-001: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; |
| 1884 | + v, ok := Names.get(table, "name-002"); |
| 1885 | + Out.str("name-002: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; |
| 1886 | +end; |
| 1887 | + |
| 1888 | +end Kept. |
| 1889 | +``` |
| 1890 | + |
| 1891 | +Prints `name-001: missing` and `name-002: missing`, status 0. |
| 1892 | + |
| 1893 | +``` |
| 1894 | +module Temp; |
| 1895 | +import Out; |
| 1896 | + |
| 1897 | +type Name = [8]U8; |
| 1898 | + |
| 1899 | +proc named(c: U8): Name; |
| 1900 | +var n: Name; |
| 1901 | +begin |
| 1902 | + n := "name-..."; n[7] := c; |
| 1903 | + return n; |
| 1904 | +end; |
| 1905 | + |
| 1906 | +proc main*; |
| 1907 | +var a, b: []U8; |
| 1908 | +begin |
| 1909 | + a := named('a')[0..8]; (* the array lives to the end of the statement *) |
| 1910 | + b := named('b')[0..8]; |
| 1911 | + Out.str(a); Out.str(" "); Out.str(b); Out.ln; |
| 1912 | +end; |
| 1913 | + |
| 1914 | +end Temp. |
| 1915 | +``` |
| 1916 | + |
| 1917 | +Prints `name-..b`, a space and eight bytes of junk, status 0. |