| | @@ -1,4170 +0,0 @@ |
| 1 | | -# MEM_PROPOSAL: a memory-safe raz |
| 2 | | - |
| 3 | | -**Status.** A proposal, drafted 2026-10-17. Reviewed whole by the owner on 2026-10-26: `PLAN.md` §2 says what goes in (F.1, `[]const T`, G, E.4, `Task`, `Guarded`, the fence as `import SYSTEM`) and what is left out (B, C, D, the rest of E). |
| 4 | | -Nothing in it is built. Four adversarial reviews, made the same day, |
| 5 | | -are appendices 4 to 7. They find real holes in the guarantee |
| 6 | | -(appendix 4), wrong and imprecise claims about other languages and |
| 7 | | -hardware (5), wrong counts and unsupported benchmark conclusions (6), |
| 8 | | -and pain in real code that sections 14 and 15 understate (7). The body |
| 9 | | -below is as first drafted; where an appendix contradicts it, the |
| 10 | | -appendix stands until the body is revised. It assumes that anything may change: the |
| 11 | | -language, the library, the compiler, and the programs written for |
| 12 | | -them. It builds on two entries of `PROPOSALS.md`, "Less that is |
| 13 | | -undefined" and part 3 of "What a call does with its arguments" (`ret` |
| 14 | | -and `keep`), and goes further than either: it puts them together into |
| 15 | | -one promise, closes the holes they leave open, and counts the cost. |
| 16 | | - |
| 17 | | -**In one paragraph.** Raz checks where memory is (an index against a |
| 18 | | -length, `nil`, zeroed variables) but not when it is still there, and |
| 19 | | -anything that can break memory may stand in any module. This proposal |
| 20 | | -splits modules in two. An `unsafe;` module may do what raz allows today. |
| 21 | | -Every other module is safe: the compiler holds it to rules under which |
| 22 | | -it can't read or write memory that isn't a live variable of the right |
| 23 | | -type. The rules are four: |
| 24 | | - |
| 25 | | -1. Pointer arithmetic, casts, `ADR`, C and code procedures go behind |
| 26 | | - `unsafe;`. |
| 27 | | -2. A slice or pointer *lent* by a variable can't outlive that |
| 28 | | - variable. Most of this is checked when compiling, and it takes |
| 29 | | - PROPOSALS' `ret` and `keep`. |
| 30 | | -3. A container that hands out slices of its memory *counts* them, |
| 31 | | - and won't free a block while one is held. |
| 32 | | -4. Safe code doesn't free heap memory by hand. It keeps that memory |
| 33 | | - for the life of the program, or holds it in a container or a |
| 34 | | - `Pool` that frees it. |
| 35 | | - |
| 36 | | -The library's own unsafe modules are trusted to keep the promise, as |
| 37 | | -a safe program is trusted to keep its logic. The cost, measured below: |
| 38 | | - |
| 39 | | -- **Programs:** nothing for code that keeps to slices and records. 1.5 |
| 40 | | - to 2 times for chasing a linked structure through checked handles |
| 41 | | - instead of raw pointers, where a program chooses handles. |
| 42 | | -- **Compiler:** about 5% more instructions, if its scanner checks its |
| 43 | | - buffer instead of reading it through a pointer. |
| 44 | | -- **Ergonomics:** a record can't keep a slice into a buffer that |
| 45 | | - belongs to someone else. |
| 46 | | - |
| 47 | | ---- |
| 48 | | - |
| 49 | | -## Contents |
| 50 | | - |
| 51 | | -1. Motivation |
| 52 | | -2. What the code we have does: a survey |
| 53 | | -3. The guarantee |
| 54 | | -4. The design, in brief |
| 55 | | -5. Part A: the fence, `unsafe;` |
| 56 | | -6. Part B: lending, `ret` and `keep` |
| 57 | | -7. Part C: owners that count what they lend |
| 58 | | -8. Part D: the heap without `free` |
| 59 | | -9. Part E: threads |
| 60 | | -10. Part F: the small mends |
| 61 | | -11. Part G: a debugging heap |
| 62 | | -12. Raz beside other languages |
| 63 | | -13. Performance |
| 64 | | -14. Ergonomics |
| 65 | | -15. What breaks |
| 66 | | -16. Changes to the report |
| 67 | | -17. Changes to the library |
| 68 | | -18. Changes to the compiler |
| 69 | | -19. Alternatives considered |
| 70 | | -20. Order of work |
| 71 | | -21. Open questions |
| 72 | | -- Appendix 1: the survey's numbers |
| 73 | | -- Appendix 2: the benchmarks |
| 74 | | -- Appendix 3: the five programs of section 1 |
| 75 | | -- Appendix 4: adversarial review, soundness |
| 76 | | -- Appendix 5: adversarial review, claims about other languages and hardware |
| 77 | | -- Appendix 6: adversarial review, the proposal's numbers and samples |
| 78 | | -- Appendix 7: adversarial review, porting real code |
| 79 | | - |
| 80 | | ---- |
| 81 | | - |
| 82 | | -## 1. Motivation |
| 83 | | - |
| 84 | | -### 1.1 What raz promises today |
| 85 | | - |
| 86 | | -| Check | Today | |
| 87 | | -|---|---| |
| 88 | | -| Index and slice bounds | checked, unless `check off;` | |
| 89 | | -| `nil` dereference, `nil` procedure | stops the program | |
| 90 | | -| Division by zero, `low / -1` | stops the program | |
| 91 | | -| Stack overflow | stops the program | |
| 92 | | -| Variables start at zero | always | |
| 93 | | -| Integer overflow | wraps, defined | |
| 94 | | -| A variant's fields read only through `match` | always | |
| 95 | | -| A view's bytes stay inside its variable | checked | |
| 96 | | -| Integer to enumeration conversion | checked | |
| 97 | | -| A slice returned from its own frame | an error, but only for a direct `return` (7.3) | |
| 98 | | -| Use after free, after `Arena.reset`, after a `Vec` grows | nothing | |
| 99 | | -| A slice kept past its frame by any other route | nothing | |
| 100 | | -| A slice of a call's array kept past its statement | nothing | |
| 101 | | -| Pointer arithmetic, `p[i]` | unchecked, anywhere | |
| 102 | | -| Integer to pointer, pointer to pointer | allowed, anywhere | |
| 103 | | -| `ADR` of a local, kept | allowed, anywhere | |
| 104 | | -| C, code procedures, `SYSCALL` | allowed, anywhere | |
| 105 | | -| A race tearing a slice or a variant | the report says nothing becomes undefined (7.6); it does | |
| 106 | | - |
| 107 | | -This is close to Oberon's or Pascal's promise, without a garbage |
| 108 | | -collector behind it. Spatial safety (indexes, lengths, `nil`) is |
| 109 | | -mostly there. Temporal safety (whether memory is still there) isn't |
| 110 | | -there at all. Nothing marks the code that can break memory, so any |
| 111 | | -module may. |
| 112 | | - |
| 113 | | -### 1.2 Five programs that compile with no warning |
| 114 | | - |
| 115 | | -Each is complete, compiled by today's compiler with no warning, and run. |
| 116 | | -The full texts are in appendix 3. |
| 117 | | - |
| 118 | | -**Appending a buffer to itself.** |
| 119 | | - |
| 120 | | -``` |
| 121 | | -Buf.init(b, Heap.heap); |
| 122 | | -for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) |
| 123 | | -Buf.str(b, Buf.bytes(b)); (* doubles it, or should *) |
| 124 | | -``` |
| 125 | | - |
| 126 | | -`Buf.str` grows `b` first: it allocates a new block, copies the bytes |
| 127 | | -and frees the old block. It then copies from `s`, which still points at |
| 128 | | -the old block. It prints 24 `a`s, as it should, because the heap didn't |
| 129 | | -reuse the freed block in time. With another allocator, or another |
| 130 | | -thread using the heap, it prints garbage. Nothing tells the programmer |
| 131 | | -that this line is wrong. A test passes. |
| 132 | | - |
| 133 | | -**A slice kept across a `Vec`'s growth.** |
| 134 | | - |
| 135 | | -``` |
| 136 | | -first := Vec.all(v); (* good until v next grows *) |
| 137 | | -p := Vec.add(v); (* grows: first now points at freed memory *) |
| 138 | | -... |
| 139 | | -p^ := -1; (* after another growth: writes into a block the heap took back *) |
| 140 | | -Out.int(first[0]); (* prints 1, as if nothing were wrong *) |
| 141 | | -``` |
| 142 | | - |
| 143 | | -The library's comments say "good until the array next grows". The |
| 144 | | -compiler doesn't know that comment. |
| 145 | | - |
| 146 | | -**A slice of the frame, through a call.** |
| 147 | | - |
| 148 | | -``` |
| 149 | | -proc head(var h: Hex): []U8; begin return h[0..8]; end; (* allowed *) |
| 150 | | -proc short: []U8; var h: Hex; |
| 151 | | -begin ... return head(h); end; (* not caught *) |
| 152 | | -``` |
| 153 | | - |
| 154 | | -The caller prints `########`, the bytes the next call left in the dead |
| 155 | | -frame. 7.3 catches `return h[0..8]` in `short` but not the same slice |
| 156 | | -handed back through `head`. |
| 157 | | - |
| 158 | | -**A map keeping a slice of a frame.** |
| 159 | | - |
| 160 | | -``` |
| 161 | | -proc remember(n: INT); |
| 162 | | -var buf: [8]U8; |
| 163 | | -begin |
| 164 | | - buf := "name-000"; buf[7] := U8('0' + n); |
| 165 | | - _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) |
| 166 | | -end; |
| 167 | | -``` |
| 168 | | - |
| 169 | | -After `remember(1); remember(2);` both `name-001` and `name-002` are |
| 170 | | -"missing": the map's keys point at a frame that is gone. Every caller |
| 171 | | -of `Map([]U8, ...).put` must know, from the documentation alone, that |
| 172 | | -the key is kept. |
| 173 | | - |
| 174 | | -**A slice of a call's array, kept.** |
| 175 | | - |
| 176 | | -``` |
| 177 | | -a := named('a')[0..8]; |
| 178 | | -b := named('b')[0..8]; |
| 179 | | -Out.str(a); Out.str(" "); Out.str(b); |
| 180 | | -``` |
| 181 | | - |
| 182 | | -It prints `name-..b ^A^@^@^@^@^@^@^@`. Both arrays used the same |
| 183 | | -temporary, so `a` shows `b`'s bytes and `b` shows whatever came after. |
| 184 | | -Section 8 says this is undefined, and nothing catches it. |
| 185 | | - |
| 186 | | -None of these is exotic. Three are what the library's own |
| 187 | | -documentation warns of; two are what 7.3 and 8 warn of. Each runs to |
| 188 | | -the end with status 0. |
| 189 | | - |
| 190 | | -### 1.3 Why it matters for raz in particular |
| 191 | | - |
| 192 | | -- **Raz's audience.** CLAUDE.md asks that the compiler be "a model of |
| 193 | | - plain code that a beginner can follow". A beginner can't follow a |
| 194 | | - rule that lives only in a comment ("good until it next grows"). A |
| 195 | | - language that checks every index and then lets a slice outlive its |
| 196 | | - buffer teaches a false sense of safety: the checks cover the easy |
| 197 | | - half. |
| 198 | | -- **Undefined behaviour passes tests.** In four of the five programs |
| 199 | | - above the output is plausible, or right. The heap's free lists keep |
| 200 | | - freed bytes for a while; a dead frame keeps its bytes until the |
| 201 | | - next call. A program can carry such a bug for years. |
| 202 | | -- **No fence means no audit.** Today, to know whether a program can |
| 203 | | - corrupt memory, you read all of it. With a fence, you read the |
| 204 | | - modules that say `unsafe;`, and `grep` finds them. The survey |
| 205 | | - (section 2) shows how few modules would need to say it. |
| 206 | | -- **The library is growing.** Each container added (`Vec`, `Map`, `Buf`, |
| 207 | | - `List`, and `Svec` in sauce) adds rules of the "good until" kind. Those |
| 208 | | - rules should be the compiler's to check. |
| 209 | | -- **Threads.** `Thread` and `Lock` are in the library, and rnet and |
| 210 | | - rsqlite use them. A race on a slice reaches any memory today, though |
| 211 | | - 7.6 promises it can't. |
| 212 | | - |
| 213 | | ---- |
| 214 | | - |
| 215 | | -## 2. What the code we have does: a survey |
| 216 | | - |
| 217 | | -### 2.1 How it was measured |
| 218 | | - |
| 219 | | -For an exact count, not an estimate from `grep`, the compiler itself |
| 220 | | -was changed in a scratch copy. It printed one line for each operation |
| 221 | | -this proposal would fence, where it compiled one: a pointer indexed or |
| 222 | | -sliced, pointer arithmetic, a conversion to or from a pointer, `ADR`, |
| 223 | | -`PTR`, `SYSCALL`, a view, `NEW` and every dereference. Each program |
| 224 | | -and each library module's test was compiled with it. The places are |
| 225 | | -counted once each, whatever number of programs compiled them. The |
| 226 | | -hooks stand where most of the fence's checks would go (section 18). |
| 227 | | - |
| 228 | | -Code surveyed: |
| 229 | | - |
| 230 | | -| Code | Version | Lines | How | |
| 231 | | -|---|---|---|---| |
| 232 | | -| raz `src/` (the compiler) | main | 14,323 | compiler-counted | |
| 233 | | -| raz `lib/` | main | 10,291 | compiler-counted | |
| 234 | | -| raz `tools/`, `examples/`, `test/libc` | main | 2,207+ | compiler-counted | |
| 235 | | -| rnet (HTTP, DNS, TLS seams) | raz 0.15.0 | 5,111 | compiler-counted, with 0.15.0's `lib/` | |
| 236 | | -| rjson | raz 0.15.0 | 1,882 | compiler-counted, with 0.15.0's `lib/` | |
| 237 | | -| rflate (inflate) | raz 0.15.0 | 1,319 | compiler-counted, with 0.15.0's `lib/` | |
| 238 | | -| rsqlite (SQLite over C) | raz 0.18.0 | 705 | compiler-counted, with 0.18.0's `lib/` | |
| 239 | | -| rterm | raz 0.15.0 | 101 | compiler-counted | |
| 240 | | -| rmacs (an editor, archived) | raz v0.5.0+7 | 4,932 | `grep`: written before `INT`, today's compiler refuses it | |
| 241 | | -| ravite (an editor) | raz v0.5.0+7 | 2,460 | `grep`, as rmacs | |
| 242 | | -| rlX11 (X11 over a socket) | raz v0.3.0+52 | 7,026 | `grep`, as rmacs | |
| 243 | | - |
| 244 | | -About 50,000 lines in all. Code written for an older raz was compiled |
| 245 | | -by today's compiler against the library of the version it was written |
| 246 | | -for. The full tables are in appendix 1. |
| 247 | | - |
| 248 | | -### 2.2 What it found |
| 249 | | - |
| 250 | | -**Nobody uses `check off;`.** Not one module in 50,000 lines. Bounds |
| 251 | | -checks are cheap enough that no one has wanted them off. |
| 252 | | - |
| 253 | | -**Almost every `ADR` is an argument to the library.** Of rnet's 572 |
| 254 | | -`ADR`s, 571 are arguments, and so are 556 of rmacs's 560 and all 77 of |
| 255 | | -rjson's. They are the library's old pointer parameters, which report |
| 256 | | -2026-10.33 made `var` and `const`; code written for v0.19.0 and later |
| 257 | | -has lost them already. `src/`, which has been ported, keeps 27, and |
| 258 | | -none of them needs to be an `ADR`: |
| 259 | | - |
| 260 | | -| What `src/` does with `ADR` and pointer casts | Sites | The safe form | |
| 261 | | -|---|---|---| |
| 262 | | -| a grown array: `^Chunk(Scan.regrab(^U8(chunks), ...))` | 35 | `Vec(Chunk)`, or a slice and `Mem`'s growth, in one trusted module | |
| 263 | | -| a real's bits: `p := ^F64(ADR(x.val))` | 6 | a view, `x.val.(F64)`, safe today | |
| 264 | | -| a slice passed as two words: `Scan.intern(ADR(s[0]), LEN(s))` | 7 | `Scan.intern(s)`: a slice parameter | |
| 265 | | -| out-parameters: `isReg(w, ADR(r), ADR(size))` | 5 | `var r, size` | |
| 266 | | -| a pointer to a local record: `curLoop := ADR(lp)` | 1 | a field index, or `var` | |
| 267 | | -| `SYSCALL(4, ...)`: `stat` | 1 | `Sys.info` | |
| 268 | | - |
| 269 | | -**Pointer indexing is buffers.** `src/` indexes a pointer 277 times |
| 270 | | -and slices one 30 times, nearly all in six modules: `Scan` (76), `Link` |
| 271 | | -(63), `Chunk` (53), `X64` (23), `Elf` (17) and `Diag` (15). Each keeps |
| 272 | | -a byte or record buffer that it grows by hand: `text[pc + i] := ...`, |
| 273 | | -`lp[lpLen] := ...`, `buf[at + i] := ...`. That is `Vec` and `Buf` |
| 274 | | -written out again, for speed, without checks. The scanner reads its |
| 275 | | -source through `buf: ^U8`, past the end to a sentinel zero. |
| 276 | | - |
| 277 | | -**Dereferences are everywhere and harmless.** 1,015 in `src/` (`Parse` |
| 278 | | -517, `Item` 256, `Sym` 106): `o^.typ`, `t^.base`. Every one is a pointer |
| 279 | | -from `NEW` on the heap, which the compiler never frees. Under part D |
| 280 | | -they stay as they are, unchecked and free of cost. |
| 281 | | - |
| 282 | | -**The library is where the unsafe code is.** `Sys` (287 operations, |
| 283 | | -129 of them `SYSCALL`), `Rt` (111), `Thread` (33), `Heap` (16) and `Map` |
| 284 | | -(19). It is the code that should be trusted and read twice. `Math`, |
| 285 | | -`Out`, `Sort` and `Width` have none; `Str`, `Fmt`, `Opt`, `Files` and |
| 286 | | -`Lock` have two to five each, all of them avoidable. |
| 287 | | - |
| 288 | | -**Slices held from containers.** 35 places assign `Buf.bytes`, |
| 289 | | -`Vec.all` or `Windows.all` to a variable and use it over several |
| 290 | | -statements; the rest pass it straight on. Some places store one in a |
| 291 | | -record: |
| 292 | | - |
| 293 | | -``` |
| 294 | | -m^.body := Buf.bytes(ADR(m^.data)); (* rnet Http.readWhole *) |
| 295 | | -m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}; (* l is a slice of m^.head's bytes *) |
| 296 | | -res^.body := Buf.bytes(ADR(text)); (* rnet's test server: a module Buf, reset per request *) |
| 297 | | -``` |
| 298 | | - |
| 299 | | -`Http.Message` holds slices into two buffers of its own. It is right, |
| 300 | | -as long as nobody grows `m^.head` after the headers are read and |
| 301 | | -nobody uses the headers after `Http.done`. The compiler knows neither |
| 302 | | -condition. Section 14 shows what this pattern costs under the |
| 303 | | -proposal. |
| 304 | | - |
| 305 | | -**Records that hold slices** (each one is a place where something must |
| 306 | | -decide how long the slice lives): `src/` 10, `lib/` 22, rnet 12, rjson 8, |
| 307 | | -ravite 5, rmacs 4, `tools/` 4, rlX11 3, rflate 2, rsqlite 1. |
| 308 | | - |
| 309 | | -**Threads are rare.** Two of the eight other repositories spawn |
| 310 | | -threads (rnet's server, rsqlite's test). `src/`, the tools and the |
| 311 | | -editors have none. |
| 312 | | - |
| 313 | | -**Freeing is rare too.** `Mem.free`, `Heap`'s `free` or `Str.free` by |
| 314 | | -hand: `src/` 7 (all in grown arrays), rmacs 9, rjson 6, ravite 2, |
| 315 | | -rlX11 1, rnet, rflate and rsqlite 0. Programs free memory through |
| 316 | | -`done` on a container (rnet 30, rmacs 16) far more than by hand: 54 |
| 317 | | -`done`s to 26 frees, outside the library. |
| 318 | | - |
| 319 | | -### 2.3 What the survey says about the design |
| 320 | | - |
| 321 | | -1. A fence costs little. Outside the library and the compiler's |
| 322 | | - buffers, the operations it fences are almost all `ADR`s that the |
| 323 | | - v0.19.0 library already removed. In `src/`, the fenced |
| 324 | | - operations are buffers and small habits, each with a safe form. |
| 325 | | -2. Leaving pointers unchecked costs nothing as long as nothing frees |
| 326 | | - them. The compiler's 1,015 dereferences are of heap memory that |
| 327 | | - lives as long as the program. Making `free` unsafe, and giving |
| 328 | | - containers the job of freeing (part D), keeps those dereferences |
| 329 | | - free of cost. |
| 330 | | -3. The hard case is a slice of a container's memory held while the |
| 331 | | - container changes. It is found in rmacs, ravite, rnet and the |
| 332 | | - library itself (`Fmt`, `Opt`), and nothing today checks it. Part C |
| 333 | | - is aimed at it. |
| 334 | | -4. Threads can wait for a weaker rule than Rust's (part E), since few |
| 335 | | - programs use them. |
| 336 | | - |
| 337 | | ---- |
| 338 | | - |
| 339 | | -## 3. The guarantee |
| 340 | | - |
| 341 | | -The proposal puts one paragraph into section 10 of the report, in |
| 342 | | -place of today's list of what isn't defined: |
| 343 | | - |
| 344 | | -> **The guarantee.** A program is *safe* if none of its modules says |
| 345 | | -> `unsafe;`, the library's aside, and its threads race (7.6) only on |
| 346 | | -> variables of a basic, pointer, procedure or slice type. A safe |
| 347 | | -> program reads and writes only variables that exist, each as a value |
| 348 | | -> of its own type, and calls only procedures. It does what this report |
| 349 | | -> says, or stops with status 2 and says where and why. The library's |
| 350 | | -> unsafe modules are trusted to keep this promise for every use a safe |
| 351 | | -> program can make of what they export. |
| 352 | | - |
| 353 | | -What the guarantee covers: |
| 354 | | - |
| 355 | | -- **Spatial:** no read or write outside a variable: indexes and views |
| 356 | | - checked, as now; pointers in safe code made only by `NEW` and by the |
| 357 | | - library, never by arithmetic or conversion. |
| 358 | | -- **Temporal:** no read or write of memory that has been freed or |
| 359 | | - reused: slices and pointers lent by a frame or a container can't |
| 360 | | - outlive it (B, C); the heap is never freed under a pointer safe code |
| 361 | | - holds (D). |
| 362 | | -- **Type:** no value read as another type: views of pointers and |
| 363 | | - conversions to pointers fenced; variants only through `match`; enums |
| 364 | | - and `BOOL` only from their values. |
| 365 | | -- **Initialization:** as now, every variable starts at zero. |
| 366 | | -- **Races:** within the bounds above (part E). |
| 367 | | - |
| 368 | | -What it doesn't cover, on purpose: |
| 369 | | - |
| 370 | | -- **Leaks.** A safe program may keep memory it no longer needs, as a |
| 371 | | - garbage-collected one may. |
| 372 | | -- **Running out of memory or stack.** These stop the program, as now. |
| 373 | | -- **Logic.** A stale handle into a `Pool` stops the program; it doesn't |
| 374 | | - fix the bug. A slice of a buffer that was cleared shows the buffer's |
| 375 | | - new contents, safely. |
| 376 | | -- **Deadlock**, and a race on a whole record, variant or container. |
| 377 | | - The second is undefined, as in Go, and part E says why. |
| 378 | | -- **The unsafe modules themselves.** They are trusted, as `unsafe` |
| 379 | | - code is in Rust and `UNSAFE MODULE`s are in Modula-3. |
| 380 | | - |
| 381 | | -The guarantee is stated once and is the same on every target. |
| 382 | | -Appendix A keeps only how it is carried out: whether the machine or |
| 383 | | -the code catches a fault, and how a slice is read in one access. |
| 384 | | - |
| 385 | | ---- |
| 386 | | - |
| 387 | | -## 4. The design, in brief |
| 388 | | - |
| 389 | | -| Part | What it does | Checked | Cost at run time | |
| 390 | | -|---|---|---|---| |
| 391 | | -| 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 | |
| 392 | | -| 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 | |
| 393 | | -| 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 | |
| 394 | | -| 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 | |
| 395 | | -| 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 | |
| 396 | | -| 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 | |
| 397 | | -| G. Debugging | `Heap` in a mode that poisons and holds back freed blocks | at run time, when chosen | when chosen | |
| 398 | | - |
| 399 | | -A program that is safe today, which is to say every program that |
| 400 | | -keeps to slices, records and the library, mostly stays as it is. Section 15 counts |
| 401 | | -what breaks. |
| 402 | | - |
| 403 | | ---- |
| 404 | | - |
| 405 | | -## 5. Part A: the fence, `unsafe;` |
| 406 | | - |
| 407 | | -### 5.1 The rule |
| 408 | | - |
| 409 | | -A module that says `unsafe;`, after its imports, links and `check` |
| 410 | | -line, may do everything raz allows today. A module that doesn't is |
| 411 | | -*safe*, and it is an error for it to do any of the following: |
| 412 | | - |
| 413 | | -| Operation | Why it's fenced | |
| 414 | | -|---|---| |
| 415 | | -| `ADR(x)` | a pointer to anything, a local included, that outlives nothing | |
| 416 | | -| `p + i`, `p - i`, `p[i]`, `p[lo..hi]` on a pointer | no length to check against | |
| 417 | | -| 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 | |
| 418 | | -| 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 | |
| 419 | | -| `PTR(s)` | the first word of a slice, unchecked | |
| 420 | | -| a view `v.(T)` whose `T` holds a pointer, procedure or slice | makes one from bytes | |
| 421 | | -| writing through a view of a variable that holds a pointer, procedure, slice, variant, enumeration or `BOOL` | changes those bytes behind their type | |
| 422 | | -| `check off;` | indexes unchecked | |
| 423 | | -| `extern`, `link` | C can do anything | |
| 424 | | -| a code procedure, `SYSCALL` | the machine can do anything | |
| 425 | | -| `ARGV()` | a `^^U8` from C; `Files.arg` gives a slice | |
| 426 | | -| a call of an `unsafe proc`, or of a value of an `unsafe proc` type | the procedure says it can break the promise | |
| 427 | | - |
| 428 | | -What stays safe, though it involves pointers: `p^`, `p^.f`, `p^[i]` (an |
| 429 | | -array through a pointer is indexed and checked), `nil`, comparing |
| 430 | | -pointers, `p - q` (an integer), `NEW`, and passing and storing a |
| 431 | | -pointer as any value. A pointer in safe code is only ever `nil`, from |
| 432 | | -`NEW`, or handed out by the library. Part B says how long each one |
| 433 | | -lives. |
| 434 | | - |
| 435 | | -The message names the mending: |
| 436 | | - |
| 437 | | -``` |
| 438 | | -Window.raz:41:13: error: ADR is for unsafe modules |
| 439 | | - 41 | XNextEvent(dpy, ADR(ev)); |
| 440 | | - | ^^^^^^^ |
| 441 | | - help: say "unsafe;" after the module's imports, or pass ev as a var |
| 442 | | -``` |
| 443 | | - |
| 444 | | -### 5.2 Unsafe procedures |
| 445 | | - |
| 446 | | -Some of the library's procedures can break the promise whatever safe |
| 447 | | -code does: `Mem.free`, `Heap`'s `free`, `Str.free`, `Sys.mmap`, |
| 448 | | -`Sys.munmap`, `Thread.spawn` with its `^U8`. They are declared |
| 449 | | - |
| 450 | | -``` |
| 451 | | -unsafe proc free*(a: ^Allocator; p: ^U8); |
| 452 | | -``` |
| 453 | | - |
| 454 | | -and only an unsafe module may call one. A procedure type may say |
| 455 | | -`unsafe proc(...)`; a value of that type may be called only from an |
| 456 | | -unsafe module, and a safe procedure may stand where an unsafe type is |
| 457 | | -wanted, not the other way. `Mem.Allocator`'s two fields are of unsafe |
| 458 | | -types: safe code may pass an allocator to the library but can't call |
| 459 | | -it. |
| 460 | | - |
| 461 | | -`unsafe`, like `static` in `link static;`, is a word only where it |
| 462 | | -stands: before `proc`, and as the module's line. Elsewhere it is a |
| 463 | | -name. |
| 464 | | - |
| 465 | | -### 5.3 The trust |
| 466 | | - |
| 467 | | -A safe module may import an unsafe one. What the unsafe module |
| 468 | | -exports, other than its `unsafe proc`s, it promises safe to use: for |
| 469 | | -any arguments a safe module can make, its procedures keep the |
| 470 | | -guarantee. This is Modula-3's rule for an `UNSAFE MODULE` that |
| 471 | | -implements a safe `INTERFACE`, and Rust's for a safe function built |
| 472 | | -on `unsafe` blocks. What the promise demands of an unsafe module, in |
| 473 | | -the report (section 16): |
| 474 | | - |
| 475 | | -1. What it returns as lasting (part B) lasts: its memory is never |
| 476 | | - freed or reused while the program runs. |
| 477 | | -2. What it returns through `ret` lives no longer than the argument it |
| 478 | | - says. If the argument is an owner, the module doesn't free memory |
| 479 | | - it lent while the owner's `LENDS` count is above zero (part C). |
| 480 | | -3. What it keeps (`keep` parameters) it may hold for as long as it |
| 481 | | - likes; what it doesn't mark `keep`, it doesn't hold past the call. |
| 482 | | -4. Its exported types hide whatever a safe module could misuse: a |
| 483 | | - container's pointer fields aren't exported. |
| 484 | | -5. Its procedures given to other threads, or shared by them, are safe |
| 485 | | - to call from several threads at once, or say otherwise. |
| 486 | | - |
| 487 | | -So `grep -l '^unsafe;'` lists every module whose bugs could corrupt |
| 488 | | -memory, and the library's are among them, as they are today. |
| 489 | | - |
| 490 | | -### 5.4 Which modules would say it |
| 491 | | - |
| 492 | | -From the survey, as the code stands: |
| 493 | | - |
| 494 | | -- **The library:** `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, |
| 495 | | - `Thread`, `Lock`, `C`, `CAbi`, and the containers `Buf`, `Vec`, `Map`, |
| 496 | | - `List`, which hold raw blocks and grow them. `Str`, `Fmt`, `Opt` and |
| 497 | | - `Files` can drop their two to five fenced operations and be safe. |
| 498 | | - `Math`, `Out`, `Sort` and `Width` are safe already. |
| 499 | | -- **`src/`:** all eleven modules today. Mended as section 2.2's |
| 500 | | - table says, with the six buffer modules' grown arrays made `Vec`s or |
| 501 | | - slices, `src/` keeps one unsafe module: `Scan`, for its allocator |
| 502 | | - (`grab`) and, if it keeps it, the pointer through its source buffer. |
| 503 | | - `Elf` writes the executable through `Sys.write` and needs none. |
| 504 | | -- **`examples/`:** `Args` (it reads `ARGV()`, which `Files.arg` does |
| 505 | | - for it), `Cpu` (a code procedure), `Pthreads`, `Printf`, `Window` |
| 506 | | - (C), `Volatile` (a device's address), `Sh` and `Workers` (`ADR` at |
| 507 | | - calls: mended by `var`). Five stay unsafe (`Cpu`, `Pthreads`, |
| 508 | | - `Printf`, `Window`, `Volatile`), as an example of each kind of |
| 509 | | - unsafety should be. |
| 510 | | -- **Elsewhere:** rsqlite's `Sqlite` (C); rlX11's three casts look like |
| 511 | | - work for views; rnet needs it only to keep `Http.Message` as it is |
| 512 | | - (section 14). |
| 513 | | - |
| 514 | | ---- |
| 515 | | - |
| 516 | | -## 6. Part B: lending, `ret` and `keep` |
| 517 | | - |
| 518 | | -Part B is PROPOSALS' part 3 (`ret`, `keep`) with two changes. Pointers |
| 519 | | -are followed, not only slices, and a third kind of lender, the owner, |
| 520 | | -comes from part C. What is said there of "frame-bound", "outliving the |
| 521 | | -call" and the checks stands. This section gives the rules in the |
| 522 | | -terms the guarantee needs. |
| 523 | | - |
| 524 | | -### 6.1 Lasting and lent |
| 525 | | - |
| 526 | | -Every value that holds a slice or a pointer (a *reference*) is, for |
| 527 | | -the compiler, either: |
| 528 | | - |
| 529 | | -- **lasting:** it points at memory that lives to the end of the |
| 530 | | - program: `nil`, `[]`, a string constant, a module variable or a part |
| 531 | | - of one, memory from `NEW` on the heap (part D), and what the library |
| 532 | | - returns as lasting (a result with no `ret` parameter); |
| 533 | | -- **lent** by one or more *lenders* of the procedure it is in: |
| 534 | | - - **the frame**: a slice of a local array, of a value parameter's |
| 535 | | - array, or of an array literal; an array a call returned (part F); |
| 536 | | - - **a parameter `p`**: a slice parameter's value, what a `var` or |
| 537 | | - `const` parameter's arrays hold or its references point at; and |
| 538 | | - the parameter's own variable, for `var` and `const`; |
| 539 | | - - **an owner `o`** (part C): what `o` lent through a `ret`. |
| 540 | | - |
| 541 | | -A value made from others is lent by every lender of its parts: a slice, |
| 542 | | -a field, an element of `x`; a record, variant or array literal of |
| 543 | | -parts; a call's result, from its arguments for `ret` parameters. A |
| 544 | | -local variable holding references is lent by everything assigned to |
| 545 | | -it anywhere in its procedure. That is PROPOSALS' rule, and the reason |
| 546 | | -some checks wait for the procedure's `end`. |
| 547 | | - |
| 548 | | -### 6.2 What may be done with a lent reference |
| 549 | | - |
| 550 | | -A lent reference may be: |
| 551 | | - |
| 552 | | -- read, indexed, sliced, compared, and passed to any parameter not |
| 553 | | - marked `keep`; |
| 554 | | -- held in a local variable, or in a field or element of one (owner-lent |
| 555 | | - values only in a local of slice or pointer type: see 7.3); |
| 556 | | -- returned, if each of its lenders is a parameter marked `ret`. |
| 557 | | - |
| 558 | | -It may not be: |
| 559 | | - |
| 560 | | -- stored in a module variable, through a pointer (`p^.f := s`), or into |
| 561 | | - a `var` parameter or part of one; |
| 562 | | -- given to a `keep` parameter; |
| 563 | | -- returned while lent by the frame, an owner, or a parameter not |
| 564 | | - marked `ret`; |
| 565 | | -- given to `Task.spawn` (part E). |
| 566 | | - |
| 567 | | -The rules are PROPOSALS' checks 1 to 3, with "frame-bound" read as |
| 568 | | -"lent". Every check needs only the procedure in hand and the headings |
| 569 | | -of what it calls, so a one-pass compiler can make it: the checks on a |
| 570 | | -local wait for the procedure's `end`, as PROPOSALS describes. |
| 571 | | - |
| 572 | | -### 6.3 Marks |
| 573 | | - |
| 574 | | -``` |
| 575 | | -proc trim*(ret s: []U8): []U8; (* the result may point where s does *) |
| 576 | | -proc bytes*(ret const b: Buf): []U8; (* the result is lent by b, an owner *) |
| 577 | | -proc put*(var m: Map; keep k: K; keep v: V): BOOL; (* k and v must last *) |
| 578 | | -``` |
| 579 | | - |
| 580 | | -`ret` and `keep` stand before `var` or `const`, and are words only |
| 581 | | -there. A mark that lends nothing (`keep n: INT`) is allowed, so a |
| 582 | | -generic module can mark `keep v: T` for every `T`. PROPOSALS covers |
| 583 | | -procedure values, generics, `extern` (no marks; unsafe anyway) and |
| 584 | | -code procedures (trusted; unsafe anyway). |
| 585 | | - |
| 586 | | -Marks at the call (PROPOSALS' part 1) are not part of this proposal: |
| 587 | | -the checks hold whether or not the call repeats them. |
| 588 | | - |
| 589 | | -### 6.4 Examples |
| 590 | | - |
| 591 | | -``` |
| 592 | | -proc greet: []U8; |
| 593 | | -var line: [80]U8; n: INT; |
| 594 | | -begin |
| 595 | | - n := Sys.read(Sys.stdin, line); |
| 596 | | - Out.str(Str.trim(line[0..n])); (* fine: lent by the frame, used here *) |
| 597 | | - return Str.trim(line[0..n]); (* error: lent by the frame *) |
| 598 | | -end; |
| 599 | | - |
| 600 | | -proc first(ret s: []U8): []U8; |
| 601 | | -begin |
| 602 | | - return s[0..1]; (* fine: s is ret *) |
| 603 | | -end; |
| 604 | | - |
| 605 | | -proc remember(n: INT); |
| 606 | | -var buf: [8]U8; k: []U8; ok: BOOL; |
| 607 | | -begin |
| 608 | | - buf := "name-000"; buf[7] := U8('0' + n); |
| 609 | | - _ := Names.put(table, buf[0..8], n); (* error: put keeps k, and this is lent by the frame *) |
| 610 | | - k, ok := Str.copy(Heap.heap, buf[0..8]); (* lasting: a copy on the heap *) |
| 611 | | - if ok then _ := Names.put(table, k, n); end; (* fine *) |
| 612 | | -end; |
| 613 | | -``` |
| 614 | | - |
| 615 | | -The messages: |
| 616 | | - |
| 617 | | -``` |
| 618 | | -Kept.raz:10:30: error: Names.put keeps its key, and buf[0..8] is lent by this call's frame |
| 619 | | - 10 | _ := Names.put(table, buf[0..8], n); |
| 620 | | - | ^^^^^^^^^ |
| 621 | | - help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) |
| 622 | | -``` |
| 623 | | - |
| 624 | | -``` |
| 625 | | -Escape.raz:14:12: error: head(h) is lent by h, a local of short, and can't be returned |
| 626 | | - 14 | return head(h); |
| 627 | | - | ^^^^^^^ |
| 628 | | - help: head's result points into what it is given (ret h); return a copy, or take h as a var parameter of short |
| 629 | | -``` |
| 630 | | - |
| 631 | | -### 6.5 Pointers |
| 632 | | - |
| 633 | | -PROPOSALS' marks follow slices only and leave pointers to the promise |
| 634 | | -of section 10. Here pointers are references too. In a safe module the only |
| 635 | | -pointers are lasting (from `NEW` on the heap, or from the library) or |
| 636 | | -lent by an owner (`Vec.add`, `Pool.at`). `ADR` is fenced, so a safe |
| 637 | | -module can't make a pointer to the frame. A pointer lent by an |
| 638 | | -owner follows the same rules as a slice. |
| 639 | | - |
| 640 | | -### 6.6 What it closes |
| 641 | | - |
| 642 | | -- A slice of the frame returned or stored by any route (today's 7.3 |
| 643 | | - catches one route). |
| 644 | | -- A slice of a parameter's array stored past the call, or returned |
| 645 | | - unmarked. |
| 646 | | -- A map, list or vector keeping a slice that doesn't last. |
| 647 | | -- `Opt.init` keeping a table built on the frame (it becomes `keep |
| 648 | | - table`, and `examples/Sh.raz` passes a constant, as PROPOSALS shows). |
| 649 | | - |
| 650 | | ---- |
| 651 | | - |
| 652 | | -## 7. Part C: owners that count what they lend |
| 653 | | - |
| 654 | | -### 7.1 The problem part B can't solve |
| 655 | | - |
| 656 | | -`Buf.bytes(b)` returns a slice of heap memory, so by PROPOSALS' rule it |
| 657 | | -points "nowhere that ends", and part B would call it lasting. It |
| 658 | | -isn't: the next `Buf.add` may free that memory. The slice is lent by |
| 659 | | -`b`, and how long it stays good depends on what happens to `b`, at run |
| 660 | | -time, often through a pointer: `Buf.bytes(x^.path)`. |
| 661 | | - |
| 662 | | -There are two ways to check that when compiling. One is Rust's: no |
| 663 | | -change to `b` while any slice of it is live, found by liveness and |
| 664 | | -the exclusivity of `&mut`. The other is flow analysis in one pass: |
| 665 | | -mark a slice stale when its lender is passed as `var`, and refuse to |
| 666 | | -read it after that. Both fail raz's limits. Rust's needs lifetimes in |
| 667 | | -types and borrow regions. The one-pass flow analysis can't see a |
| 668 | | -loop's second iteration before it compiles the first: |
| 669 | | - |
| 670 | | -``` |
| 671 | | -s := Buf.bytes(b); |
| 672 | | -while more do |
| 673 | | - Out.str(s); (* compiled before the add below; but the second time round s is stale *) |
| 674 | | - Buf.add(b, c); |
| 675 | | -end; |
| 676 | | -``` |
| 677 | | - |
| 678 | | -and through a pointer every call may change the lender, so every call |
| 679 | | -would make the slice stale, which is false alarms everywhere. |
| 680 | | - |
| 681 | | -So part C checks at run time, as raz checks an index. The cost is an |
| 682 | | -add when a lent slice is taken into a variable and a subtract when the |
| 683 | | -variable lets go of it. |
| 684 | | - |
| 685 | | -### 7.2 Owners |
| 686 | | - |
| 687 | | -A record type with a field of the new built-in type `LENDS` is an |
| 688 | | -*owner*: |
| 689 | | - |
| 690 | | -``` |
| 691 | | -type |
| 692 | | - Buf* = record |
| 693 | | - lends: LENDS; (* how many slices of data are held *) |
| 694 | | - a: ^Mem.Allocator; |
| 695 | | - data: ^U8; |
| 696 | | - len*, cap: INT; |
| 697 | | - end; |
| 698 | | -``` |
| 699 | | - |
| 700 | | -`LENDS` is an `INT` that only the compiler changes: the owner's own |
| 701 | | -module may read it, and nothing may assign it. An owner is lent from |
| 702 | | -only through a `ret` parameter of its type, `var` or `const`: |
| 703 | | - |
| 704 | | -``` |
| 705 | | -proc bytes*(ret const b: Buf): []U8; |
| 706 | | -proc all*(ret const v: Vec): []T; |
| 707 | | -proc add*(ret var v: Vec): ^T; |
| 708 | | -proc spare*(ret var b: Buf; n: INT): []U8; |
| 709 | | -``` |
| 710 | | - |
| 711 | | -A record that holds an owner, `Http.Message` with its two `Buf`s, is |
| 712 | | -not an owner itself. What its `Buf`s lend is counted on each `Buf`. |
| 713 | | - |
| 714 | | -### 7.3 Counting |
| 715 | | - |
| 716 | | -Where a call returns a reference lent by an owner `o`: |
| 717 | | - |
| 718 | | -- **Used in its statement** (`Out.str(Buf.bytes(b))`, `Buf.str(c, |
| 719 | | - Buf.bytes(b))`): `o.lends` is raised by one as the call returns and |
| 720 | | - lowered at the end of the statement. |
| 721 | | -- **Assigned to a local** of slice or pointer type, `s := Buf.bytes(b)`: |
| 722 | | - the local gets a hidden word, its *hold*, which records the address of |
| 723 | | - `o.lends`. Assigning the local again lowers the old count and raises |
| 724 | | - the new; when the procedure returns, by any path, each hold still set |
| 725 | | - lowers its count, as a `defer` would. `s := []` lets go. |
| 726 | | -- **Anywhere else**: stored in a record, an array, a module variable, |
| 727 | | - through a pointer, or returned. This is an error by part B, since |
| 728 | | - the reference is lent by an owner. A local record holding one is |
| 729 | | - also an error, so that each hold covers one reference: |
| 730 | | - |
| 731 | | -``` |
| 732 | | -Fmt.raz:140:5: error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable |
| 733 | | -``` |
| 734 | | - |
| 735 | | -A reference passed to another procedure needs no count of its own: |
| 736 | | -the caller holds it, by a statement's count or a local's hold, for the |
| 737 | | -whole call. A `ret` result lent by a lent value (`t := Str.trim(s)`, |
| 738 | | -with `s` lent by `b`) is lent by `b` too, and its local gets its own |
| 739 | | -hold. |
| 740 | | - |
| 741 | | -The owner's address is fixed while it is lent. An owner is either a |
| 742 | | -local, a parameter, or a variable reached through a lasting pointer, |
| 743 | | -and part B keeps the lent value from outliving a local or parameter |
| 744 | | -owner. So the hold's address stays good until it is let go. |
| 745 | | - |
| 746 | | -### 7.4 What an owner does with its count |
| 747 | | - |
| 748 | | -The owner's module, which is unsafe and trusted, reads `lends` |
| 749 | | -before it frees memory it has lent: |
| 750 | | - |
| 751 | | -- **Growing:** if `lends` is 0, free the old block, as now. If not, |
| 752 | | - keep it on a list of *retired* blocks, and free those at the next |
| 753 | | - growth, `reset` or `done` that finds `lends` 0. A slice held across |
| 754 | | - the growth keeps pointing at the old block, which stays allocated: |
| 755 | | - it reads what the buffer held when the slice was taken. This is Go's |
| 756 | | - `append`: the old slice still sees the old array. |
| 757 | | -- **`done`**, which gives everything back: if `lends` is above 0, the |
| 758 | | - program stops: |
| 759 | | - |
| 760 | | - ``` |
| 761 | | - Buf.done while 1 slice it lent is still held |
| 762 | | - ``` |
| 763 | | - |
| 764 | | - and the calls under way are shown, as a failed check shows them. |
| 765 | | - `done` can't wait, and can't leave the memory to the slice without |
| 766 | | - leaking it for good. |
| 767 | | -- **`reset`** keeps the block, so it is always safe: a slice held |
| 768 | | - reads the new bytes as they are written over the old. |
| 769 | | - |
| 770 | | -With this, the self-append of 1.2 is right: `Buf.str(b, Buf.bytes(b))` |
| 771 | | -holds a count across the call, the growth retires the old block, and |
| 772 | | -`COPY` reads the old block, still allocated. The `Vec` example reads |
| 773 | | -`1 2` because the memory is still there. The stale `p^ := -1` writes |
| 774 | | -into a retired block: lost, but harmless. Section 11's debugging heap |
| 775 | | -can say so. |
| 776 | | - |
| 777 | | -### 7.5 What it costs |
| 778 | | - |
| 779 | | -- **Run time:** two adds per lend held: on x86-64, `inc qword [r]` and |
| 780 | | - `dec qword [r]`, about two cycles each. In a program that uses |
| 781 | | - `Thread` they are `lock xadd`, about 20 cycles each (part E). Lends |
| 782 | | - are rare next to element accesses: `Fmt.format` lends once per call, |
| 783 | | - and a loop over `Buf.bytes(b)` lends once. |
| 784 | | -- **Memory:** a word per owner, a word per local that holds a lend, |
| 785 | | - and at most the retired blocks, which add up to less than the |
| 786 | | - current block (each was half the next). |
| 787 | | -- **Compiler:** the hold slots, the raise and lower code, and the |
| 788 | | - epilogue's let-go. The epilogue reuses the machinery `defer` already |
| 789 | | - has. |
| 790 | | - |
| 791 | | -### 7.6 Owners aren't copied |
| 792 | | - |
| 793 | | -Copying a `Buf` today makes two records that both own one block. |
| 794 | | -Freeing it twice, or growing one while the other reads, breaks |
| 795 | | -memory. rnet's `Http.reset` does exactly this, safely by luck: |
| 796 | | -`head := m^.head; ...; m^ := {..., head: head}`. In a safe module, a |
| 797 | | -value of an owner type, or of a type that holds one, may not be: |
| 798 | | - |
| 799 | | -- assigned from another variable, returned, passed as a value |
| 800 | | - parameter, or put in a literal. A literal may still leave it out, so |
| 801 | | - that it is zero (`{}`), the empty owner; |
| 802 | | -- compared, or viewed. |
| 803 | | - |
| 804 | | -It is passed as `var` or `const`, and moved by the library: `Buf.swap(var |
| 805 | | -a, b)`, `Buf.take(var from, to)`. The message: |
| 806 | | - |
| 807 | | -``` |
| 808 | | -Http.raz:153:5: error: a Buf.Buf owns memory, and can't be copied |
| 809 | | - help: Buf.take(m^.data, data) moves it, leaving m^.data empty |
| 810 | | -``` |
| 811 | | - |
| 812 | | -### 7.7 Who is an owner |
| 813 | | - |
| 814 | | -`Buf`, `Vec`, `Map` (it lends nothing, but owns its table; `LENDS` |
| 815 | | -stops a copy), `List`, `Pool`, `Arena` and the owned-string map of |
| 816 | | -part D. A program's own record may be an owner too, if an unsafe |
| 817 | | -module of the program frees what it lends. |
| 818 | | - |
| 819 | | ---- |
| 820 | | - |
| 821 | | -## 8. Part D: the heap without `free` |
| 822 | | - |
| 823 | | -### 8.1 The rule |
| 824 | | - |
| 825 | | -In a safe module: |
| 826 | | - |
| 827 | | -- `NEW(p, a)` with `a` lasting (`Heap.heap`) gives a lasting `p`. |
| 828 | | - `Heap.heap` never frees it under safe code, because only unsafe code |
| 829 | | - can call `free`. |
| 830 | | -- `NEW(p, a)` with `a` lent by an owner (an arena, part C) gives a |
| 831 | | - `p` lent by that owner, counted like a slice. |
| 832 | | -- `Mem.free`, `Heap`'s `free`, `Str.free` and `Mem.unmap` are `unsafe |
| 833 | | - proc`s. |
| 834 | | - |
| 835 | | -So a safe program frees memory in one of three ways: |
| 836 | | - |
| 837 | | -1. **Through a container** that owns it: `Buf.done`, `Vec.done`, |
| 838 | | - `Map.done`, `List.clear`, `Pool.free`. Most programs do this already: |
| 839 | | - outside the library, the survey's `done` calls outnumber its hand |
| 840 | | - frees 54 to 26. |
| 841 | | -2. **Through a `Pool(T)`**, for records that come and go one by one |
| 842 | | - (8.2). |
| 843 | | -3. **By ending the program.** A compiler, a tool or a short-lived |
| 844 | | - server process frees nothing by hand, and `src/` frees only its |
| 845 | | - grown arrays, which become `Vec`s. |
| 846 | | - |
| 847 | | -The 1,015 dereferences in `src/` stay as they are, with no check and |
| 848 | | -no cost: every pointer behind them is lasting. |
| 849 | | - |
| 850 | | -### 8.2 `Pool(T)`: handles with a generation |
| 851 | | - |
| 852 | | -``` |
| 853 | | -module Pool(T); |
| 854 | | - |
| 855 | | -type |
| 856 | | - Handle* = record i, gen: INT; end; (* zero: no record *) |
| 857 | | - Pool* = record lends: LENDS; ... end; |
| 858 | | - |
| 859 | | -proc init*(var p: Pool; a: ^Mem.Allocator); |
| 860 | | -proc add*(var p: Pool; keep x: T): Handle; (* a new record, x copied in *) |
| 861 | | -proc get*(const p: Pool; h: Handle): T; (* a copy; stops if h is stale *) |
| 862 | | -proc set*(var p: Pool; h: Handle; keep x: T); (* stops if h is stale *) |
| 863 | | -proc at*(ret var p: Pool; h: Handle): ^T; (* in place, lent by p, counted *) |
| 864 | | -proc valid*(const p: Pool; h: Handle): BOOL; |
| 865 | | -proc free*(var p: Pool; h: Handle); (* the record gone; h, and every copy, stale *) |
| 866 | | -proc done*(var p: Pool); |
| 867 | | -``` |
| 868 | | - |
| 869 | | -Each slot holds a `T` and a generation. `free` raises the slot's |
| 870 | | -generation and puts the slot on a free list. `get`, `set` and `at` check |
| 871 | | -the handle's generation against the slot's, and the index against the |
| 872 | | -pool's length, and stop the program if they differ: |
| 873 | | - |
| 874 | | -``` |
| 875 | | -Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) |
| 876 | | -``` |
| 877 | | - |
| 878 | | -A slot is used only for a `T`, so even a pointer from `at` kept past |
| 879 | | -`free` points at a `T`: a wrong record, perhaps, but never memory |
| 880 | | -of another type. `at`'s count also keeps the pool from moving its slots |
| 881 | | -while the pointer is held (7.4). |
| 882 | | - |
| 883 | | -This is the generational arena of Rust's `slotmap` and |
| 884 | | -`generational-arena`, and the handle pattern Zig and game engines use; |
| 885 | | -Vale builds the same check into every reference. Measured cost |
| 886 | | -(section 13): a list chased through handles takes 1.5 times as long as |
| 887 | | -one chased through raw pointers when it is too big for the caches, and |
| 888 | | -2 times when it fits in L1. Part of the first is that each slot is 32 |
| 889 | | -bytes, not 16. |
| 890 | | - |
| 891 | | -### 8.3 Owned strings |
| 892 | | - |
| 893 | | -`Str.copy` gives a lasting copy, which a safe program can't free. For a |
| 894 | | -long-running program that makes and drops strings (an editor's buffer |
| 895 | | -names, a server's paths), the library adds: |
| 896 | | - |
| 897 | | -- `Buf` as the string a program owns: `Buf.str(name, s)`, freed by |
| 898 | | - `Buf.done`; |
| 899 | | -- `Names(V)`, a map from strings to `V` that copies each key in on |
| 900 | | - `put` and frees it on `remove` and `done`: `Map([]U8, V, ...)` with |
| 901 | | - its keys owned, for those who would otherwise `Str.copy` and leak. |
| 902 | | - |
| 903 | | -### 8.4 Arenas |
| 904 | | - |
| 905 | | -An arena hands out memory and frees it all at once, so what it gives |
| 906 | | -is lent by the arena: |
| 907 | | - |
| 908 | | -``` |
| 909 | | -var ar: Arena.Arena; t: ^Tree; |
| 910 | | -... |
| 911 | | -NEW(t, Arena.allocator(ar)); (* lent by ar *) |
| 912 | | -... |
| 913 | | -Arena.reset(ar); (* stops the program if t is still held *) |
| 914 | | -``` |
| 915 | | - |
| 916 | | -`Arena.allocator(ret var ar): ^Mem.Allocator` gives the allocator, |
| 917 | | -lent by `ar`; `NEW` from it gives a `t` lent by `ar`, counted. Lent |
| 918 | | -values can't be stored in records (part B), so an arena in safe code |
| 919 | | -holds no linked structure: the pointer to a tree's root may live in |
| 920 | | -a local, but the tree's own links can't. A program that builds |
| 921 | | -linked structures in an arena does it in an unsafe module, or with |
| 922 | | -indexes into a `Vec`. Section 14 weighs this. |
| 923 | | - |
| 924 | | ---- |
| 925 | | - |
| 926 | | -## 9. Part E: threads |
| 927 | | - |
| 928 | | -### 9.1 What races can break |
| 929 | | - |
| 930 | | -7.6 says a variable that two threads touch without ordering "holds a |
| 931 | | -value it had or was given, or a mixture of their bytes" and that |
| 932 | | -"nothing else of the program becomes undefined". The second half is |
| 933 | | -wrong today: |
| 934 | | - |
| 935 | | -- a **slice** torn between two writes, one's address with the other's |
| 936 | | - length, is checked against the wrong length and reaches any memory; |
| 937 | | -- a **variant** torn between two cases reads one case's bytes as the |
| 938 | | - other's fields: an integer as a pointer; |
| 939 | | -- a **container** written by two threads at once (`Buf.add` in each) |
| 940 | | - races on its length and its block: one thread writes past the end of |
| 941 | | - the block the other just freed. |
| 942 | | - |
| 943 | | -Go has the same hole: its memory model says that a race on a |
| 944 | | -multi-word value (an interface, a slice, a string) "can lead to |
| 945 | | -arbitrary memory corruption". Rust closes it with `Send` and `Sync`, |
| 946 | | -traits that the type system checks. Java closes it by tearing only |
| 947 | | -`long` and `double`, never a reference. |
| 948 | | - |
| 949 | | -### 9.2 The proposal |
| 950 | | - |
| 951 | | -1. **A slice is one access.** On every target, a slice is read and |
| 952 | | - written in one access that can't tear, as a word is. On x86-64 a |
| 953 | | - slice is aligned to 16 bytes and moved with `movdqa`, which Intel |
| 954 | | - and AMD guarantee single-copy atomic on processors with AVX. On |
| 955 | | - x86-64 without AVX, the implementation uses `lock cmpxchg16b`, or |
| 956 | | - refuses the target, as appendix A says. ARMv8.4 has 16-byte |
| 957 | | - atomic `LDP`/`STP` (FEAT_LSE2). A program that hands slices from |
| 958 | | - thread to thread, publishing a buffer for others to read, is then |
| 959 | | - safe with no lock. |
| 960 | | -2. **The guarantee holds for races on basic, pointer, procedure and |
| 961 | | - slice variables, and no others.** A race on a variant, or on a |
| 962 | | - whole record or array copied at once, or calls of one container's |
| 963 | | - procedures from two threads at once without a lock, is outside |
| 964 | | - it: undefined, as in Go. Section 3 says so, and 7.6 is rewritten |
| 965 | | - to say so. |
| 966 | | -3. **A safe way to start a thread.** `Thread.spawn(p, arg: ^U8)` becomes |
| 967 | | - an `unsafe proc`. A generic `Task(T)` takes its place for safe |
| 968 | | - modules: |
| 969 | | - |
| 970 | | - ``` |
| 971 | | - module Task(T); |
| 972 | | - proc spawn*(p: proc(var x: T); keep x: T): (^Thread.Thread, ERROR); |
| 973 | | - ``` |
| 974 | | - |
| 975 | | - `x` is copied into the new thread's stack before `spawn` returns. |
| 976 | | - Its references must be lasting (`keep`), so a thread never holds |
| 977 | | - a slice of its spawner's frame. |
| 978 | | -4. **Atomics take a variable.** `CAS(x, old, new)`, `XCHG(x, v)` and |
| 979 | | - `XADD(x, k)` take a variable, as `INC` does; through a pointer, `XADD(p^, |
| 980 | | - 1)`. A safe module can then use them, with no `ADR`. |
| 981 | | -5. **Counts are atomic where there are threads.** Part C's raise and |
| 982 | | - lower are `lock xadd` in a program that imports `Thread`, so that two |
| 983 | | - threads lending from one locked `Buf` keep its count right. A |
| 984 | | - program without `Thread` gets the plain `inc` and `dec`. |
| 985 | | -6. **`Lock.Guarded(T)`**, a value with its lock, for sharing a |
| 986 | | - container: |
| 987 | | - |
| 988 | | - ``` |
| 989 | | - g: Guarded(Names.Map); |
| 990 | | - Guarded.with(g, addName); (* addName(var m: Names.Map) runs under the lock *) |
| 991 | | - ``` |
| 992 | | - |
| 993 | | - It makes the safe pattern the easy one, as Rust's `Mutex<T>` does, |
| 994 | | - though nothing stops a program from sharing a container without it. |
| 995 | | - |
| 996 | | -### 9.3 Why not Rust's way |
| 997 | | - |
| 998 | | -A static rule that a container can be reached from two threads only |
| 999 | | -under a lock needs, at the least, marks on types for what may cross |
| 1000 | | -threads (`Send`) and be shared (`Sync`), and a way to see that module |
| 1001 | | -variables are shared. Module variables are reachable from every thread, |
| 1002 | | -and raz has no thread-local storage to put them in instead. It would |
| 1003 | | -add a second type system to the language for a feature two |
| 1004 | | -repositories out of eight use. Section 19 keeps it as a later step. |
| 1005 | | - |
| 1006 | | ---- |
| 1007 | | - |
| 1008 | | -## 10. Part F: the small mends |
| 1009 | | - |
| 1010 | | -### 10.1 An array a call returns lives to the end of its procedure |
| 1011 | | - |
| 1012 | | -"Less that is undefined", piece 1. The temporary's slot in the frame is |
| 1013 | | -reserved for the rest of the procedure, as a deferred statement's slots |
| 1014 | | -already are, so `s := f('a')[0..4]` is lent by the frame, not by the |
| 1015 | | -statement: defined until the procedure returns, and part B keeps it |
| 1016 | | -from going further. In a loop the slot holds the latest call's array. |
| 1017 | | -1.2's last program then prints `name-..a name-..b`, since each call has |
| 1018 | | -a slot of its own. |
| 1019 | | - |
| 1020 | | -The same for a `const` parameter's temporary (section 8): its slot is |
| 1021 | | -reserved to the end of the procedure. |
| 1022 | | - |
| 1023 | | -Cost: a frame bigger by each such call's array. That is not measured |
| 1024 | | -here; in `src/`, arrays returned by calls are small (`Str.fromInt`'s |
| 1025 | | -20 bytes, `Str.encode`'s 4), so the estimate is tens of bytes per |
| 1026 | | -frame. |
| 1027 | | - |
| 1028 | | -### 10.2 A string's bytes |
| 1029 | | - |
| 1030 | | -"Less that is undefined", piece 2. Writing a string constant's bytes, |
| 1031 | | -through a slice of it, either stops the program (a bad address, as now |
| 1032 | | -on Linux, since constants are in read-only data) or changes the |
| 1033 | | -constant for the rest of the run. Which one is the target's choice |
| 1034 | | -(appendix A). Either is defined, and neither touches another |
| 1035 | | -variable. A later `[]const U8` (PROPOSALS) would make it a compile-time |
| 1036 | | -error. |
| 1037 | | - |
| 1038 | | -### 10.3 Views |
| 1039 | | - |
| 1040 | | -A view reading any variable's bytes as an integer type is safe: it |
| 1041 | | -reveals an address, but it can't make one. Writing through a view of a |
| 1042 | | -variable that holds a pointer, slice, procedure, variant, enumeration |
| 1043 | | -or `BOOL` is fenced (5.1), since it would make one of those from |
| 1044 | | -arbitrary bytes. Views of plain data, the survey's every use outside |
| 1045 | | -`Rt`, stay safe. |
| 1046 | | - |
| 1047 | | -### 10.4 `match` on a lent variant |
| 1048 | | - |
| 1049 | | -A `match` on a variant whose case holds references gives names that |
| 1050 | | -are lent as the variant is: a field of a local variant lent by the frame |
| 1051 | | -is lent by the frame. Part B's rules follow. |
| 1052 | | - |
| 1053 | | ---- |
| 1054 | | - |
| 1055 | | -## 11. Part G: a debugging heap |
| 1056 | | - |
| 1057 | | -Unsafe modules are trusted, and trust must be tested. `Heap` gets a |
| 1058 | | -second mode, chosen when the program starts (`RAZ_HEAP=debug` in the |
| 1059 | | -environment, or `Heap.debug(true)` before the first allocation): |
| 1060 | | - |
| 1061 | | -- every freed block is filled with `0DEH` and kept off the free lists |
| 1062 | | - for the next 1,024 frees (a quarantine), so a stale read sees junk |
| 1063 | | - and a stale write is found when the block leaves the quarantine and |
| 1064 | | - its bytes are checked; |
| 1065 | | -- each block gets eight guard bytes after it, checked when it is freed; |
| 1066 | | -- `Buf`, `Vec` and `Pool` fill a retired block with `0DEH` too, so a |
| 1067 | | - slice held across a growth reads junk in the debugging heap and the |
| 1068 | | - old bytes otherwise. |
| 1069 | | - |
| 1070 | | -A break is reported as a failed check is: where, and the calls under |
| 1071 | | -way. `make check` runs the library's tests and `test/run` in both modes. |
| 1072 | | -This is Zig's debug allocator, glibc's `MALLOC_PERTURB_`, and Chrome's |
| 1073 | | -MiraclePtr quarantine, without their reach. It costs nothing unless |
| 1074 | | -chosen. It is the one part that changes no rule and could come first. |
| 1075 | | - |
| 1076 | | ---- |
| 1077 | | - |
| 1078 | | -## 12. Raz beside other languages |
| 1079 | | - |
| 1080 | | -| Language | Spatial | Temporal | Forged pointers | Races | Fence | What it costs | |
| 1081 | | -|---|---|---|---|---|---|---| |
| 1082 | | -| C | none | none | anything | UB | none | nothing | |
| 1083 | | -| C++, hardened | hardened `std` containers; `-fbounds-safety` for C (clang) | none | anything | UB | none | a little | |
| 1084 | | -| 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 | |
| 1085 | | -| Odin, Hare, C3 | checked | none | anywhere | UB | none | a check per index | |
| 1086 | | -| 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 | |
| 1087 | | -| Java, C# | checked | a garbage collector | none | references never tear; `long` may in Java | C#: `unsafe` blocks | a GC, a runtime | |
| 1088 | | -| Swift | checked | reference counting; exclusivity checked at compile and run time | only through `Unsafe*` types | Swift 6: `Sendable`, checked | `Unsafe` in names | refcounting traffic | |
| 1089 | | -| Rust | checked | the borrow checker, at compile time | only in `unsafe` | `Send`/`Sync`, at compile time | `unsafe` blocks and functions | lifetimes, learning, compile time | |
| 1090 | | -| 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 | |
| 1091 | | -| 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 | |
| 1092 | | -| Oberon | checked | a garbage collector | only through `SYSTEM` | n/a | `IMPORT SYSTEM` | a GC | |
| 1093 | | -| 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 | |
| 1094 | | -| Cyclone | fat pointers | regions, checked statically | none | n/a | none | annotations, wider pointers | |
| 1095 | | -| 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 | |
| 1096 | | -| **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 | |
| 1097 | | - |
| 1098 | | -What raz takes from each: |
| 1099 | | - |
| 1100 | | -- **From Modula-3:** the fence by module, and the trust in an unsafe |
| 1101 | | - module's safe interface. The unit of review is a file, as Wirth's |
| 1102 | | - languages always had it. |
| 1103 | | -- **From Ada:** a static rule that a reference can't outlive its |
| 1104 | | - object's level, with no lifetime variables in types. Ada's |
| 1105 | | - accessibility levels are part B's frame, parameters and lasting |
| 1106 | | - memory, nearly exactly. Ada also names deallocation as unchecked. |
| 1107 | | -- **From Rust:** `ret` is lifetime elision written out; `keep` is |
| 1108 | | - `'static`. What raz doesn't take is lifetimes in records, which is |
| 1109 | | - what lets Rust check `Http.Message` and what costs Rust its |
| 1110 | | - learning curve. |
| 1111 | | -- **From Swift:** checking exclusivity at run time where the compiler |
| 1112 | | - can't, as part C counts lends. |
| 1113 | | -- **From Go:** a slice held across a growth sees the old array; and an |
| 1114 | | - honest statement about races. |
| 1115 | | -- **From Vale, `slotmap` and Zig's handle idiom:** generations, |
| 1116 | | - but in a container (`Pool`), not in every pointer, so that the 99% of |
| 1117 | | - pointers that are never freed pay nothing. |
| 1118 | | -- **From Zig:** the debugging allocator as the first line of defence |
| 1119 | | - for unsafe code. |
| 1120 | | - |
| 1121 | | -Where raz ends up: about as safe as Go or Modula-3 for a program that |
| 1122 | | -uses no threads, with no garbage collector and no run time beyond a |
| 1123 | | -count per lend; less expressive than Rust (no record may borrow); and |
| 1124 | | -far simpler to learn and to compile. |
| 1125 | | - |
| 1126 | | ---- |
| 1127 | | - |
| 1128 | | -## 13. Performance |
| 1129 | | - |
| 1130 | | -All measurements are on the session's machine, 4 cores of an x86-64 |
| 1131 | | -virtual machine, using today's compiler. Wall-clock times are the |
| 1132 | | -best of several runs; on this machine they vary by 10 to 20% between |
| 1133 | | -runs, so where it matters instruction counts from `valgrind |
| 1134 | | ---tool=callgrind` are given, which don't vary. |
| 1135 | | - |
| 1136 | | -### 13.1 The compiler's speed |
| 1137 | | - |
| 1138 | | -The largest cost of the proposal to `src/` itself would be checking the |
| 1139 | | -scanner's buffer, if `Scan` stops being unsafe. To measure it, `Scan`'s |
| 1140 | | -`buf: ^U8` was made a checked `[]U8` (with the sentinel inside its |
| 1141 | | -length) and everything else left as it was. Five lines changed: |
| 1142 | | - |
| 1143 | | -| Compile | Pointer (today) | Checked slice | More | |
| 1144 | | -|---|---|---|---| |
| 1145 | | -| `src/Raz.raz`, the compiler itself | 240,851,288 instructions | 251,595,933 | **+4.5%** | |
| 1146 | | -| the generated benchmark, 58,025 lines | 40,305,841 | 42,519,299 | +5.5% | |
| 1147 | | - |
| 1148 | | -`make bench`'s 348,025 lines compile in 625 to 660 ms here, about |
| 1149 | | -530,000 to 557,000 lines a second; 5.5% more is about 500,000 to 528,000, inside the 400,000-line |
| 1150 | | -floor and inside `make prev-bench`'s tenth. Most of the cost is the |
| 1151 | | -scanner's inner loops, `while (c = ' ') ... c := buf[p]`, checking |
| 1152 | | -each byte. Section 21 asks whether `Scan` stays unsafe instead, |
| 1153 | | -leaving the compiler as fast as it is. |
| 1154 | | - |
| 1155 | | -The other changes to `src/` (grown arrays to `Vec`, `intern(s)`, views) |
| 1156 | | -cost nothing measurable: `Vec`'s access through `all` is a slice index, |
| 1157 | | -which is the same check the hand-grown arrays don't have, on paths |
| 1158 | | -much cooler than the scanner's. |
| 1159 | | - |
| 1160 | | -The compiler's own checks (part B, C, the fence) are flags on items |
| 1161 | | -and modules and run while each expression is compiled: no measurable |
| 1162 | | -compile time. |
| 1163 | | - |
| 1164 | | -### 13.2 Kernels |
| 1165 | | - |
| 1166 | | -`MemBench.raz` and `GenBench.raz` (appendix 2): |
| 1167 | | - |
| 1168 | | -| Kernel | Run 1 | Run 2 | What it shows | |
| 1169 | | -|---|---|---|---| |
| 1170 | | -| chase a 1,000,000-node list (16-byte nodes), raw pointers | 8,312 ms | 7,515 ms | the baseline | |
| 1171 | | -| 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 | |
| 1172 | | -| chase a 1,000-node list (in L1), raw pointers | 857 ms | 810 ms | | |
| 1173 | | -| the same through handles | 1,631 ms | 1,643 ms | **1.9–2.0×**: the checks themselves | |
| 1174 | | -| chase 1,000,000 32-byte nodes, raw pointers | 14,001 ms | 13,725 ms | the larger node alone, against row 1: **+70–85%** | |
| 1175 | | -| 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 | |
| 1176 | | -| 1,000 32-byte nodes, raw | 870 ms | 917 ms | | |
| 1177 | | -| 1,000 32-byte nodes, fat pointers | 830 ms | 1,047 ms | within noise to +15% | |
| 1178 | | -| sum 16,000,000 bytes through `^U8`, 50 times | 305 ms | 342 ms | | |
| 1179 | | -| the same through a checked `[]U8` | 271 ms | 434 ms | within noise: the check hides behind the loads | |
| 1180 | | -| sum 4,000 bytes (in L1), 200,000 times, `^U8` | 261 ms | 265 ms | | |
| 1181 | | -| the same, checked `[]U8` | 256 ms | 306 ms | 0–15% | |
| 1182 | | - |
| 1183 | | -What they say: |
| 1184 | | - |
| 1185 | | -- **Bounds checks are cheap.** On sequential access the check is |
| 1186 | | - hidden by the loads it guards. This is why nobody uses `check off;`. |
| 1187 | | -- **A generation check is cheap when it is in the object's cache line** |
| 1188 | | - (the fat-pointer rows). **Wider references are not cheap:** doubling a |
| 1189 | | - node from 16 to 32 bytes costs 70 to 85% when the structure doesn't fit |
| 1190 | | - in the caches. This is the main argument against making every `^T` |
| 1191 | | - a fat generational pointer (section 19). It is also why `Pool`'s |
| 1192 | | - handles cost half again: the 32-byte slots, not the check. |
| 1193 | | -- **Handles cost 1.5–2× where pointer chasing dominates**, which is |
| 1194 | | - linked lists and trees. A safe program pays it only for the records |
| 1195 | | - it frees one by one; everything else stays a lasting `^T` with no |
| 1196 | | - check. |
| 1197 | | - |
| 1198 | | -### 13.3 What each part costs a program |
| 1199 | | - |
| 1200 | | -| Part | Cost | Where | |
| 1201 | | -|---|---|---| |
| 1202 | | -| A, the fence | none | compile time | |
| 1203 | | -| B, lending | none | compile time | |
| 1204 | | -| 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 | |
| 1205 | | -| C, retired blocks | memory: at most the current block again, only while a lend is held across a growth | rare | |
| 1206 | | -| D, no `free` | none for lasting pointers; handles where chosen, 1.5–2× on chasing | `Pool` users only | |
| 1207 | | -| 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 | |
| 1208 | | -| E, atomic counts | about 20 cycles per lend, with threads only | | |
| 1209 | | -| F, temporaries | frame size | | |
| 1210 | | -| G, the debugging heap | none unless chosen | | |
| 1211 | | - |
| 1212 | | ---- |
| 1213 | | - |
| 1214 | | -## 14. Ergonomics |
| 1215 | | - |
| 1216 | | -### 14.1 What doesn't change |
| 1217 | | - |
| 1218 | | -Most raz is already safe under this proposal: the survey's `Parse`, |
| 1219 | | -`Item`, `Sym` and `Gen`, `tools/`, rjson's parser, rflate's inflater, |
| 1220 | | -rterm. They use records, slices, `var`, `const` and pointers from |
| 1221 | | -`NEW`, and they don't free. For them the change is a few `ret`s in the |
| 1222 | | -library's headings, which the caller never writes. |
| 1223 | | - |
| 1224 | | -### 14.2 What a programmer meets |
| 1225 | | - |
| 1226 | | -**A slice of a buffer kept in a record.** rnet's `Http.Message` keeps |
| 1227 | | -`headers[i].name` as slices of `m^.head`'s bytes and `body` as a slice |
| 1228 | | -of `m^.data`. Under part B and C these are lent by owners and can't be |
| 1229 | | -stored in a record. The choices: |
| 1230 | | - |
| 1231 | | -1. Offsets instead of slices: |
| 1232 | | - |
| 1233 | | - ``` |
| 1234 | | - Header* = record name, value: Span; end; (* Span = record at, len: INT; end *) |
| 1235 | | - proc name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by m *) |
| 1236 | | - ``` |
| 1237 | | - |
| 1238 | | - which is safe, a little longer, and survives `m^.head` growing. It |
| 1239 | | - is how Rust programs without lifetimes in structs do it. |
| 1240 | | -2. `Http` says `unsafe;`, and keeps its invariant by hand, as it does |
| 1241 | | - today. It becomes one of the modules a reviewer reads twice. |
| 1242 | | - |
| 1243 | | -The proposal recommends the first for libraries, since it is what |
| 1244 | | -the guarantee is for. |
| 1245 | | - |
| 1246 | | -**A slice held across a call that might change its owner.** This is |
| 1247 | | -allowed. Part C counts it, and the owner retires instead of freeing. |
| 1248 | | -rmacs's `save`, with its `path := Buf.bytes(x^.path)` held across |
| 1249 | | -`Buf.reset(tmp)` and `Buf.str(tmp, path)`, compiles and runs as |
| 1250 | | -before. |
| 1251 | | - |
| 1252 | | -**`done` with a slice still held.** This stops the program at run time: |
| 1253 | | - |
| 1254 | | -``` |
| 1255 | | -proc report(x: ^Buffer); |
| 1256 | | -var name: []U8; |
| 1257 | | -begin |
| 1258 | | - name := Buf.bytes(x^.name); |
| 1259 | | - Buf.done(x^.name); (* stops: name still holds a lend *) |
| 1260 | | - ... |
| 1261 | | -end; |
| 1262 | | -``` |
| 1263 | | - |
| 1264 | | -The cure is `name := []` before `done`, or not holding it. It is a |
| 1265 | | -false alarm only when `name` is never read again. Since a stop is |
| 1266 | | -loud and the cure is one line, the proposal accepts it. |
| 1267 | | - |
| 1268 | | -**Owners can't be copied.** `head := m^.head` in rnet becomes |
| 1269 | | -`Buf.take(m^.head, head)`. The survey didn't count such copies; rnet's |
| 1270 | | -`Http.reset` is the one found by reading. |
| 1271 | | - |
| 1272 | | -**Records that come and go.** An editor's windows, freed when closed, |
| 1273 | | -become a `Pool(Window)` with `Handle`s where rmacs had `^Window` and |
| 1274 | | -`Mem.free`. Each access is `Windows.at(pool, h)^.field` or `get`. This is |
| 1275 | | -longer than `w^.field`, and 1.5–2× slower in a pointer-chasing loop, |
| 1276 | | -which an editor doesn't have. |
| 1277 | | - |
| 1278 | | -**An arena with links.** A tree built in an arena with `^Node` links |
| 1279 | | -can't be safe (8.4): links are stored in records, and lent pointers |
| 1280 | | -can't be. It becomes indexes into a `Vec(Node)`, which is often faster |
| 1281 | | -(smaller, contiguous), or stays in an unsafe module. |
| 1282 | | - |
| 1283 | | -**Strings that must be freed.** `Str.copy` and `Str.free` become |
| 1284 | | -`Names(V)` or a `Buf` per string (8.3). |
| 1285 | | - |
| 1286 | | -**Threads.** `Thread.spawn(work, ^U8(ADR(job)))` becomes |
| 1287 | | -`Jobs.spawn(work, job)`, with `import Jobs := Task(Job)`. That is |
| 1288 | | -shorter. |
| 1289 | | - |
| 1290 | | -### 14.3 What the compiler says |
| 1291 | | - |
| 1292 | | -Each new error names the rule and the mending, in the house style: |
| 1293 | | - |
| 1294 | | -``` |
| 1295 | | -error: ADR is for unsafe modules |
| 1296 | | - help: pass x as a var parameter, or say "unsafe;" after the module's imports |
| 1297 | | -error: Names.put keeps its key, and buf[0..8] is lent by this call's frame |
| 1298 | | - help: give put a copy that lasts: Str.copy(Heap.heap, buf[0..8]) |
| 1299 | | -error: Buf.bytes(b) is lent by b, which counts what it lends: hold it in a slice variable |
| 1300 | | -error: a Buf.Buf owns memory, and can't be copied |
| 1301 | | - help: Buf.take(from, to) moves it |
| 1302 | | -error: Str.trim(s) is lent by s, which isn't marked ret |
| 1303 | | - help: mark the parameter "ret s: []U8" to return what points into it |
| 1304 | | -error: Mem.free is an unsafe procedure |
| 1305 | | - help: free through the container that owns the memory, or say "unsafe;" |
| 1306 | | -``` |
| 1307 | | - |
| 1308 | | -and two new run-time stops: |
| 1309 | | - |
| 1310 | | -``` |
| 1311 | | -Buf.done while 1 slice it lent is still held |
| 1312 | | -Pool.get: a stale handle (slot 4, generation 3; the slot is at 5) |
| 1313 | | -``` |
| 1314 | | - |
| 1315 | | ---- |
| 1316 | | - |
| 1317 | | -## 15. What breaks |
| 1318 | | - |
| 1319 | | -Everything breaks that uses a fenced operation in a module that |
| 1320 | | -doesn't say `unsafe;`, or stores a lent reference, or copies an |
| 1321 | | -owner. By codebase: |
| 1322 | | - |
| 1323 | | -| Code | What breaks | The mending | |
| 1324 | | -|---|---|---| |
| 1325 | | -| `lib/` | every module with a fenced operation: `Rt`, `Mem`, `Heap`, `Arena`, `Bytes`, `Sys`, `Thread`, `Lock`, `C`, `CAbi`, `Buf`, `Vec`, `Map`, `List` | `unsafe;` | |
| 1326 | | -| | `Str`, `Fmt`, `Opt`, `Files` | drop two to five operations each; they become safe | |
| 1327 | | -| | 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 | |
| 1328 | | -| | `Buf`, `Vec`, `Map`, `List`, `Arena`: a `LENDS` field, retiring, `done`'s stop, `take`, `swap` | about 15 lines each | |
| 1329 | | -| | new: `Pool`, `Task`, `Names`, `Lock.Guarded`, `Arena.allocator`; `Heap`'s debugging mode | about 400 lines in all | |
| 1330 | | -| | `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 | |
| 1331 | | -| `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;` | |
| 1332 | | -| `tools/` | nothing fenced; any `Map.put` of a frame slice | none found | |
| 1333 | | -| `examples/` | `Args`, `Cpu`, `Pthreads`, `Printf`, `Window`, `Volatile`, `Sh`, `Workers` | `Args`, `Sh`, `Workers` mended; the other five say `unsafe;`, as examples of it | |
| 1334 | | -| `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 | |
| 1335 | | -| rnet | `Http.Message` keeps lent slices; `reset` copies `Buf`s; `Thread.spawn` | spans and accessors; `take`; `Task` | |
| 1336 | | -| rjson | `Str.free` and `Mem.free` (6); a few casts | `Names` or `Buf`; views | |
| 1337 | | -| rflate | none beyond `ADR` at calls (gone with v0.19.0's library) | none | |
| 1338 | | -| rsqlite | C | `unsafe;` on `Sqlite` | |
| 1339 | | -| rmacs, ravite | `ADR` at calls (gone with v0.19.0); `Mem.free` (9 and 2) of windows and buffers | `Pool` | |
| 1340 | | -| rlX11 | casts on X11 replies | views; one unsafe module for the socket's bytes | |
| 1341 | | -| rmacs's and ravite's `Scan` use | `tools/Scan.raz` | nothing fenced | |
| 1342 | | - |
| 1343 | | -Every break is found when compiling, with a message that names its |
| 1344 | | -mending, except a `done` while a lend is held, which shows up at run |
| 1345 | | -time with a message. No program changes meaning without an error. |
| 1346 | | - |
| 1347 | | -A `raz -fix` (or `tools/Mutate.raz` taught the rewrites) can make |
| 1348 | | -the mechanical ones: `ADR(x)` at a `var` parameter, `^F64(ADR(x))` to |
| 1349 | | -a view, `intern(ADR(s[0]), LEN(s))` to `intern(s)`, `unsafe;` where a |
| 1350 | | -module keeps a fenced operation after those. |
| 1351 | | - |
| 1352 | | ---- |
| 1353 | | - |
| 1354 | | -## 16. Changes to the report |
| 1355 | | - |
| 1356 | | -The report grows by about three pages, from 32 to 35, inside its |
| 1357 | | -40. By section: |
| 1358 | | - |
| 1359 | | -**1. A first look.** One paragraph: what is safe, what `unsafe;` |
| 1360 | | -means, where to read more. |
| 1361 | | - |
| 1362 | | -**3. Modules.** The grammar takes the line: |
| 1363 | | - |
| 1364 | | -``` |
| 1365 | | -Module = "module" ident [ "(" ModParams ")" ] ";" |
| 1366 | | - { Import } { Link } [ Check ] [ Unsafe ] { Declaration } |
| 1367 | | - [ "begin" Statements ] "end" ident "." . |
| 1368 | | -Unsafe = "unsafe" ";" . |
| 1369 | | -``` |
| 1370 | | - |
| 1371 | | -A new paragraph, **`unsafe;`**, says what it allows (the table of |
| 1372 | | -5.1), and that `link` and `check off;` need it. **Generic modules**: |
| 1373 | | -an instance is safe or unsafe as its generic module is, as with |
| 1374 | | -`check`. |
| 1375 | | - |
| 1376 | | -**5.3 Slices.** "A slice is aligned to twice an address's |
| 1377 | | -alignment, and read and written in one access (7.6)." |
| 1378 | | - |
| 1379 | | -**5.4 Pointers.** A paragraph: in a safe module a pointer is `nil`, |
| 1380 | | -from `NEW`, or from the library; section 8.x says how long it lives. |
| 1381 | | - |
| 1382 | | -**5.5 Records.** **Owners**: a record with a `LENDS` field; it can't |
| 1383 | | -be copied in a safe module (7.6 of this proposal). `LENDS` joins the |
| 1384 | | -basic types in 5.1, as a type only a record's field may have. |
| 1385 | | - |
| 1386 | | -**5.9 Procedure types.** `unsafe proc`, and the marks `ret` and `keep`, |
| 1387 | | -which a procedure type carries; what may stand where (PROPOSALS). |
| 1388 | | - |
| 1389 | | -**6.4 Pointers.** `p + i`, `p - i`, `p[i]` and `p[lo..hi]`: "only in an |
| 1390 | | -unsafe module". |
| 1391 | | - |
| 1392 | | -**6.7 Conversions.** The pointer rows: "only in an unsafe module". |
| 1393 | | - |
| 1394 | | -**6.8 Built-in procedures.** `ADR`, `PTR`, `SYSCALL` and `ARGV`: "only in |
| 1395 | | -an unsafe module". `NEW` (part D): what it gives lasts, or is lent by |
| 1396 | | -its allocator's owner. `CAS`, `XCHG` and `XADD` take a variable. |
| 1397 | | - |
| 1398 | | -**6.9 Views.** Writing a view of a variable that holds a pointer, |
| 1399 | | -slice, procedure, variant, enumeration or `BOOL`, and a view as a |
| 1400 | | -pointer type, are for unsafe modules. |
| 1401 | | - |
| 1402 | | -**7.3 Return.** The paragraph on slices of the frame is replaced by a |
| 1403 | | -reference to the new section 8.x, which covers every route. |
| 1404 | | - |
| 1405 | | -**7.6 Volatile.** "Nothing else of the program becomes undefined by |
| 1406 | | -it" becomes: a race on a variable of a basic, pointer, procedure or |
| 1407 | | -slice type gives a value it had or was given, never a mixture; a race |
| 1408 | | -on anything else, or on a container's procedures called at once, is |
| 1409 | | -outside the guarantee (10). |
| 1410 | | - |
| 1411 | | -**8. Procedures.** The marks `ret` and `keep` in the grammar, |
| 1412 | | -`Params = [ "ret" ] [ "keep" ] [ "var" | "const" ] ...`, and |
| 1413 | | -`ProcDeclaration` takes `[ "unsafe" ]` before `proc`. A new section, |
| 1414 | | -**8.x Lending**, about two pages, with part B's rules (lasting, |
| 1415 | | -lent, by whom; what may be done with each) and part C's counting, |
| 1416 | | -and the examples of 6.4 of this proposal. An array a call returns, and a |
| 1417 | | -`const` parameter's temporary, live to the end of the procedure |
| 1418 | | -(part F). The paragraph "kept past its statement ... the exception of |
| 1419 | | -section 10" goes. |
| 1420 | | - |
| 1421 | | -**9. Calling C.** "`extern` and `link` only in an unsafe module." |
| 1422 | | - |
| 1423 | | -**10. Programs.** **Defined behaviour** becomes **The guarantee** |
| 1424 | | -(section 3), and the list of exceptions shrinks to one sentence: an |
| 1425 | | -unsafe module, a code procedure and C may break memory, and what |
| 1426 | | -follows isn't defined; a safe program can't. The stops stay as they |
| 1427 | | -are, and the two new run-time stops are added: an owner's `done` with |
| 1428 | | -lends held, and a library container's own checks (a stale handle). **Errors**: a |
| 1429 | | -fenced operation outside an unsafe module, a lent value where it can't |
| 1430 | | -go, a copied owner, a call of an `unsafe proc` from a safe module. |
| 1431 | | - |
| 1432 | | -**Appendix A.** How slices are made one access (16-byte moves, or a |
| 1433 | | -lock, or a refused target); whether writing a string constant stops or |
| 1434 | | -changes it; how the debugging heap is chosen. |
| 1435 | | - |
| 1436 | | -**Appendix B.** The grammar's new lines. |
| 1437 | | - |
| 1438 | | -**The library volume.** `unsafe proc` and `ret`/`keep` in every |
| 1439 | | -heading; `Pool`, `Task`, `Names`, `Lock.Guarded`; owners' `take`, |
| 1440 | | -`swap` and their stop; `Heap`'s debugging mode. `Mem.Allocator` |
| 1441 | | -described as an unsafe interface. Which modules are unsafe, and their |
| 1442 | | -promise. |
| 1443 | | - |
| 1444 | | -**`doc/report-history.md`**, **`doc/compiler.md`** (each rule, where in |
| 1445 | | -the compiler, with code before and after), **raz(7)**, the tutorial and |
| 1446 | | -`STANDARDS.md` ("a parameter is a value, `var`, `const`, or `keep`; a |
| 1447 | | -pointer only in an unsafe module or where `NEW` gave it"). |
| 1448 | | - |
| 1449 | | ---- |
| 1450 | | - |
| 1451 | | -## 17. Changes to the library |
| 1452 | | - |
| 1453 | | -| Module | Change | |
| 1454 | | -|---|---| |
| 1455 | | -| `Mem` | `Allocator`'s fields `unsafe proc`; `free`, `unmap`, `pages` `unsafe proc`s | |
| 1456 | | -| `Heap` | `free` unsafe; the debugging mode (part G); big blocks' address ranges kept reserved after `free` in debugging mode | |
| 1457 | | -| `Arena` | an owner; `allocator(ret var ar)`; `reset` and `done` stop if lends are held | |
| 1458 | | -| `Buf` | an owner; `bytes`, `spare` `ret`; retiring; `done` stops; `take`, `swap` | |
| 1459 | | -| `Vec` | an owner; `all`, `add`, `tryAdd` `ret`; `push`, `tryPush` `keep x`; retiring; `done` stops; `take`, `swap` | |
| 1460 | | -| `Map` | an owner (it counts no lends, but isn't copied); `put` `keep k`, `keep v` | |
| 1461 | | -| `List` | an owner; `push` `keep v` | |
| 1462 | | -| `Str` | `trim`, `trimLeft`, `trimRight`, `cut`, `field` `ret`; `free` unsafe; `copy` documented as lasting; safe module | |
| 1463 | | -| `Fmt`, `Opt`, `Files` | made safe; `Opt.init`, `scope` `keep` | |
| 1464 | | -| `Sys` | the raw-pointer calls `unsafe proc`; `nextEntry` `ret`; the rest safe to call | |
| 1465 | | -| `Thread` | `spawn` unsafe; `Mutex` taken by `var`, as now | |
| 1466 | | -| `Lock` | `Guarded(T)` | |
| 1467 | | -| new `Pool(T)` | 8.2 | |
| 1468 | | -| new `Task(T)` | 9.2 | |
| 1469 | | -| new `Names(V)` | 8.3 | |
| 1470 | | - |
| 1471 | | ---- |
| 1472 | | - |
| 1473 | | -## 18. Changes to the compiler |
| 1474 | | - |
| 1475 | | -Where each part goes in `src/`, and about how big each is. The |
| 1476 | | -budget is 14,000 lines of code and the compiler is about 11,500 today. |
| 1477 | | - |
| 1478 | | -| Part | Where | Lines | |
| 1479 | | -|---|---|---| |
| 1480 | | -| 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 | |
| 1481 | | -| 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 | |
| 1482 | | -| 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 | |
| 1483 | | -| D. `NEW`'s provenance | lasting or lent by its allocator | 20 | |
| 1484 | | -| 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 | |
| 1485 | | -| F. Temporaries | the slot reserved to the end, as `defer`'s are | 20 | |
| 1486 | | -| Messages, with help | | 100 | |
| 1487 | | -| **In all** | | **840–990** | |
| 1488 | | - |
| 1489 | | -So the compiler grows to about 12,400–12,500 lines, inside the budget, |
| 1490 | | -with room for the documentation the house style demands. The |
| 1491 | | -rewrite of `src/` to be safe (section 15) takes lines away: 35 grown |
| 1492 | | -arrays made `Vec`s. |
| 1493 | | - |
| 1494 | | -Each rule is explained in `doc/compiler.md` where it is done, with the |
| 1495 | | -code before and after, as CLAUDE.md asks. |
| 1496 | | - |
| 1497 | | ---- |
| 1498 | | - |
| 1499 | | -## 19. Alternatives considered |
| 1500 | | - |
| 1501 | | -**A garbage collector.** It would make `free` and part C unneeded, as in |
| 1502 | | -Go, Java and Oberon. It is rejected: raz promises "a static executable |
| 1503 | | -with no run time besides the code it uses" (10). A collector needs |
| 1504 | | -stack maps, barriers or pauses, and a heap the language owns, and it |
| 1505 | | -would end raz as a systems language with a C-like footprint. |
| 1506 | | - |
| 1507 | | -**Rust's borrow checker.** It closes everything, races included, at |
| 1508 | | -compile time. It is rejected for raz: lifetimes in types, regions |
| 1509 | | -inferred over whole procedures (non-lexical lifetimes are a fixpoint |
| 1510 | | -over the control flow, not one pass), and a learning curve that is |
| 1511 | | -the opposite of "a beginner can follow". The proposal takes from it |
| 1512 | | -`ret` (elision, written) and `keep` (`'static`), and leaves out |
| 1513 | | -lifetimes in records, knowing what that costs (14.2). |
| 1514 | | - |
| 1515 | | -**Fat generational pointers for every `^T`** (Vale). Every `^T` would |
| 1516 | | -become (address, generation), and `free` would be safe and checked at |
| 1517 | | -every dereference. Measured (13.2): the check costs little, since the |
| 1518 | | -generation sits in the object's cache line, but doubling a pointer |
| 1519 | | -cost 70–85% on a structure past the caches. Records with pointers grow, |
| 1520 | | -C interop needs a second, raw pointer type, and the 1,015 dereferences |
| 1521 | | -in `src/`, of memory never freed, would pay for a check they can't fail. |
| 1522 | | -It is kept as a fallback if part D proves too narrow: `Pool` is the |
| 1523 | | -same mechanism, where it is paid for only by what is freed. |
| 1524 | | - |
| 1525 | | -**Statically killing a lent slice when its owner changes.** One-pass |
| 1526 | | -flow analysis can't see a loop's back edge, and through a pointer |
| 1527 | | -every call may change the owner (7.1). It would need a second pass, or |
| 1528 | | -a rule so strict ("a lent slice dies at the end of its statement") |
| 1529 | | -that `s := Buf.bytes(b)` over several lines, 35 places in the survey, |
| 1530 | | -would all break. |
| 1531 | | - |
| 1532 | | -**Stop on growth while lent, instead of retiring.** It is simpler to |
| 1533 | | -explain, and it finds the stale-pointer bug in 1.2 at once. But it also |
| 1534 | | -stops `Buf.str(b, Buf.bytes(b))`, which is right and common in other |
| 1535 | | -languages (Go's `append(s, s...)`). Retiring keeps right programs |
| 1536 | | -running, and the debugging heap (part G) shows the stale ones. |
| 1537 | | - |
| 1538 | | -**Thread-local module variables, or `Send`/`Sync`.** They are needed |
| 1539 | | -for a static race guarantee. They are left for later (9.3): they |
| 1540 | | -cost a second type system for a feature little used. If they come, |
| 1541 | | -part E's statement grows to cover every program, and nothing else in |
| 1542 | | -this proposal changes. |
| 1543 | | - |
| 1544 | | -**Hardware: memory tagging (ARM MTE) and CHERI.** They catch use |
| 1545 | | -after free and out-of-bounds by tagging memory and pointers. They |
| 1546 | | -help unsafe modules and C, they aren't on x86-64, and they are |
| 1547 | | -probabilistic (MTE's four bits). They would make part G stronger, |
| 1548 | | -not replace B to D. |
| 1549 | | - |
| 1550 | | -**Only the fence (PROPOSALS' piece 4).** It is cheap and gives a list |
| 1551 | | -of modules to audit, but what it leaves undefined in safe code is |
| 1552 | | -exactly 1.2's first four programs. A fence around code that is still |
| 1553 | | -unsafe would mislead the reader. That is why this proposal exists. |
| 1554 | | - |
| 1555 | | ---- |
| 1556 | | - |
| 1557 | | -## 20. Order of work |
| 1558 | | - |
| 1559 | | -Each step is a release, and each leaves `make check` passing and every |
| 1560 | | -program building, with warnings where a later step will make errors. |
| 1561 | | - |
| 1562 | | -1. **The debugging heap (G).** It changes no rule, and finds bugs in |
| 1563 | | - today's code, the library's above all, before the rules arrive. |
| 1564 | | - Run `make check` under it. |
| 1565 | | -2. **Temporaries to the end of the procedure (F.1), strings (F.2).** |
| 1566 | | - No program breaks. |
| 1567 | | -3. **Atomic slices, and 7.6 rewritten (E.1, E.2).** No program breaks. |
| 1568 | | -4. **`ret` and `keep` (B), as warnings,** then errors a release later. |
| 1569 | | - Mark the library. This is PROPOSALS' part 3, extended to |
| 1570 | | - pointers. |
| 1571 | | -5. **Owners (C).** `LENDS` in the containers, retiring, counting, |
| 1572 | | - `take` and `swap`; the copy check as a warning, then an error. |
| 1573 | | -6. **The heap (D).** `Pool`, `Names`, `Task`; `free` an `unsafe |
| 1574 | | - proc`, warned of first. |
| 1575 | | -7. **The fence (A),** last, as a warning for one release, then an |
| 1576 | | - error, once everything it would flag has a safe form. `src/` comes |
| 1577 | | - to it, keeping `Scan` unsafe, or not, by the owner's word (21). |
| 1578 | | -8. **The report's guarantee (section 10),** stated when step 7 makes |
| 1579 | | - it true. |
| 1580 | | - |
| 1581 | | -`src/` must build with the release `BOOT` names, so it takes up each |
| 1582 | | -step one release after the step ships. |
| 1583 | | - |
| 1584 | | ---- |
| 1585 | | - |
| 1586 | | -## 21. Open questions |
| 1587 | | - |
| 1588 | | -1. **Does `Scan` stay unsafe?** Checking its buffer costs the |
| 1589 | | - compiler 4.5% (13.1). Leaving it unsafe keeps the speed, and the |
| 1590 | | - compiler then has one unsafe module, which is easy to read. |
| 1591 | | -2. **`LENDS` as a type, or a mark on the record** (`owner record`)? |
| 1592 | | - The field makes the count visible to the module that reads it, and |
| 1593 | | - needs no new word; a mark would be more explicit. |
| 1594 | | -3. **Should `done` with a lend held leak instead of stopping?** It |
| 1595 | | - would mean no false alarms, but a silent leak that can grow. |
| 1596 | | -4. **Is a local record holding an owner-lent slice worth allowing?** |
| 1597 | | - (7.3 forbids it.) It needs one hold per reference in the record, and |
| 1598 | | - a let-go when the record is reassigned. `Fmt.Arg` arrays are the |
| 1599 | | - case: `[Fmt.str(Buf.bytes(b))]` is fine inside a statement, but not |
| 1600 | | - held in a local array. |
| 1601 | | -5. **Is the race guarantee enough?** A cheap dynamic check would close |
| 1602 | | - the container case in programs with threads: each owner records |
| 1603 | | - the thread that last changed it, and changes from another thread |
| 1604 | | - without the lock stop the program, as Swift's exclusivity checks do. |
| 1605 | | -6. **`Pool`'s handle**: two words, or one, with 40 bits of index and 24 |
| 1606 | | - of generation? One word fits in a register and halves `Pool`'s |
| 1607 | | - memory for handles, and generations would wrap after 16 million |
| 1608 | | - frees of one slot. |
| 1609 | | -7. **`unsafe` per procedure, not per module?** Rust's `unsafe` blocks |
| 1610 | | - are finer. A module is raz's unit of review, and a module can be |
| 1611 | | - split, but `Sys` would need a split into a safe and an unsafe half |
| 1612 | | - for readers to see the difference. |
| 1613 | | - |
| 1614 | | ---- |
| 1615 | | - |
| 1616 | | -## Appendix 1: the survey's numbers |
| 1617 | | - |
| 1618 | | -Places of each operation, counted once each, by the instrumented |
| 1619 | | -compiler. `deref` and `new` are shown for scale; they stay safe, as |
| 1620 | | -does `p - q`, which the module table below counts with the rest. |
| 1621 | | - |
| 1622 | | -| Code | `ADR` | deref | `p[i]` | `p[a..b]` | `p ± i` | `p - q` | ptr cast | int→ptr | ptr→int | view | `NEW` | `SYSCALL` | |
| 1623 | | -|---|---|---|---|---|---|---|---|---|---|---|---|---| |
| 1624 | | -| raz `src/` | 27 | 1,015 | 277 | 30 | 3 | 0 | 42 | 0 | 0 | 0 | 5 | 3 | |
| 1625 | | -| raz `lib/` | 144 | 93 | 88 | 14 | 49 | 2 | 52 | 13 | 4 | 2 | 1 | 140 | |
| 1626 | | -| raz `examples/` | 15 | 46 | 2 | 1 | 0 | 0 | 5 | 0 | 0 | 3 | 1 | 0 | |
| 1627 | | -| raz `test/libc` | 110 | 15 | 35 | 11 | 18 | 0 | 64 | 1 | 6 | 0 | 1 | 0 | |
| 1628 | | -| rnet | 471 | 359 | 0 | 0 | 0 | 0 | 9 | 1 | 1 | 0 | 0 | 0 | |
| 1629 | | -| rjson | 91 | 105 | 0 | 7 | 1 | 0 | 13 | 0 | 0 | 0 | 0 | 0 | |
| 1630 | | -| rflate | 61 | 102 | 0 | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 2 | 0 | |
| 1631 | | -| rsqlite | 38 | 12 | 1 | 3 | 0 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | |
| 1632 | | - |
| 1633 | | -The fenced operations of each module of `src/` and `lib/`: |
| 1634 | | - |
| 1635 | | -| Module | Fenced | Of which | |
| 1636 | | -|---|---|---| |
| 1637 | | -| `src/Scan` | 99 | `p[i]` 76, casts 12, `p[a..b]` 6, `ADR` 3, `p ± i` 2 | |
| 1638 | | -| `src/Link` | 71 | `p[i]` 63, `p[a..b]` 4, casts 4 | |
| 1639 | | -| `src/Chunk` | 65 | `p[i]` 53, casts 10, `p[a..b]` 1, `ADR` 1 | |
| 1640 | | -| `src/X64` | 31 | `p[i]` 23, `ADR` 5, casts 3 | |
| 1641 | | -| `src/Diag` | 23 | `p[i]` 15, `p[a..b]` 3, casts 3, `ADR` 2 | |
| 1642 | | -| `src/Elf` | 23 | `p[i]` 17, `p[a..b]` 3, `ADR` 3 | |
| 1643 | | -| `src/Parse` | 21 | `p[a..b]` 8, `ADR` 5, `p[i]` 5, casts 2, `SYSCALL` 1 | |
| 1644 | | -| `src/Sym` | 17 | `p[i]` 12, casts 3, `ADR` 2 | |
| 1645 | | -| `src/Item` | 16 | `p[i]` 5, `p[a..b]` 4, casts 4, `ADR` 3 | |
| 1646 | | -| `src/Gen` | 8 | `p[i]` 5, `ADR` 2, casts 1 | |
| 1647 | | -| `src/Raz` | 8 | `p[i]` 3, `SYSCALL` 2, `ADR` 1, `p[a..b]` 1, `p ± i` 1 | |
| 1648 | | -| `lib/Sys` | 287 | `SYSCALL` 129, `ADR` 98, `p[i]` 31, casts 12, `p ± i` 8, `p[a..b]` 6 | |
| 1649 | | -| `lib/Rt` | 111 | `p ± i` 32, `p[i]` 31, casts 20, `ADR` 10, int→ptr 10, `SYSCALL` 6 | |
| 1650 | | -| `lib/Thread` | 33 | `ADR` 16, casts 6, `SYSCALL` 5, `p[i]` 3, `p ± i` 3 | |
| 1651 | | -| `lib/Map` | 19 | `p[i]` 16, casts 3 | |
| 1652 | | -| `lib/Heap` | 16 | `p ± i` 4, casts 4, ptr→int 4, `p[i]` 2 | |
| 1653 | | -| `lib/Bytes` | 10 | `ADR` 5, casts 5 | |
| 1654 | | -| `lib/Buf` | 6 | `p[a..b]` 4, `p[i]` 1, `ADR` 1 | |
| 1655 | | -| `lib/Opt` | 5 | `ADR` 5 | |
| 1656 | | -| `lib/Arena` | 4 | `p ± i` 2, `ADR` 1, cast 1 | |
| 1657 | | -| `lib/Fmt` | 4 | `ADR` 4 | |
| 1658 | | -| `lib/Files`, `lib/Str` | 3 each | | |
| 1659 | | -| `lib/Lock`, `lib/Mem` | 2 each | | |
| 1660 | | -| `lib/List` | 1 | | |
| 1661 | | -| `lib/Math`, `Out`, `Sort`, `Width` | 0 | | |
| 1662 | | - |
| 1663 | | -`Vec` (generic, and instantiated by no program surveyed) has 11 by |
| 1664 | | -`grep`. `C` and `CAbi` are `extern` declarations (96 and 2). |
| 1665 | | - |
| 1666 | | -By `grep`, for the code today's compiler refuses (written before |
| 1667 | | -`INT`): |
| 1668 | | - |
| 1669 | | -| Code | Lines of code | `ADR` | at a call | casts | frees | `done` | `reset` | |
| 1670 | | -|---|---|---|---|---|---|---|---| |
| 1671 | | -| rmacs | 4,323 | 560 | 556 | 9 | 9 | 16 | 66 | |
| 1672 | | -| ravite | 2,185 | 202 | 200 | 3 | 2 | 1 | 15 | |
| 1673 | | -| rlX11 | 5,226 | 89 | 87 | 3 | 1 | 0 | 0 | |
| 1674 | | - |
| 1675 | | -## Appendix 2: the benchmarks |
| 1676 | | - |
| 1677 | | -Built with `raz -o MemBench MemBench.raz` and run as they are. Both |
| 1678 | | -are in the session's scratch space and can be added to `test/bench` |
| 1679 | | -if the proposal goes ahead. |
| 1680 | | - |
| 1681 | | -``` |
| 1682 | | -module MemBench; |
| 1683 | | -import Out, Sys; |
| 1684 | | - |
| 1685 | | -const |
| 1686 | | - Big = 1000000; (* past the caches *) |
| 1687 | | - Small = 1000; (* in L1 *) |
| 1688 | | - Bytes = 16000000; |
| 1689 | | - |
| 1690 | | -type |
| 1691 | | - Node = record next: ^Node; val: INT; end; |
| 1692 | | - H = record i: INT; gen: INT; end; |
| 1693 | | - Slot = record next: H; val: INT; gen: INT; end; |
| 1694 | | - |
| 1695 | | -var |
| 1696 | | - nodes: [Big]Node; |
| 1697 | | - slots: [Big]Slot; |
| 1698 | | - perm: [Big]INT; |
| 1699 | | - bytes: [Bytes]U8; |
| 1700 | | - sink: INT; |
| 1701 | | - |
| 1702 | | -(* A random cycle through the first n nodes, the same in both arrays *) |
| 1703 | | -proc build(n: INT); |
| 1704 | | -var i, j, t: INT; seed: U64; |
| 1705 | | -begin |
| 1706 | | - seed := 7; |
| 1707 | | - for i := 0 to n - 1 do perm[i] := i; end; |
| 1708 | | - for i := n - 1 to 1 by -1 do |
| 1709 | | - seed := seed * 6364136223846793005 + 1442695040888963407; |
| 1710 | | - j := INT(seed shr 33) mod (i + 1); |
| 1711 | | - t := perm[i]; perm[i] := perm[j]; perm[j] := t; |
| 1712 | | - end; |
| 1713 | | - for i := 0 to n - 1 do |
| 1714 | | - j := perm[(i + 1) mod n]; |
| 1715 | | - nodes[perm[i]] := {next: ADR(nodes[j]), val: i}; |
| 1716 | | - slots[perm[i]] := {next: {i: j, gen: 3}, val: i, gen: 3}; |
| 1717 | | - end; |
| 1718 | | -end; |
| 1719 | | - |
| 1720 | | -proc chasePtr(steps: INT): INT; |
| 1721 | | -var p: ^Node; s, k: INT; |
| 1722 | | -begin |
| 1723 | | - p := ADR(nodes[perm[0]]); |
| 1724 | | - for k := 1 to steps do s := s + p^.val; p := p^.next; end; |
| 1725 | | - return s; |
| 1726 | | -end; |
| 1727 | | - |
| 1728 | | -(* As a checked Pool.get would: the generation, and the index *) |
| 1729 | | -proc chaseHandle(steps: INT): INT; |
| 1730 | | -var h: H; s, k: INT; |
| 1731 | | -begin |
| 1732 | | - h := {i: perm[0], gen: 3}; |
| 1733 | | - for k := 1 to steps do |
| 1734 | | - if slots[h.i].gen # h.gen then Sys.exit(3); end; |
| 1735 | | - s := s + slots[h.i].val; |
| 1736 | | - h := slots[h.i].next; |
| 1737 | | - end; |
| 1738 | | - return s; |
| 1739 | | -end; |
| 1740 | | - |
| 1741 | | -proc sumPtr(p: ^U8; n, reps: INT): INT; |
| 1742 | | -var s, i, r: INT; |
| 1743 | | -begin |
| 1744 | | - for r := 1 to reps do |
| 1745 | | - for i := 0 to n - 1 do s := s + INT(p[i]); end; |
| 1746 | | - end; |
| 1747 | | - return s; |
| 1748 | | -end; |
| 1749 | | - |
| 1750 | | -proc sumSlice(b: []U8; reps: INT): INT; |
| 1751 | | -var s, i, r: INT; |
| 1752 | | -begin |
| 1753 | | - for r := 1 to reps do |
| 1754 | | - for i := 0 to LEN(b) - 1 do s := s + INT(b[i]); end; |
| 1755 | | - end; |
| 1756 | | - return s; |
| 1757 | | -end; |
| 1758 | | -``` |
| 1759 | | - |
| 1760 | | -`main` builds `Big`, times each chase for 100,000,000 steps, builds |
| 1761 | | -`Small`, times each for 500,000,000, then the sums: 16,000,000 bytes 50 |
| 1762 | | -times and 4,000 bytes 200,000 times. `GenBench.raz` is the same chase |
| 1763 | | -with 32-byte records on both sides: |
| 1764 | | - |
| 1765 | | -``` |
| 1766 | | -type |
| 1767 | | - Node = record next: ^Node; val, pad1, pad2: INT; end; |
| 1768 | | - GP = record p: ^GNode; gen: INT; end; |
| 1769 | | - GNode = record gen: INT; next: GP; val: INT; end; |
| 1770 | | - |
| 1771 | | -proc chaseGen(steps: INT): INT; |
| 1772 | | -var g: GP; s, k: INT; |
| 1773 | | -begin |
| 1774 | | - g := {p: ADR(gnodes[perm[0]]), gen: 5}; |
| 1775 | | - for k := 1 to steps do |
| 1776 | | - if g.p^.gen # g.gen then Sys.exit(3); end; |
| 1777 | | - s := s + g.p^.val; |
| 1778 | | - g := g.p^.next; |
| 1779 | | - end; |
| 1780 | | - return s; |
| 1781 | | -end; |
| 1782 | | -``` |
| 1783 | | - |
| 1784 | | -The compiler's instruction counts: `valgrind --tool=callgrind raz -I src |
| 1785 | | --I build/src -o /dev/null src/Raz.raz`, the same compiler built twice |
| 1786 | | -from `src/`, once with `Scan.State.buf: ^U8` and once with `[]U8`. The |
| 1787 | | -five lines changed were the field's type, `grab(n + 1)[0..n + 1]`, |
| 1788 | | -`Diag.addFile(path, PTR(cur.buf), n)`, the local `buf` in `next`, and |
| 1789 | | -`intern(PTR(buf) + start, p - start)`. The second compiler builds |
| 1790 | | -itself. |
| 1791 | | - |
| 1792 | | -## Appendix 3: the five programs of section 1 |
| 1793 | | - |
| 1794 | | -``` |
| 1795 | | -module SelfAppend; |
| 1796 | | -import Buf, Heap, Out; |
| 1797 | | - |
| 1798 | | -proc main*; |
| 1799 | | -var b: Buf.Buf; i: INT; |
| 1800 | | -begin |
| 1801 | | - Buf.init(b, Heap.heap); |
| 1802 | | - for i := 1 to 64 do Buf.add(b, 'a'); end; (* full: 64 of 64 *) |
| 1803 | | - Buf.str(b, Buf.bytes(b)); (* doubles it: or should *) |
| 1804 | | - Out.str(Buf.bytes(b)[56..80]); Out.ln; |
| 1805 | | -end; |
| 1806 | | - |
| 1807 | | -end SelfAppend. |
| 1808 | | -``` |
| 1809 | | - |
| 1810 | | -Prints `aaaaaaaaaaaaaaaaaaaaaaaa`, status 0: right, by luck. |
| 1811 | | - |
| 1812 | | -``` |
| 1813 | | -module Stale; |
| 1814 | | -import Vec := Vec(INT), Heap, Out; |
| 1815 | | - |
| 1816 | | -proc main*; |
| 1817 | | -var v: Vec.Vec; first: []INT; i: INT; p: ^INT; |
| 1818 | | -begin |
| 1819 | | - Vec.init(v, Heap.heap); |
| 1820 | | - for i := 1 to 16 do Vec.push(v, i); end; |
| 1821 | | - first := Vec.all(v); (* good until v next grows *) |
| 1822 | | - p := Vec.add(v); (* grows: first now points at freed memory *) |
| 1823 | | - p^ := 99; |
| 1824 | | - for i := 0 to 15 do Vec.push(v, 1000 + i); end; (* grows again: p is stale *) |
| 1825 | | - p^ := -1; (* writes into a block the heap has taken back *) |
| 1826 | | - Out.int(first[0]); Out.str(" "); Out.int(first[1]); Out.ln; |
| 1827 | | -end; |
| 1828 | | - |
| 1829 | | -end Stale. |
| 1830 | | -``` |
| 1831 | | - |
| 1832 | | -Prints `1 2`, status 0: it read and wrote freed memory, and looks right. |
| 1833 | | - |
| 1834 | | -``` |
| 1835 | | -module Escape; |
| 1836 | | -import Out; |
| 1837 | | - |
| 1838 | | -type Hex = [16]U8; |
| 1839 | | - |
| 1840 | | -proc head(var h: Hex): []U8; |
| 1841 | | -begin |
| 1842 | | - return h[0..8]; (* allowed: h is the caller's *) |
| 1843 | | -end; |
| 1844 | | - |
| 1845 | | -proc short: []U8; |
| 1846 | | -var h: Hex; i: INT; |
| 1847 | | -begin |
| 1848 | | - for i := 0 to 15 do h[i] := 'x'; end; |
| 1849 | | - return head(h); (* a slice of short's frame: not caught *) |
| 1850 | | -end; |
| 1851 | | - |
| 1852 | | -proc noise; |
| 1853 | | -var junk: [64]U8; i: INT; |
| 1854 | | -begin |
| 1855 | | - for i := 0 to 63 do junk[i] := '#'; end; |
| 1856 | | -end; |
| 1857 | | - |
| 1858 | | -proc main*; |
| 1859 | | -var s: []U8; |
| 1860 | | -begin |
| 1861 | | - s := short(); |
| 1862 | | - noise; |
| 1863 | | - Out.str(s); Out.ln; |
| 1864 | | -end; |
| 1865 | | - |
| 1866 | | -end Escape. |
| 1867 | | -``` |
| 1868 | | - |
| 1869 | | -Prints `########`, status 0: `noise`'s bytes, read through a slice of |
| 1870 | | -a dead frame. |
| 1871 | | - |
| 1872 | | -``` |
| 1873 | | -module Kept; |
| 1874 | | -import Names := Map([]U8, INT, Str.hash, Str.eq), Str, Heap, Out; |
| 1875 | | - |
| 1876 | | -var table: Names.Map; |
| 1877 | | - |
| 1878 | | -proc remember(n: INT); |
| 1879 | | -var buf: [8]U8; |
| 1880 | | -begin |
| 1881 | | - buf := "name-000"; |
| 1882 | | - buf[7] := U8('0' + n); |
| 1883 | | - _ := Names.put(table, buf[0..8], n); (* the map keeps a slice of this frame *) |
| 1884 | | -end; |
| 1885 | | - |
| 1886 | | -proc main*; |
| 1887 | | -var v: INT; ok: BOOL; |
| 1888 | | -begin |
| 1889 | | - Names.init(table, Heap.heap); |
| 1890 | | - remember(1); |
| 1891 | | - remember(2); |
| 1892 | | - v, ok := Names.get(table, "name-001"); |
| 1893 | | - Out.str("name-001: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; |
| 1894 | | - v, ok := Names.get(table, "name-002"); |
| 1895 | | - Out.str("name-002: "); if ok then Out.int(v); else Out.str("missing"); end; Out.ln; |
| 1896 | | -end; |
| 1897 | | - |
| 1898 | | -end Kept. |
| 1899 | | -``` |
| 1900 | | - |
| 1901 | | -Prints `name-001: missing` and `name-002: missing`, status 0. |
| 1902 | | - |
| 1903 | | -``` |
| 1904 | | -module Temp; |
| 1905 | | -import Out; |
| 1906 | | - |
| 1907 | | -type Name = [8]U8; |
| 1908 | | - |
| 1909 | | -proc named(c: U8): Name; |
| 1910 | | -var n: Name; |
| 1911 | | -begin |
| 1912 | | - n := "name-..."; n[7] := c; |
| 1913 | | - return n; |
| 1914 | | -end; |
| 1915 | | - |
| 1916 | | -proc main*; |
| 1917 | | -var a, b: []U8; |
| 1918 | | -begin |
| 1919 | | - a := named('a')[0..8]; (* the array lives to the end of the statement *) |
| 1920 | | - b := named('b')[0..8]; |
| 1921 | | - Out.str(a); Out.str(" "); Out.str(b); Out.ln; |
| 1922 | | -end; |
| 1923 | | - |
| 1924 | | -end Temp. |
| 1925 | | -``` |
| 1926 | | - |
| 1927 | | -Prints `name-..b`, a space and eight bytes of junk, status 0. |
| 1928 | | - |
| 1929 | | ---- |
| 1930 | | - |
| 1931 | | -## Appendix 4: adversarial review, soundness |
| 1932 | | - |
| 1933 | | -This appendix tests section 3's promise against parts A to F, read as |
| 1934 | | -written. It finds 12 ways a program of safe modules and the library, as |
| 1935 | | -section 17 would change it, still breaks the guarantee; 7 ambiguities |
| 1936 | | -or contradictions; and 3 problems with checking or building the rules |
| 1937 | | -in one pass. Two of the breaks are in today's language too, and the |
| 1938 | | -proposal leaves them as they are: a variant changed while `match` names |
| 1939 | | -its fields, and an `ERROR` written through a view. Both were run with |
| 1940 | | -today's compiler. The rest follow from the text of the proposal. |
| 1941 | | - |
| 1942 | | -### Breaks the guarantee |
| 1943 | | - |
| 1944 | | -**1. A variant changed under its `match`.** |
| 1945 | | - |
| 1946 | | -``` |
| 1947 | | -type V = variant ptr(p: ^INT); num(n: INT); end; |
| 1948 | | -var v: V; (* a module variable *) |
| 1949 | | -proc flip(a: INT); begin v := num(a); end; |
| 1950 | | -... |
| 1951 | | -v := ptr(q); |
| 1952 | | -match v of |
| 1953 | | -| ptr(p): flip(h.(INT) + 8); p^ := 1000000; (* p reads num's bytes as a pointer *) |
| 1954 | | -| num(_n): |
| 1955 | | -end; |
| 1956 | | -``` |
| 1957 | | - |
| 1958 | | -Run today, this sets the length of a heap slice, `h^.s`, to 1,000,000. |
| 1959 | | -Every operation in it stays safe under 5.1: the view only reads a |
| 1960 | | -pointer's bytes as an integer (10.3), and that is allowed. 7.4 says the |
| 1961 | | -names stand for the fields of `s` itself, and nothing stops the arm, a |
| 1962 | | -call it makes, or an alias (`var` parameter, pointer) from giving `s` |
| 1963 | | -another case. 10.4 covers only lending. Fix: in a safe module, an arm's |
| 1964 | | -names are a copy of the fields whenever the arm could change the |
| 1965 | | -variable (any call, any store through a pointer or `var` parameter, or |
| 1966 | | -the variable named), or each use of a name checks the tag first. Cost: |
| 1967 | | -a compare per use, or a copy per `match`, and one line less of 7.4. |
| 1968 | | - |
| 1969 | | -**2. An `ERROR` written through a view.** `e.(INT) := h.(INT); |
| 1970 | | -Out.str(MSG(e))` printed 64 KB of memory today. `ERROR` is an address |
| 1971 | | -(5.8), but the list in 5.1 and 10.3 of what may not be written through |
| 1972 | | -a view (pointer, procedure, slice, variant, enumeration, `BOOL`) leaves |
| 1973 | | -it out. Fix: add `ERROR`, and better, state the rule the other way round: |
| 1974 | | -a view may write only a variable made wholly of the types 6.9 allows as |
| 1975 | | -a view's `T`. Cost: none. |
| 1976 | | - |
| 1977 | | -**3. A safe module makes its own allocator.** `Mem.Allocator`'s fields |
| 1978 | | -are exported. 5.2 lets a safe procedure stand where an `unsafe proc` |
| 1979 | | -type is wanted. So a safe module can build `{alloc: mine, free: none}` |
| 1980 | | -and pass it to `NEW`. Its `mine` can return the same lasting `^U8` for |
| 1981 | | -every call, or a 1-byte block for a large `T`. Then `NEW` zeroes and |
| 1982 | | -hands out memory that two pointers of different types share, or that |
| 1983 | | -runs past its block. The same goes for copying `Arena.allocator(ar)^`, |
| 1984 | | -or `ar.base`, into a heap record and passing that: Arena's `alloc` |
| 1985 | | -casts its argument to `^Arena`, and reads past the copy. The trust of |
| 1986 | | -5.3 is broken by code the trusted module calls back. Fix: a field of an |
| 1987 | | -`unsafe proc` type may be set only in an unsafe module, and |
| 1988 | | -`Mem.Allocator` becomes a type safe code can't build or copy (its |
| 1989 | | -fields unexported, copying refused as for an owner). Cost: a rule in |
| 1990 | | -5.2 and in 7.6. |
| 1991 | | - |
| 1992 | | -**4. Procedures that take an allocator report arena memory as lasting.** |
| 1993 | | -`Mem.alloc`, `Str.copy` and the result of `NEW` through such a call |
| 1994 | | -carry no `ret` on their allocator, so by 6.1 what they return is |
| 1995 | | -lasting. Given `Arena.allocator(ar)`, they return arena memory. After |
| 1996 | | -`Arena.reset`, that memory goes to the next `NEW` of another type. The |
| 1997 | | -same holds for `Buf.init`, `Vec.init`, `Map.init`, `List.init` and |
| 1998 | | -`Pool.init`, which keep the allocator in the owner without a `keep` |
| 1999 | | -mark, against obligation 3. Fix: `ret a` on every procedure whose |
| 2000 | | -result comes from `a`, and `keep a` on every `init`. Then an arena's |
| 2001 | | -allocator can't be kept by a container, and what `Str.copy` gives from |
| 2002 | | -it is lent by the arena. Cost: marks on about ten headings. |
| 2003 | | - |
| 2004 | | -**5. Storing a lent slice in an element of a slice.** 6.2 allows a |
| 2005 | | -lent value to be "held in a local variable, or in a field or element of |
| 2006 | | -one". An element of a local slice is someone else's memory: |
| 2007 | | - |
| 2008 | | -``` |
| 2009 | | -proc stash(s: [][]U8); (* s: the caller's array, or a Vec's block *) |
| 2010 | | -var buf: [8]U8; |
| 2011 | | -begin s[0] := buf[0..8]; end; (* allowed by 6.2's words; dangles after return *) |
| 2012 | | -``` |
| 2013 | | - |
| 2014 | | -PROPOSALS' "outliving the call" lists `p^.f` and `p^[i]` but not |
| 2015 | | -`s[i]`. Fix: what is reached through a slice is a place that outlives |
| 2016 | | -the call, as through a pointer, unless the slice is lent only by the |
| 2017 | | -frame. Cost: a few false alarms on local slices of local arrays. |
| 2018 | | - |
| 2019 | | -**6. Only a call's result is counted.** 7.3 counts "where a call |
| 2020 | | -returns a reference lent by an owner". `t := s`, `t := s[1..3]` and |
| 2021 | | -`u := t^[0..10]`, with `s` held, are not calls. Read as written, `t` |
| 2022 | | -gets no hold. Then `s := []` lets the count fall to zero while `t` |
| 2023 | | -still points into the block, and the next growth frees it. Fix: every |
| 2024 | | -assignment to a local of a value lent by an owner sets that local's |
| 2025 | | -holds, whatever the expression. Cost: none beyond what was meant. |
| 2026 | | - |
| 2027 | | -**7. One hold, two owners.** A value may be lent by two owners at once: |
| 2028 | | -`Buf.bytes(all[0])` with `all := Bufs.all(v)`; `NEW(t, al)` with `T` an |
| 2029 | | -owner, then `Buf.bytes(t^)`; `pick(Buf.bytes(a), Buf.bytes(b))` with |
| 2030 | | -two `ret` parameters. 7.3 gives a local one hidden word. Whichever owner |
| 2031 | | -it leaves uncounted can free or move the memory: the outer `Vec` frees |
| 2032 | | -the block that holds the inner `Buf`, and the hold then lowers a word of |
| 2033 | | -freed memory. Fix: a hold per owner a value can be lent by, which the |
| 2034 | | -compiler knows from the heading. Or forbid an owner reached through an |
| 2035 | | -owner-lent value. Cost: a word per extra owner. The second choice |
| 2036 | | -forbids `Vec(Buf.Buf)` and `Pool` of owners in practice. |
| 2037 | | - |
| 2038 | | -**8. Library containers copy owners.** 7.6 forbids copies only in safe |
| 2039 | | -modules. `Vec`, `Pool`, `Map` and `List` are unsafe and generic, so |
| 2040 | | -they can't know that `T` is an owner. `Pool.get` returns a copy of a |
| 2041 | | -slot. `Vec`'s growth copies every element into the new block, and, with |
| 2042 | | -a lend held, keeps the old copy alive too. `Vec.pop`, `List.pop` and |
| 2043 | | -`Map.get` copy out. Two `Buf`s then own one block: one grows and frees |
| 2044 | | -it, and the other reads it. 7.6's rule also misses the result of a call |
| 2045 | | -(`b := Pools.get(p, h)` isn't "assigned from another variable"). Fix: a |
| 2046 | | -generic module's type parameter may be an owner only if the module says |
| 2047 | | -it takes owners. Those modules move owners, never copy them, and |
| 2048 | | -`get` is refused for them. Cost: a mark on generic parameters, and |
| 2049 | | -`Pool` and `Vec` written for both cases. |
| 2050 | | - |
| 2051 | | -**9. Other routes that copy or overwrite an owner.** None of these is in |
| 2052 | | -7.6's list: |
| 2053 | | - |
| 2054 | | -- `COPY(y, x)` on arrays of owners; |
| 2055 | | -- `match` on another module's variable, which today names fields of a |
| 2056 | | - copy (confirmed by running it), and so counts on the copy; |
| 2057 | | -- a variant case built from an owner, `has(b)`, which isn't plainly |
| 2058 | | - "a literal"; |
| 2059 | | -- `b := {}`, `x^ := {}`, and `Pool.add(p, {})`, which 7.6 allows, and |
| 2060 | | - `Buf.init(b, a)` on a `Buf` with a lend held. Each sets `lends` to |
| 2061 | | - zero under a hold. The hold's later let-go makes it -1. The next lend |
| 2062 | | - brings it back to 0 while that slice is held, and the next growth |
| 2063 | | - frees the block under it. |
| 2064 | | - |
| 2065 | | -Fix: state the rule as "a value of a type that holds an owner is never |
| 2066 | | -copied or overwritten in a safe module, nor by the library while its |
| 2067 | | -`lends` is above zero". Add `COPY`, case construction, `match` on a |
| 2068 | | -copy, and `{}` over a variable that isn't already empty (or make |
| 2069 | | -`init` and `{}` stop when `lends` isn't zero). Cost: a few rules and a |
| 2070 | | -test in each `init`. |
| 2071 | | - |
| 2072 | | -**10. `take`, `swap` and the count.** 7.6 names `Buf.take(var from, to)` |
| 2073 | | -and `Buf.swap` and says nothing of `lends`. Holds point at `from.lends`. |
| 2074 | | -After the move, `to` owns the block with a count of 0, and frees it at |
| 2075 | | -its next growth while the slices are held. Fix: `take` and `swap` stop |
| 2076 | | -when either owner's `lends` is above zero. Cost: a compare each. Add it |
| 2077 | | -to obligation 2. |
| 2078 | | - |
| 2079 | | -**11. Letting go of a hold while a `match` names its fields.** |
| 2080 | | - |
| 2081 | | -``` |
| 2082 | | -p := Vs.add(v); p^ := a("abc"); |
| 2083 | | -match p^ of |
| 2084 | | -| a(s): p := nil; grow(v); Out.str(s); (* s names a field of a freed block *) |
| 2085 | | -| b: |
| 2086 | | -end; |
| 2087 | | -``` |
| 2088 | | - |
| 2089 | | -The names stand for the variable in place, and assigning `p` lets its |
| 2090 | | -hold go. Fix: a `match` on a lent variable takes its own count for the |
| 2091 | | -whole statement. Cost: an add and a subtract per such `match`. |
| 2092 | | - |
| 2093 | | -**12. The library breaks its own obligations.** Section 17 leaves these |
| 2094 | | -as they are, and each lets a safe program reach freed memory: |
| 2095 | | - |
| 2096 | | -- `List.head*` and `Node.next*` are exported, against obligation 4. |
| 2097 | | - `n := l.head; List.pop(l); n^.val` reads a freed node. |
| 2098 | | -- `Thread.join` unmaps the mapping that holds the `Thread` record. The |
| 2099 | | - `^Thread` that `Task.spawn` returns stays "lasting", and a second |
| 2100 | | - `join` or a `signal` reads, and unmaps by, whatever the address |
| 2101 | | - holds next. |
| 2102 | | -- Over C, `Sys.nextEntry`'s name points into C's `readdir` buffer, |
| 2103 | | - which `closeDir` frees. `Dir` is no owner, so nothing counts it. A |
| 2104 | | - `nextEntry` or `closeDir` after `closeDir` hands C a freed `DIR`. |
| 2105 | | -- Over musl, `Sys.env`'s "lasting" result can be freed by a later |
| 2106 | | - `setEnv` of the same name, since musl frees the strings it made. |
| 2107 | | -- `Names(V)`'s procedures that return a key must be `ret`, or `remove` |
| 2108 | | - frees what they gave. The proposal doesn't give its headings. |
| 2109 | | - |
| 2110 | | -Fix: unexport `List`'s pointers and give an iterator that lends; |
| 2111 | | -`Task` returns an owner handle that `join` takes by `var` and empties; |
| 2112 | | -`Dir` an owner; `env` copied into lasting memory over C. Cost: small, |
| 2113 | | -but it shows that obligations 1 to 5 need an audit of each module, not |
| 2114 | | -only the marks of section 17. |
| 2115 | | - |
| 2116 | | -### Ambiguities and contradictions |
| 2117 | | - |
| 2118 | | -**13. Section 3 calls a racing container program safe.** Section 3's |
| 2119 | | -definition counts a program as safe if its threads race "only on |
| 2120 | | -variables of a basic, pointer, procedure or slice type". Two threads |
| 2121 | | -calling `Buf.add` on one `Buf` race only on such fields (`len`, |
| 2122 | | -`data`), so the guarantee claims their behaviour is defined. 9.2 says |
| 2123 | | -it isn't. Fix: put 9.2's "a container's procedures called at once" |
| 2124 | | -into section 3's sentence. |
| 2125 | | - |
| 2126 | | -**14. A slice in a packed record, or in a block aligned to 8.** E.1 |
| 2127 | | -promises one access for every slice. A slice field of a packed record |
| 2128 | | -is read in parts (5.5). `Vec` asks its allocator for 8-byte alignment. |
| 2129 | | -Either tears, or `movdqa` faults on it. Fix: no slice in a packed |
| 2130 | | -record; every allocator call for a type holding a slice asks for 16. |
| 2131 | | - |
| 2132 | | -**15. Returning what an owner inside a parameter lent.** 6.2 forbids |
| 2133 | | -returning a value "lent by an owner", even when the owner is a `ret` |
| 2134 | | -parameter. So `proc bytes2(ret const b: Buf): []U8 begin return |
| 2135 | | -Buf.bytes(b) end` is an error, and 14.2's recommended |
| 2136 | | -`Http.name(ret const m: Message; i): []U8` can't be written. If it is |
| 2137 | | -allowed, a caller of `name` sees only `m`, which is no owner (7.2), and |
| 2138 | | -has no count to raise. Fix: allow it when the `ret` parameter is itself |
| 2139 | | -the owner. For a record that holds owners, the caller raises each of |
| 2140 | | -their counts, or the accessor is refused. |
| 2141 | | - |
| 2142 | | -**16. When the epilogue lets go.** 7.3 says the let-go happens "as a |
| 2143 | | -`defer` would". If it is placed as a `defer` at the assignment, a user |
| 2144 | | -`defer f(b, s)` written before it runs after the let-go, and `f` can |
| 2145 | | -grow `b` and read `s`. Fix: holds are let go after every deferred |
| 2146 | | -statement has run. |
| 2147 | | - |
| 2148 | | -**17. "The end of the statement" for compound statements.** A count |
| 2149 | | -taken in a `while` condition, a `for` bound, an `if` condition or a |
| 2150 | | -`match` head: is it lowered once per evaluation or at the statement's |
| 2151 | | -`end`? Lowered once at `end`, a `while` raises it each round and leaks |
| 2152 | | -counts. Then `done` stops though nothing is held. A `try` that leaves |
| 2153 | | -mid-statement must lower it too. Fix: say per evaluation, and on every |
| 2154 | | -exit. |
| 2155 | | - |
| 2156 | | -**18. Two arms of one rule for `{}`.** 7.6 forbids passing an owner as |
| 2157 | | -a value parameter but allows a literal that leaves it out. So is |
| 2158 | | -`Pool.add(p, {})` allowed? Item 9 shows why the answer matters. |
| 2159 | | - |
| 2160 | | -**19. Writable constants beyond strings.** F.2 covers a string's bytes. |
| 2161 | | -An array constant of variants, enumerations or `BOOL`s may be sliced |
| 2162 | | -(4), and on a target where constants are writable, a compiler that |
| 2163 | | -folds `match Rows[0]` from the constant's case reads fields of another |
| 2164 | | -case. Fix: on such targets, writing any constant through a slice stops |
| 2165 | | -the program, or slices of non-string constants can't be written. |
| 2166 | | - |
| 2167 | | -### One-pass and implementability problems |
| 2168 | | - |
| 2169 | | -**20. A hold must be kept for every reference local.** A local may hold |
| 2170 | | -a lasting value at one assignment and an owner's lend at a later one |
| 2171 | | -(a loop's next round), and one pass doesn't know the later one when it |
| 2172 | | -compiles the earlier. So every assignment to every slice or pointer |
| 2173 | | -local must test and lower a hold, and every copy from one local to |
| 2174 | | -another must pass the hold on. That cost is per assignment, not "per |
| 2175 | | -lend held", and it falls on `src/`'s pointer loops (`o := o^.next`). |
| 2176 | | -Section 13 doesn't count it. Fix: measure it, or let a hold word exist |
| 2177 | | -only for locals declared with a mark (say `lent s: []U8`), checked at |
| 2178 | | -`end`. |
| 2179 | | - |
| 2180 | | -**21. Atomic counts depend on the whole program.** E.5 makes the counts |
| 2181 | | -`lock xadd` "in a program that imports `Thread`". A module compiled |
| 2182 | | -before another module's `import Thread` is read can't know which to |
| 2183 | | -emit, and separate compilation (10) forbids depending on it. Fix: |
| 2184 | | -always `lock`, or read every module's imports first. Cost: about 20 |
| 2185 | | -cycles per lend, or a pass over the import graph. |
| 2186 | | - |
| 2187 | | -**22. Re-entry through the procedures a container is given.** `Map` |
| 2188 | | -calls `hash` and `eq`, `Sort` calls `less`, `Guarded.with` calls its |
| 2189 | | -procedure, and `Rt.atExit` procedures run after a failed check inside |
| 2190 | | -any of these. A safe callback can call `put`, `remove` or `done` on the |
| 2191 | | -same container while its own code is mid-loop: `done` inside `eq` while |
| 2192 | | -`get` probes leaves `slots` nil with an index still in hand. No |
| 2193 | | -obligation in 5.3 speaks of it, and checking the trusted code for every |
| 2194 | | -re-entry is not one pass of anything. Fix: obligation 6, "a module that |
| 2195 | | -calls a procedure given by safe code holds its own `lends` across the |
| 2196 | | -call", so that `done` stops; the library's containers do it. |
| 2197 | | - |
| 2198 | | -### Checked and found covered |
| 2199 | | - |
| 2200 | | -- `Pool.at` across `Pool.free`: the slot keeps its type, so a stale |
| 2201 | | - pointer reads the wrong record of the right type, as 8.2 says. That |
| 2202 | | - holds except for variants (item 1) and owners in slots (items 7 to 9). |
| 2203 | | -- Retired blocks and `reset`: the bytes keep their type; a held slice |
| 2204 | | - sees new contents, safely. |
| 2205 | | -- `var` parameters aliasing: `f(x, x)` with a `done` inside stops on |
| 2206 | | - the count; a callee assigning the caller's held local through `var` |
| 2207 | | - leaves the hold set, which errs on the safe side. |
| 2208 | | -- Holds and threads: a thread raises a count only while it already |
| 2209 | | - holds one, so the count can't pass through zero under another |
| 2210 | | - thread's test. |
| 2211 | | -- `Task.spawn`: `keep x` refuses lent values, and owners can't be |
| 2212 | | - passed by value. |
| 2213 | | -- `a, b := f(x)` and `return f(x)`: each target is checked as a single |
| 2214 | | - assignment. |
| 2215 | | -- A `const` parameter of another module's variable is passed in place |
| 2216 | | - today (run to confirm), so its count lands on the real owner. |
| 2217 | | -- A safe generic module instantiated with an owner: each instance is |
| 2218 | | - checked, so a copy inside it is refused there. |
| 2219 | | - |
| 2220 | | ---- |
| 2221 | | - |
| 2222 | | -## Appendix 5: adversarial review, claims about other languages and hardware |
| 2223 | | - |
| 2224 | | -This appendix checks every claim MEM_PROPOSAL.md makes about other |
| 2225 | | -languages, hardware, research and precedent. Of 44 claims checked, 5 |
| 2226 | | -are wrong, 22 imprecise, 15 correct and 2 unverifiable. None of the |
| 2227 | | -errors breaks the design. Three of them touch it, though: 21.5 leans on |
| 2228 | | -Swift for a cross-thread check that Swift doesn't make; 9.2 says a |
| 2229 | | -slice published with no lock is safe, which fails on ARM; and 11 files |
| 2230 | | -Chrome's BackupRefPtr under debugging heaps, when it is the closest |
| 2231 | | -precedent for part C. Most of the imprecise ones are table cells that |
| 2232 | | -leave out a condition or a newer fact. |
| 2233 | | - |
| 2234 | | -How it was checked: through the session's proxy, which let through only |
| 2235 | | -GitHub-hosted sources (raw.githubusercontent.com) and web search. So |
| 2236 | | -primary sources were read where they live on GitHub (the Go memory |
| 2237 | | -model and spec, the C# standard, swift-evolution, Zig's langref and |
| 2238 | | -library, Fil-C, Chromium, glibc, slotmap, generational-arena, |
| 2239 | | -portable-atomic, GCC's libatomic, the Linux kernel's MTE document, D's |
| 2240 | | -DIPs, CPython). Vendor manuals (Intel SDM, AMD APM, Arm ARM) and the |
| 2241 | | -Modula-3, Ada and Java texts were checked through quotations that web |
| 2242 | | -search returned. Where a manual's section number could not be seen |
| 2243 | | -directly, the entry says so. |
| 2244 | | - |
| 2245 | | -### Wrong |
| 2246 | | - |
| 2247 | | -**W1. Section 21.5: "changes from another thread without the lock stop |
| 2248 | | -the program, as Swift's exclusivity checks do."** |
| 2249 | | -Wrong. Swift's run-time exclusivity checks are not required to see |
| 2250 | | -accesses from other threads, and by design they don't look. SE-0176 |
| 2251 | | -says: "Dynamic enforcement is not required to detect concurrent |
| 2252 | | -conflicting accesses, and we propose that by default it should not |
| 2253 | | -make any effort to do so ... it can track accesses in a thread-local |
| 2254 | | -data structure." Swift leaves races to Thread Sanitizer and, since |
| 2255 | | -Swift 6, to `Sendable` checking at compile time. |
| 2256 | | -Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md (section "Concurrency"). |
| 2257 | | -Correct wording: "... stop the program. Swift's run-time exclusivity |
| 2258 | | -checks don't do this: they track accesses per thread. The nearest |
| 2259 | | -precedents are Go's run-time check for concurrent map writes and |
| 2260 | | -ThreadSanitizer." |
| 2261 | | - |
| 2262 | | -**W2. Section 12, Zig row: "`@ptrCast`, `@intToPtr` anywhere".** |
| 2263 | | -Wrong name. `@intToPtr` was renamed `@ptrFromInt` in Zig 0.11 (2023), |
| 2264 | | -and `@ptrToInt` became `@intFromPtr`. Today's langref has |
| 2265 | | -`@ptrFromInt` (7 uses) and `@intFromPtr` (6), and no `@intToPtr`. |
| 2266 | | -Source: https://raw.githubusercontent.com/ziglang/zig/master/doc/langref.html.in (Zig has since moved to Codeberg; the GitHub copy is the last one mirrored). |
| 2267 | | -Correct wording: "`@ptrCast`, `@ptrFromInt` anywhere". |
| 2268 | | - |
| 2269 | | -**W3. Section 12, "Java, C#" row: forged pointers "none".** |
| 2270 | | -Wrong for C#. C# has real pointers, pointer arithmetic and casts from |
| 2271 | | -integers in `unsafe` code. The same row names C#'s `unsafe` blocks as |
| 2272 | | -its fence, so the row contradicts itself. Also, |
| 2273 | | -`System.Runtime.CompilerServices.Unsafe` and `MemoryMarshal` reinterpret |
| 2274 | | -references with no `unsafe` keyword at all, so the fence has holes. Java |
| 2275 | | -can forge addresses through `sun.misc.Unsafe` (its memory methods were |
| 2276 | | -deprecated for removal in JDK 23, JEP 471) and through the FFM API's |
| 2277 | | -restricted methods, which warn unless `--enable-native-access` is given |
| 2278 | | -(JEP 454 and 472). |
| 2279 | | -Sources: https://github.com/dotnet/csharpstandard (unsafe code chapter); https://mail.openjdk.org/pipermail/jdk-dev/2024-May/008910.html (JEP 471); https://www.infoq.com/news/2024/07/jep-472-restrict-jni-jdk-24. |
| 2280 | | -Correct wording: split the row. Java: "none in the language; |
| 2281 | | -`sun.misc.Unsafe` and FFM restricted methods, behind a flag". C#: "in |
| 2282 | | -`unsafe` code; also the `Unsafe` and `MemoryMarshal` classes, which |
| 2283 | | -need no `unsafe`". |
| 2284 | | - |
| 2285 | | -**W4. Section 9.2, point 1: "A program that hands slices from thread to |
| 2286 | | -thread, publishing a buffer for others to read, is then safe with no |
| 2287 | | -lock."** |
| 2288 | | -Wrong on ARM, and true on x86-64 only if the compiler keeps the stores |
| 2289 | | -in order. Single-copy atomicity means the 16 bytes don't tear. It says |
| 2290 | | -nothing about the order in which other stores are seen. AArch64 is |
| 2291 | | -weakly ordered. A reader can see the new slice and still see old bytes |
| 2292 | | -in the buffer it points at, unless the store is a release (`STLR`, or |
| 2293 | | -`DMB` then `STP`) and the load an acquire. If the buffer was a recycled |
| 2294 | | -heap block, those old bytes may be another type's pointers. That breaks |
| 2295 | | -the type guarantee of section 3, which publication with no lock is |
| 2296 | | -meant to keep. x86-64's TSO keeps store order, so there it holds, |
| 2297 | | -provided the compiler doesn't reorder. |
| 2298 | | -Sources: https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs (needs FEAT_LRCPC3's `LDIAPP`/`STILP`, or barriers, for acquire and release); the Arm ARM's memory model, B2.3. |
| 2299 | | -Correct wording: "... is then safe with no lock on x86-64. On AArch64 a |
| 2300 | | -slice store that publishes is a release and its load an acquire; |
| 2301 | | -appendix A says how." |
| 2302 | | - |
| 2303 | | -**W5. Section 12, "Java, C#" row: "references never tear; `long` may in |
| 2304 | | -Java".** |
| 2305 | | -Wrong by omission for C#, the row's other language. The C# standard |
| 2306 | | -(9.6) promises atomic reads and writes only for `bool`, `char`, the |
| 2307 | | -integer types up to 32 bits, `float` and references. It says "Reads and |
| 2308 | | -writes of other types, including `long`, `ulong`, `double`, and |
| 2309 | | -`decimal`, as well as user-defined types, need not be atomic." So C# |
| 2310 | | -structs tear, and that includes multi-word ones such as `ArraySegment<T>` |
| 2311 | | -and `Memory<T>`. C# stays memory-safe anyway because every array access |
| 2312 | | -is checked again against the array itself. That is worth saying, since |
| 2313 | | -it is the other way out of the torn-slice problem. |
| 2314 | | -Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md#96-atomicity-of-variable-references. |
| 2315 | | -Correct wording: "references never tear; `long` and `double` may (in |
| 2316 | | -C#, structs too), but each array access is checked again". |
| 2317 | | - |
| 2318 | | -### Imprecise |
| 2319 | | - |
| 2320 | | -**I1. Section 9.2: "`movdqa`, which Intel and AMD guarantee single-copy |
| 2321 | | -atomic on processors with AVX"; section 4: "none on x86-64 with AVX".** |
| 2322 | | -Right in substance, but conditions are missing. Intel's SDM Vol. 3A, |
| 2323 | | -"Guaranteed Atomic Operations" (section 9.1.1 in the editions that GCC |
| 2324 | | -and Microsoft's STL quote; numbering shifts between editions), says: |
| 2325 | | -"Processors that enumerate support for Intel AVX (by setting the |
| 2326 | | -feature flag CPUID.01H:ECX.AVX[bit 28]) guarantee that the 16-byte |
| 2327 | | -memory operations performed by the following instructions will always |
| 2328 | | -be carried out atomically: MOVAPD, MOVAPS, and MOVDQA; VMOVAPD, |
| 2329 | | -VMOVAPS, and VMOVDQA when encoded with VEX.128; VMOVAPD, VMOVAPS, |
| 2330 | | -VMOVDQA32, and VMOVDQA64 when encoded with EVEX.128 and k0 (masking |
| 2331 | | -disabled)", with the operands 16-byte aligned. AMD's APM Vol. 2 |
| 2332 | | -(Access Atomicity; I couldn't see the section number) is broader in one |
| 2333 | | -way and narrower in another: "Processors that report CPUID |
| 2334 | | -Fn0000_0001_ECX[AVX](bit 28) = 1 extend the atomicity for cacheable, |
| 2335 | | -naturally-aligned single loads or stores from a quadword to a double |
| 2336 | | -quadword." So AMD's covers any aligned 16-byte load or store, but only |
| 2337 | | -to cacheable memory. Neither promise belongs to "x86-64 with AVX" in |
| 2338 | | -general. GCC's libatomic trusts it only on Intel, AMD, Zhaoxin and |
| 2339 | | -newer Centaur parts, and clears AVX for other vendors: "We don't have |
| 2340 | | -a guarantee from vendors of other CPUs with AVX, like VIA." |
| 2341 | | -"Single-copy atomic" is Arm's term; Intel says "carried out |
| 2342 | | -atomically". |
| 2343 | | -Sources: https://gcc.gnu.org/pipermail/gcc-patches/2022-February/590960.html (PR104688, quoting the SDM); https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/init.c; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/x86_64.rs ("Intel, AMD, and Zhaoxin officially guarantee this behavior (VIA has not responded)"); https://github.com/microsoft/STL/issues/4480. |
| 2344 | | -Correct wording: "moved with `movdqa` from a 16-byte-aligned address. |
| 2345 | | -Intel (SDM Vol. 3A, Guaranteed Atomic Operations) and AMD (APM Vol. 2, |
| 2346 | | -Access Atomicity, for cacheable memory) guarantee this atomic on |
| 2347 | | -processors that report AVX, and so does Zhaoxin. Other vendors' AVX |
| 2348 | | -parts take the fallback." |
| 2349 | | - |
| 2350 | | -**I2. Section 9.2: "ARMv8.4 has 16-byte atomic `LDP`/`STP` |
| 2351 | | -(FEAT_LSE2)".** |
| 2352 | | -True, but the conditions and the reach are missing. FEAT_LSE2 is |
| 2353 | | -optional from Armv8.2 and mandatory from Armv8.4. The Arm ARM (DDI |
| 2354 | | -0487, B2.2.1.1, as quoted on LKML) makes LDP/LDNP/STP of two 64-bit |
| 2355 | | -registers single-copy atomic only when the access is 16-byte aligned |
| 2356 | | -and goes to Inner Write-Back, Outer Write-Back Normal cacheable memory. |
| 2357 | | -Many 64-bit Arm machines in use don't have it: Cortex-A72 (Raspberry |
| 2358 | | -Pi 4), Cortex-A76 (Pi 5), Neoverse N1 (AWS Graviton2, Ampere Altra). |
| 2359 | | -They need `LDXP`/`STXP` loops (Armv8.0) or `CASP` (FEAT_LSE, Armv8.1). |
| 2360 | | -Sources: https://lkml.iu.edu/2511.1/09040.html; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs ("LDP/STP: load/store (if Armv8.4 FEAT_LSE2 (optional from Armv8.2, mandatory from Armv8.4) is available)"). |
| 2361 | | -Correct wording: "With FEAT_LSE2 (mandatory from Armv8.4) an aligned |
| 2362 | | -16-byte `LDP`/`STP` to normal cacheable memory is single-copy atomic. |
| 2363 | | -Earlier cores use `LDXP`/`STXP` or `CASP`." |
| 2364 | | - |
| 2365 | | -**I3. Section 9.2: "On x86-64 without AVX, the implementation uses |
| 2366 | | -`lock cmpxchg16b`".** |
| 2367 | | -Works, with three costs left unsaid. First, CMPXCHG16B (CPUID CX16) is |
| 2368 | | -not in the x86-64 baseline (x86-64-v1): the first AMD64 processors |
| 2369 | | -lack it. Second, a load done as `lock cmpxchg16b` writes the line. So |
| 2370 | | -it faults on read-only pages, needs the memory to be writable (as |
| 2371 | | -portable-atomic's safety comments say), and makes readers contend with |
| 2372 | | -one another. libatomic: "Since load and store are implemented with |
| 2373 | | -CAS, they are not fast." Third, a store needs a CAS loop. Raz keeps |
| 2374 | | -slice constants, `[]` among them, in read-only data. The compiler would |
| 2375 | | -have to know those are never raced and read them plainly. |
| 2376 | | -Sources: https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/host-config.h; portable-atomic's x86_64.rs, as above. |
| 2377 | | - |
| 2378 | | -**I4. Section 13.3, row E: "none: two 8-byte moves become one 16-byte |
| 2379 | | -one".** |
| 2380 | | -Not free when the slice goes to or from general registers. That is |
| 2381 | | -the usual case, since raz returns a slice in rax and rdx. A 16-byte |
| 2382 | | -load into an XMM register then needs `movq` plus `pextrq` (or a shuffle |
| 2383 | | -and `movq`) to split it, and a store needs `movq` plus `pinsrq` or |
| 2384 | | -`punpcklqdq` to join it: two to three more uops, and a few cycles of |
| 2385 | | -latency. `pextrq` and `pinsrq` are SSE4.1, which is not baseline |
| 2386 | | -x86-64. This is the machine's cost, and it should be measured like the |
| 2387 | | -others. |
| 2388 | | -Correct wording: "a load or store of a slice through an XMM register: |
| 2389 | | -one or two more instructions where its words go to or from general |
| 2390 | | -registers; records holding slices may grow by padding to 16." |
| 2391 | | - |
| 2392 | | -**I5. Section 7.5: "`inc qword [r]` ... about two cycles each ... `lock |
| 2393 | | -xadd`, about 20 cycles".** |
| 2394 | | -Rough. On Intel, an uncontended `lock` read-modify-write measures about |
| 2395 | | -18 cycles (uops.info, Skylake). On recent AMD cores it is lower. It is |
| 2396 | | -a full barrier, and under contention, with the line bouncing between |
| 2397 | | -cores, it costs hundreds of cycles. That is the case that matters for |
| 2398 | | -two threads lending from one locked `Buf`. A memory-destination `inc` |
| 2399 | | -has a throughput near one a cycle, but about five to six cycles of |
| 2400 | | -latency when chained through store forwarding. |
| 2401 | | -Sources: https://uops.info/html-instr/INC_LOCK_M32.html; https://www.agner.org/optimize/instruction_tables.pdf. |
| 2402 | | -Correct wording: "... `lock xadd`, about 20 cycles uncontended on |
| 2403 | | -Intel, and far more when threads contend for one owner". |
| 2404 | | - |
| 2405 | | -**I6. Section 12, Zig row: "the debug allocator finds use after free and |
| 2406 | | -double frees at run time; nothing in release".** |
| 2407 | | -Partly. `std.heap.DebugAllocator` (renamed from `GeneralPurposeAllocator` |
| 2408 | | -in 0.14.0) lists "Double free detection" and "Leak detection, with |
| 2409 | | -stack traces". It doesn't detect use after free. It "Never reuses |
| 2410 | | -memory addresses" and gives freed pages back "so that it causes page |
| 2411 | | -faults when used", and in safe modes freed memory reads as `0xaa`. So |
| 2412 | | -a use after free may fault or read junk, and nothing reports it as |
| 2413 | | -such. The allocator is chosen by the program, not by the build mode: |
| 2414 | | -it works in ReleaseSafe too. |
| 2415 | | -Source: https://raw.githubusercontent.com/ziglang/zig/master/lib/std/heap/debug_allocator.zig (header comment). |
| 2416 | | -Correct wording: "the debug allocator finds double frees and leaks, and |
| 2417 | | -never reuses addresses, so a use after free tends to fault; a program |
| 2418 | | -chooses it, usually in Debug". |
| 2419 | | - |
| 2420 | | -**I7. Section 12, "C++, hardened" row: "hardened `std` containers; |
| 2421 | | -`-fbounds-safety` for C (clang)".** |
| 2422 | | -This mixes two things. `-fbounds-safety` is a C extension, not C++ |
| 2423 | | -hardening. Apple designed it and ships it in Apple's clang. Upstream, |
| 2424 | | -it is "being incrementally upstreamed", behind |
| 2425 | | -`-fexperimental-bounds-safety`. On the C++ side, the newer fact is |
| 2426 | | -missing: C++26 standardizes library hardening (P3471, adopted at |
| 2427 | | -Hagenberg, February 2025), on top of libc++'s hardening modes and |
| 2428 | | -libstdc++'s `_GLIBCXX_ASSERTIONS`. |
| 2429 | | -Sources: https://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20240513/579251.html; https://clang.llvm.org/docs/BoundsSafetyImplPlans.html; https://open-std.org/JTC1/SC22/WG21/docs/papers/2025/p3471r4.html. |
| 2430 | | -Correct wording: C row: "Spatial: none; Apple's `-fbounds-safety` |
| 2431 | | -extension (clang, partly upstream) adds checked bounds". C++ row: |
| 2432 | | -"hardened standard library (libc++, libstdc++; standard in C++26 by |
| 2433 | | -P3471)". |
| 2434 | | - |
| 2435 | | -**I8. Section 12, "Odin, Hare, C3" row: spatial "checked".** |
| 2436 | | -True by default for all three, but each can turn it off. C3 checks |
| 2437 | | -only in its safe (debug) mode, and in fast builds an out-of-bounds index |
| 2438 | | -is undefined. Hare checks every slice and array access, but its `[*]T` |
| 2439 | | -arrays are unchecked. Odin has `#no_bounds_check` and |
| 2440 | | -`-no-bounds-check`. |
| 2441 | | -Sources: https://c3-lang.org/language-rules/undefined-behaviour/; https://harelang.org/blog/2022-06-21-safety-features/. |
| 2442 | | -Correct wording: "checked by default (C3: in safe builds only); each can |
| 2443 | | -turn it off". |
| 2444 | | - |
| 2445 | | -**I9. Section 12, Swift row: fence "`Unsafe` in names".** |
| 2446 | | -Out of date. SE-0458, "Opt-in Strict Memory Safety Checking", is |
| 2447 | | -implemented in Swift 6.2. It adds `-strict-memory-safety`, an `@unsafe` |
| 2448 | | -attribute, a `@safe` attribute for a declaration that is "actually |
| 2449 | | -safe to use" though its signature holds unsafe types, and an `unsafe` |
| 2450 | | -expression "much like `try` and `await`". That is a real fence, and |
| 2451 | | -`@safe` is section 5.3's trust in a safe interface. |
| 2452 | | -Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0458-strict-memory-safety.md. |
| 2453 | | -Correct wording: "`Unsafe` in names; since Swift 6.2, an opt-in |
| 2454 | | -checked fence (`@unsafe`, `@safe`, `unsafe` expressions)". |
| 2455 | | - |
| 2456 | | -**I10. Section 12, Ada row: races "protected objects".** |
| 2457 | | -Protected objects are the tool, not the guarantee. In Ada, two |
| 2458 | | -unsynchronized conflicting uses of a shared variable are erroneous (RM |
| 2459 | | -9.10): "The execution of two concurrent actions is erroneous if the |
| 2460 | | -actions make conflicting uses of a shared variable." SPARK, under the |
| 2461 | | -Ravenscar and Jorvik profiles, proves there are no data races. |
| 2462 | | -Source: https://ada-lang.io/docs/arm/AA-9/AA-9.10/. |
| 2463 | | -Correct wording: "erroneous unless synchronized (protected objects, |
| 2464 | | -atomics); SPARK proves their absence". |
| 2465 | | - |
| 2466 | | -**I11. Section 12: "Ada's accessibility levels are part B's frame, |
| 2467 | | -parameters and lasting memory, nearly exactly."** |
| 2468 | | -Overstated. Ada's levels (RM 3.10.2) attach mainly to where an access |
| 2469 | | -type is declared. A library-level access type can't designate a |
| 2470 | | -deeper object. Most checks are static, but those for anonymous access |
| 2471 | | -parameters and some others run at run time and raise `Program_Error`. |
| 2472 | | -There is no notion of "lent by this parameter" for a result. The |
| 2473 | | -closest match to part B is C#'s ref-safety rules: their "safe-context" |
| 2474 | | -values are "declaration-block", "function-member" and |
| 2475 | | -"caller-context". Those are part B's frame, parameters and lasting |
| 2476 | | -nearly one for one. C# 11 adds `scoped` and `[UnscopedRef]`, which play |
| 2477 | | -the roles of `ret` and `keep`. |
| 2478 | | -Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md. |
| 2479 | | -Correct wording: "Ada's accessibility levels are the idea; C#'s |
| 2480 | | -safe-contexts (declaration block, function member, caller) are part |
| 2481 | | -B's three lenders nearly exactly." |
| 2482 | | - |
| 2483 | | -**I12. Section 5.3: "This is Modula-3's rule for an `UNSAFE MODULE` |
| 2484 | | -that implements a safe `INTERFACE`".** |
| 2485 | | -Right as far as it goes, but Modula-3 also fences imports, and raz |
| 2486 | | -doesn't. The Modula-3 report's Safety section says: "It is a static |
| 2487 | | -error for a safe interface to import an unsafe one or for a safe module |
| 2488 | | -to import or export an unsafe interface." Raz lets any safe module |
| 2489 | | -import an unsafe one and fences per procedure (`unsafe proc`). That is |
| 2490 | | -closer to D's `@safe`/`@trusted`/`@system` per function, and to Rust's |
| 2491 | | -`unsafe fn`, than to Modula-3. |
| 2492 | | -Source: https://www.cs.purdue.edu/homes/hosking/m3/reference/safety.html. |
| 2493 | | -Correct wording: add "Unlike Modula-3, which forbids a safe module to |
| 2494 | | -import an unsafe interface, raz fences per procedure, as D's |
| 2495 | | -`@trusted` and Rust's `unsafe fn` do." |
| 2496 | | - |
| 2497 | | -**I13. Section 12: "The unit of review is a file, as Wirth's languages |
| 2498 | | -always had it."** |
| 2499 | | -Modula-3 isn't Wirth's. It came from DEC SRC and Olivetti, building on |
| 2500 | | -Modula-2+. Pascal had no modules, so "always" is wrong. Modula-2 and |
| 2501 | | -Oberon do mark low-level code by importing `SYSTEM` per module. |
| 2502 | | -Correct wording: "The unit of review is a module, as in Modula-2's and |
| 2503 | | -Oberon's `IMPORT SYSTEM` and Modula-3's `UNSAFE`." |
| 2504 | | - |
| 2505 | | -**I14. Section 12, Vale row: "regions skip the check"; races "regions"; |
| 2506 | | -fence "`unsafe`".** |
| 2507 | | -These are mostly Vale's plans. Vale's last release is 0.2 (2022). Its |
| 2508 | | -own project page lists the region borrow checker and hybrid-generational |
| 2509 | | -memory as medium-term goals, and its `unsafe` blocks and "Fearless |
| 2510 | | -FFI" were proofs of concept. Generational references themselves, |
| 2511 | | -section 8.2's claim, are right: each object carries a current |
| 2512 | | -generation, each non-owning reference a remembered one, checked on |
| 2513 | | -dereference. Owning references aren't checked. |
| 2514 | | -Sources: https://vale.dev/memory-safe; https://vale.dev/project; https://vale.dev/blog/version-0.2-released. |
| 2515 | | -Correct wording: "generational references, checked at each |
| 2516 | | -dereference; regions, which would skip the check, are designed and not |
| 2517 | | -finished". |
| 2518 | | - |
| 2519 | | -**I15. Section 12, Cyclone row: temporal "regions, checked |
| 2520 | | -statically".** |
| 2521 | | -Leaves out that Cyclone's heap region is garbage collected |
| 2522 | | -(conservatively, with the Boehm collector). Grossman's PLDI 2002 paper |
| 2523 | | -integrates regions "with stack allocation and a garbage collector". |
| 2524 | | -Unique and reference-counted pointers came later (Hicks et al.). |
| 2525 | | -Cyclone's temporal safety for the heap is a GC, which is what raz |
| 2526 | | -refuses. |
| 2527 | | -Sources: https://www.cs.umd.edu/~mwh/papers/GrossmanMJHWC02.html; https://www.cs.washington.edu/homes/djg/slides/cyclone_pldi02.pdf. |
| 2528 | | -Correct wording: "regions checked statically; the heap region garbage |
| 2529 | | -collected". |
| 2530 | | - |
| 2531 | | -**I16. Section 12, "Fil-C, CHERI" row: "Fil-C: a few times slower"; |
| 2532 | | -"Fil-C: atomic capabilities"; "CHERI: revocation".** |
| 2533 | | -Fil-C's own figures are "about 1.5x-4x slower" (README and Manifesto, |
| 2534 | | -version 0.686). On races, Fil-C says "Pointer races on pointers not |
| 2535 | | -marked `_Atomic` or `volatile` lead to Fil-C panics, at worst". Only |
| 2536 | | -atomic pointers get an "atomic box". CHERI's capabilities give spatial |
| 2537 | | -safety in hardware. Its temporal safety needs software revocation |
| 2538 | | -sweeps (Cornucopia, in CheriBSD), and it costs 128-bit pointers. |
| 2539 | | -Sources: https://raw.githubusercontent.com/pizlonator/fil-c/deluge/README.md; https://raw.githubusercontent.com/pizlonator/fil-c/deluge/Manifesto.md. |
| 2540 | | -Correct wording: "Fil-C: 1.5 to 4 times slower, and a concurrent GC; |
| 2541 | | -CHERI: 128-bit capabilities, and revocation by software sweeps". |
| 2542 | | - |
| 2543 | | -**I17. Section 19: "[MTE and CHERI] aren't on x86-64, and they are |
| 2544 | | -probabilistic (MTE's four bits)."** |
| 2545 | | -Two fixes. First, only MTE is probabilistic: a 4-bit tag per 16-byte |
| 2546 | | -granule (Linux's document: "a 4-bit allocation tag for each 16-byte |
| 2547 | | -granule"), so a stale pointer passes 1 time in 16 by chance. CHERI's |
| 2548 | | -bounds are exact. Second, x86 is on its way: Intel and AMD announced |
| 2549 | | -ChkTag, a common x86 memory-tagging specification, on 13 October 2025, |
| 2550 | | -with no shipping date. MTE is also not only for debugging any more. |
| 2551 | | -Apple's Memory Integrity Enforcement runs Enhanced MTE always on and |
| 2552 | | -synchronously on the iPhone 17 (September 2025). |
| 2553 | | -Sources: https://raw.githubusercontent.com/torvalds/linux/master/Documentation/arch/arm64/memory-tagging-extension.rst; https://www.amd.com/en/blogs/2025/amd-and-intel-celebrate-first-anniversary-of-x86-ecosys.html; https://www.phoronix.com/news/AMD-Intel-One-Year-x86-Eco; https://security.apple.com/blog/memory-integrity-enforcement. |
| 2554 | | -Correct wording: "They aren't on x86-64 yet (Intel and AMD announced |
| 2555 | | -ChkTag in 2025). MTE is probabilistic, with four bits a tag; CHERI is |
| 2556 | | -exact, but needs software revocation for use after free." |
| 2557 | | - |
| 2558 | | -**I18. Section 11: "This is ... Chrome's MiraclePtr quarantine".** |
| 2559 | | -MiraclePtr is not a debugging heap, and its quarantine isn't a fixed |
| 2560 | | -count. `raw_ptr<T>`, implemented by BackupRefPtr, keeps a reference |
| 2561 | | -count in each PartitionAlloc slot. It is "quarantining the freed memory |
| 2562 | | -as long as any dangling `raw_ptr<T>` pointing to it exists, and |
| 2563 | | -poisoning it (with 0xEF..EF pattern)". Its constructor, destructor and |
| 2564 | | -assignment "need to maintain BackupRefPtr's ref-count (atomic |
| 2565 | | -increment/decrement)". It ships in production Chrome. That makes it a |
| 2566 | | -precedent for part C, not part G: count the references a block has |
| 2567 | | -lent, and retire the block instead of freeing it while the count is |
| 2568 | | -above zero. Its documentation also records the cost part C should |
| 2569 | | -expect: "on a couple occasions it led to significant memory leaks". A |
| 2570 | | -fixed FIFO quarantine with guard bytes, like part G's, is |
| 2571 | | -AddressSanitizer's quarantine and redzones, and GWP-ASan's. |
| 2572 | | -Source: https://raw.githubusercontent.com/chromium/chromium/main/base/memory/raw_ptr.md. |
| 2573 | | -Correct wording in 11: "This is AddressSanitizer's quarantine and |
| 2574 | | -redzones, Zig's debug allocator and glibc's `MALLOC_PERTURB_`, without |
| 2575 | | -their reach." Add to section 7: "Chrome's BackupRefPtr (MiraclePtr) |
| 2576 | | -does the same in C++: it counts a block's references and quarantines |
| 2577 | | -it on free while the count is above zero." |
| 2578 | | - |
| 2579 | | -**I19. Section 3 and 9.2, point 2: a race on a whole record or variant |
| 2580 | | -"is undefined, as in Go".** |
| 2581 | | -Go doesn't call it undefined. The memory model says a racy read of a |
| 2582 | | -multi-word value may see "inconsistent values not corresponding to a |
| 2583 | | -single write". Only "when the values depend on the consistency of |
| 2584 | | -internal (pointer, length) or (pointer, type) pairs, as can be the case |
| 2585 | | -for interface values, maps, slices, and strings in most Go |
| 2586 | | -implementations, such races can in turn lead to arbitrary memory |
| 2587 | | -corruption." Go sets itself apart from C and C++, "where the meaning of |
| 2588 | | -any program with a race is entirely undefined". A race on a plain |
| 2589 | | -struct of integers just gives mixed values. |
| 2590 | | -Source: https://raw.githubusercontent.com/golang/go/master/doc/go_mem.html (go.dev/ref/mem). |
| 2591 | | -Correct wording: "undefined. Go is narrower: a race tears such a value, |
| 2592 | | -and corrupts memory only through its pointer and length or type pairs." |
| 2593 | | - |
| 2594 | | -**I20. Section 9.1: Go's memory model on races over multi-word values.** |
| 2595 | | -The quotation is right, but the list it gives is short. Go names |
| 2596 | | -"interface values, maps, slices, and strings", hedged "in most Go |
| 2597 | | -implementations", and says such races "can in turn lead to arbitrary |
| 2598 | | -memory corruption". The proposal's list drops maps, and its "an |
| 2599 | | -interface, a slice, a string" reads as Go's words when they are a |
| 2600 | | -paraphrase. |
| 2601 | | -Source: as I19. |
| 2602 | | -Correct wording: "Go's memory model says that races on values made of |
| 2603 | | -(pointer, length) or (pointer, type) pairs, 'interface values, maps, |
| 2604 | | -slices, and strings in most Go implementations', 'can in turn lead to |
| 2605 | | -arbitrary memory corruption'." |
| 2606 | | - |
| 2607 | | -**I21. Section 12: "From Swift: checking exclusivity at run time where |
| 2608 | | -the compiler can't, as part C counts lends."** |
| 2609 | | -Loose. Swift's dynamic exclusivity tracks the start and end of each |
| 2610 | | -access to a class property, global or escaped variable, per thread |
| 2611 | | -(W1). It doesn't count. Part C counts outstanding loans and refuses or |
| 2612 | | -defers a release while any is held. That is Rust's `RefCell` (a borrow |
| 2613 | | -count that panics), CPython's `bytearray` (it keeps `ob_exports` and |
| 2614 | | -refuses to resize: "Existing exports of data: object cannot be |
| 2615 | | -re-sized"), Java's and .NET's fail-fast iterators (a modification |
| 2616 | | -count), and Chrome's BackupRefPtr (I18). |
| 2617 | | -Sources: https://raw.githubusercontent.com/python/cpython/main/Objects/bytearrayobject.c; https://raw.githubusercontent.com/rust-lang/rust/master/library/core/src/cell.rs. |
| 2618 | | -Correct wording: "From Rust's `RefCell`, CPython's buffer exports and |
| 2619 | | -Chrome's BackupRefPtr: a count of what is lent, checked at run time, |
| 2620 | | -where the compiler can't see it." |
| 2621 | | - |
| 2622 | | -**I22. Section 8.2: "Part of the first is that each slot is 32 bytes, |
| 2623 | | -not 16"; and open question 6, one word or two for a handle.** |
| 2624 | | -The precedent the proposal cites answers the question, and the |
| 2625 | | -proposal doesn't use it. slotmap's key is one 64-bit word: a 32-bit |
| 2626 | | -index and a 32-bit version (`idx: u32, version: NonZeroU32`). A slot |
| 2627 | | -costs `4 + max(sizeof(T), 4)` bytes. Versions wrap after 2^31 reuses of |
| 2628 | | -a slot, "and in all circumstances is the behavior safe". So the 32-byte |
| 2629 | | -slot of the benchmark comes from the two-word `Handle` chosen here, not |
| 2630 | | -from generational handles as such. The 1.5x past the caches is partly |
| 2631 | | -an artifact of that choice. |
| 2632 | | -Source: https://raw.githubusercontent.com/orlp/slotmap/master/src/lib.rs. |
| 2633 | | -Correct wording: add to 21.6: "slotmap takes one word, 32 bits each, |
| 2634 | | -and lets the version wrap; with it, a slot of a 16-byte `T` is 20 or |
| 2635 | | -24 bytes, not 32." |
| 2636 | | - |
| 2637 | | -### Correct |
| 2638 | | - |
| 2639 | | -**C1. Section 9.1: "Java closes it by tearing only `long` and `double`, |
| 2640 | | -never a reference."** Correct. JLS 17.7: a non-volatile `long` or |
| 2641 | | -`double` write may be treated "as two separate writes, one to each |
| 2642 | | -32-bit half"; "Writes to and reads of references are always atomic, |
| 2643 | | -regardless of whether they are implemented as 32-bit or 64-bit |
| 2644 | | -values." Source: https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.7 (read through a mirror: https://www.oreilly.com/library/view/the-java-language/9780133260335/ch17lev1sec7.html). |
| 2645 | | - |
| 2646 | | -**C2. Section 7.4: "This is Go's `append`: the old slice still sees the |
| 2647 | | -old array."** Correct for a growing append. The spec says: "If the |
| 2648 | | -capacity of s is not large enough to fit the additional values, append |
| 2649 | | -allocates a new, sufficiently large underlying array ... Otherwise, |
| 2650 | | -append re-uses the underlying array." In Go the GC keeps the old array |
| 2651 | | -while it is referenced. Raz retires the block and frees it at a later |
| 2652 | | -growth once the count is 0, which matches for every slice still held. |
| 2653 | | -Source: https://raw.githubusercontent.com/golang/go/master/doc/go_spec.html. |
| 2654 | | - |
| 2655 | | -**C3. Section 19: `append(s, s...)` is right in Go.** Correct: append |
| 2656 | | -copies with memmove semantics, so overlap is safe. Source: as C2. |
| 2657 | | - |
| 2658 | | -**C4. Section 12, Go row: checked, GC, forged pointers "only through |
| 2659 | | -`unsafe`", fence `import "unsafe"`.** Correct. cgo is the other way |
| 2660 | | -out, and it is also visible in imports (`import "C"`). |
| 2661 | | - |
| 2662 | | -**C5. Section 8.2: "the generational arena of Rust's `slotmap` and |
| 2663 | | -`generational-arena`".** Correct. slotmap: "persistent unique keys ... |
| 2664 | | -The keys returned by `slotmap` are versioned." generational-arena: "A |
| 2665 | | -safe arena allocator that allows deletion without suffering from the |
| 2666 | | -ABA problem by using generational indices." Sources: https://github.com/orlp/slotmap; https://github.com/fitzgen/generational-arena. |
| 2667 | | - |
| 2668 | | -**C6. Section 8.2: "the handle pattern Zig and game engines use".** |
| 2669 | | -Correct as practice. The pattern's best-known write-up is Andre |
| 2670 | | -Weissflog's "Handles are the better pointers" (2018), worth citing: |
| 2671 | | -https://floooh.github.io/2018/06/17/handles-vs-pointers.html. |
| 2672 | | - |
| 2673 | | -**C7. Section 12, Rust row, and 9.1: `Send`/`Sync` checked by the type |
| 2674 | | -system; `unsafe` blocks and functions.** Correct. |
| 2675 | | - |
| 2676 | | -**C8. Section 19: "non-lexical lifetimes are a fixpoint over the control |
| 2677 | | -flow, not one pass".** Correct. NLL (RFC 2094) computes liveness and |
| 2678 | | -region constraints by dataflow over MIR's control-flow graph. |
| 2679 | | - |
| 2680 | | -**C9. Section 12, Swift row: "exclusivity checked at compile and run |
| 2681 | | -time"; "Swift 6: `Sendable`, checked".** Correct. Swift 5 enabled |
| 2682 | | -run-time exclusivity checks in release builds; the Swift 6 language |
| 2683 | | -mode makes data-race checks errors. Source: https://github.com/swiftlang/swift-org-website/blob/main/_posts/2019-02-05-swift-5-exclusivity.md. |
| 2684 | | - |
| 2685 | | -**C10. Section 12, Modula-3 row: a GC for traced references, `DISPOSE` |
| 2686 | | -only in unsafe modules, `UNSAFE MODULE` and `UNSAFE INTERFACE`.** |
| 2687 | | -Correct. The report: "An interface or module not explicitly labeled |
| 2688 | | -UNSAFE is called safe." SRC's compiler: `IF Module.IsSafe () THEN |
| 2689 | | -Error.Msg ("DISPOSE: unsafe operation")`. Untraced references (`UNTRACED |
| 2690 | | -REF`) aren't collected. Sources: https://www.cs.purdue.edu/homes/hosking/m3/reference/unsafe.html; https://softwarepreservation.computerhistory.org/modula3/archive/DEC_SRC/release-2.11-unpacked/compiler/src/builtinOps/Dispose.m3. |
| 2691 | | - |
| 2692 | | -**C11. Section 12, Oberon row: unsafe only through `SYSTEM`, marked by |
| 2693 | | -`IMPORT SYSTEM`.** Correct. The GC belongs to the Oberon system rather |
| 2694 | | -than the language report, which is a fine point. |
| 2695 | | - |
| 2696 | | -**C12. Section 12, Ada row: `Unchecked_Deallocation`, |
| 2697 | | -`Unchecked_Conversion`, "SPARK adds ownership".** Correct. SPARK's |
| 2698 | | -pointers follow "the Rust model": move for pool-specific access types, |
| 2699 | | -borrow and observe for anonymous ones (SPARK Community 2020 onward). |
| 2700 | | -Source: https://docs.adacore.com/spark2014-docs/html/ug/en/source/access.html. |
| 2701 | | - |
| 2702 | | -**C13. Section 12, Zig row: bounds "checked in Debug and |
| 2703 | | -ReleaseSafe".** Correct. The langref: "In Debug and ReleaseSafe mode |
| 2704 | | -... triggers a safety panic"; ReleaseFast and ReleaseSmall assume |
| 2705 | | -the checks away. |
| 2706 | | - |
| 2707 | | -**C14. Section 11: "Zig's debug allocator".** Correct name since Zig |
| 2708 | | -0.14.0 (`std.heap.DebugAllocator`; `GeneralPurposeAllocator` survives |
| 2709 | | -as a deprecated alias). Source: https://ziglang.org/download/0.14.0/release-notes.html. |
| 2710 | | - |
| 2711 | | -**C15. Section 11: glibc's `MALLOC_PERTURB_`.** Correct: it fills |
| 2712 | | -blocks "when they are allocated ... and freed". It has no quarantine |
| 2713 | | -and no guard bytes; the proposal's "without their reach" allows for |
| 2714 | | -that. Source: https://raw.githubusercontent.com/bminor/glibc/master/manual/memory.texi. |
| 2715 | | - |
| 2716 | | -### Unverifiable |
| 2717 | | - |
| 2718 | | -**U1. Section 12, Zig row: races "UB".** Zig has no written memory |
| 2719 | | -model. Its atomics follow LLVM's, under which a data race on a |
| 2720 | | -non-atomic location is undefined, so the claim is very likely right. |
| 2721 | | -No Zig document says so. |
| 2722 | | - |
| 2723 | | -**U2. Section 12, Modula-3 row: races "not promised".** The report |
| 2724 | | -doesn't speak to it in what I could read. Since Modula-3's open arrays |
| 2725 | | -and `TEXT`s are behind references, a race in a safe module may not |
| 2726 | | -break memory at all. Leave it, or write "not addressed by the report". |
| 2727 | | - |
| 2728 | | -### Precedent the proposal misses |
| 2729 | | - |
| 2730 | | -- **D: `@safe`, `@trusted`, `@system`, and DIP1000's `scope` and `return |
| 2731 | | - scope`.** This is the closest match to parts A and B together. |
| 2732 | | - `@trusted` is section 5.3's trust, per function. `return scope` is |
| 2733 | | - `ret`, and plain `scope` is the opposite of `keep`. PROPOSALS.md |
| 2734 | | - cites DIP1000; MEM_PROPOSAL.md doesn't. It should, together with D's |
| 2735 | | - lesson that the corners (fields, generics, delegates) took years. |
| 2736 | | - DIP1000 is still behind `-preview=dip1000`, and its document is marked |
| 2737 | | - "Superseded". Source: https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1000.md. |
| 2738 | | -- **C#: `ref struct`, `Span<T>`, `scoped`, ref-safety contexts.** C# |
| 2739 | | - checks with local, one-pass rules that a `Span<T>` never outlives what |
| 2740 | | - it points at, with three contexts that are part B's three lenders |
| 2741 | | - (I11). It is the strongest evidence that part B works in a |
| 2742 | | - mainstream compiler without lifetimes in types. Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md. |
| 2743 | | -- **Swift: `~Escapable` types, lifetime dependencies, `Span`, and |
| 2744 | | - SE-0458.** Swift 6.2's non-escapable types (SE-0446) and `Span` |
| 2745 | | - (SE-0447) give a slice that can't outlive its source, with a |
| 2746 | | - dependence written on the function. That is `ret` again. SE-0458's |
| 2747 | | - `@safe` and `@unsafe` are the fence and the trust. Sources: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md; .../0447-span-access-shared-contiguous-storage.md; .../0458-strict-memory-safety.md. |
| 2748 | | -- **Chrome's BackupRefPtr.** Counted references with quarantine on |
| 2749 | | - free, in production C++ (I18). It is the precedent for part C's |
| 2750 | | - retirement, with measured costs and recorded leaks. |
| 2751 | | -- **Rust's `RefCell`, CPython's buffer exports, Java's `modCount`.** |
| 2752 | | - Run-time counts of loans that refuse a change while one is held |
| 2753 | | - (I21). CPython's `bytearray` refusing to resize while exported is |
| 2754 | | - part C's "stop" alternative from section 19, shipped for years. |
| 2755 | | -- **Checked C.** Microsoft's extension of C with checked pointer types |
| 2756 | | - (`_Ptr`, `_Array_ptr` with bounds) and `_Checked`/`_Unchecked` |
| 2757 | | - scopes. It is a fence in a C-like language, at a finer grain than a |
| 2758 | | - module, and it shows the cost of a per-block fence. |
| 2759 | | - https://github.com/checkedc/checkedc. |
| 2760 | | -- **SafeStack (clang).** It moves address-taken locals to a separate |
| 2761 | | - stack. That is relevant to what an unsafe module's `ADR` of a local |
| 2762 | | - can reach, and to part F's frame slots. https://clang.llvm.org/docs/SafeStack.html. |
| 2763 | | -- **Hylo (formerly Val).** Mutable value semantics: no stored |
| 2764 | | - references at all, only projections that last the call. That is the |
| 2765 | | - extreme of section 14's "a record can't keep a slice into a buffer |
| 2766 | | - that belongs to someone else", and it argues that the limit is |
| 2767 | | - livable. https://www.hylo-lang.org. |
| 2768 | | -- **Austral.** Linear types with lexical borrows, kept small on purpose |
| 2769 | | - so that one person can hold the whole checker in their head. That |
| 2770 | | - matters to raz's "a beginner can follow". https://austral-lang.org. |
| 2771 | | -- **Mojo and Carbon.** Mojo has ownership with inferred "origins", a |
| 2772 | | - Rust-like model with lighter syntax. Carbon plans a safe subset |
| 2773 | | - reached by incremental migration from C++, as part of section 20's |
| 2774 | | - order of work. Both are worth a line in section 19's view of Rust's |
| 2775 | | - way. https://docs.modular.com/mojo/manual/values/lifetimes; https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/safety/README.md. |
| 2776 | | -- **Modula-2+ and Cedar.** They had safe and unsafe (Cedar: checked, |
| 2777 | | - trusted, unchecked) modules before Modula-3, and are where the |
| 2778 | | - module fence of section 12 comes from. |
| 2779 | | -- **AddressSanitizer and GWP-ASan.** The real models for part G's |
| 2780 | | - quarantine and guard bytes (I18). |
| 2781 | | - |
| 2782 | | ---- |
| 2783 | | - |
| 2784 | | -## Appendix 6: adversarial review, the proposal's numbers and samples |
| 2785 | | - |
| 2786 | | -**Summary.** The five demo programs compile with `-Werror`, print what |
| 2787 | | -the proposal says, and do the undefined thing claimed. The callgrind |
| 2788 | | -figures repeat to within a thousand instructions. Several other things |
| 2789 | | -don't hold: |
| 2790 | | - |
| 2791 | | -- The survey counts lines, not operations, and the proposal calls them |
| 2792 | | - operations. |
| 2793 | | -- Its "test/libc" row is really `lib/Sys.raz`. |
| 2794 | | -- rnet's TLS backends and two of its tests were never compiled. |
| 2795 | | -- Most `ADR`s in rnet, rjson, rlX11 and ravite are arguments to the |
| 2796 | | - programs' own procedures, not to the library. So the claim that |
| 2797 | | - v0.19.0 "removed them already" is wrong. |
| 2798 | | -- Every one of raz's own benchmark kernels says `check off;`. |
| 2799 | | -- The kernels don't run "past the caches": the machine reports a |
| 2800 | | - 260 MB L3. |
| 2801 | | -- The 16-to-32-byte and fat-pointer conclusions are confounded by node |
| 2802 | | - layout and by noise. |
| 2803 | | -- Part C's run-time rule would stop the library's own `Opt.say`, the |
| 2804 | | - compiler's `Parse.moduleParams` and ravite's `load`. |
| 2805 | | -- 7.3 forbids the accessor that 14.2 recommends. |
| 2806 | | -- No container's `init` is marked `keep`, so a `Buf` over an `Arena` |
| 2807 | | - (used by `Fmt.eprint` and `examples/Sh`) can't be written safely. |
| 2808 | | -- Three of the sample error messages are wrong, and one gives help that |
| 2809 | | - doesn't compile. |
| 2810 | | -- The compiler cost is likely low by 40 to 70%, judged against |
| 2811 | | - PROPOSALS' own revised figure. |
| 2812 | | - |
| 2813 | | -Commands below were run on 2026-10-17. The scratch data used is in |
| 2814 | | -`/tmp/claude-0/-home-user-raz/bab05b52-9d9d-4262-9f3e-de1807ce50a5/scratchpad/` |
| 2815 | | -(S below). Files made for this review are in |
| 2816 | | -`/tmp/claude-0/-home-user/f9bd1744-45c5-5c51-82fd-fddfc77d01cc/scratchpad/` |
| 2817 | | -(W below). |
| 2818 | | - |
| 2819 | | -### 1. Survey counts |
| 2820 | | - |
| 2821 | | -**1.1 "Places", counted once each, are lines (2.1, 2.2, appendix 1).** |
| 2822 | | -`Diag.tally` prints `path:line` with no column, and `agg.py` keys on |
| 2823 | | -(kind, file, line). So two operations of one kind on one line count |
| 2824 | | -once. I rebuilt the tally compiler to print the offset as well |
| 2825 | | -(`W/tc/raz`) and compiled `src/Raz.raz` with it: |
| 2826 | | - |
| 2827 | | -| kind | lines (proposal) | distinct places | |
| 2828 | | -|---|---|---| |
| 2829 | | -| `ADR` | 27 | 32 | |
| 2830 | | -| deref | 1,015 | 1,410 | |
| 2831 | | -| `p[i]` | 277 | 372 | |
| 2832 | | -| `p[a..b]` | 30 | 44 | |
| 2833 | | -| ptr cast | 42 | 48 | |
| 2834 | | -| `p ± i` | 3 | 4 | |
| 2835 | | - |
| 2836 | | -The distinct places are themselves a floor: nested operations at one |
| 2837 | | -position still merge. **Correction:** call them "lines with", or give |
| 2838 | | -the operation counts. The ratios between modules hold. |
| 2839 | | - |
| 2840 | | -**1.2 The `test/libc` row is library code.** `test/libc/mods/Sys.raz` |
| 2841 | | -is a link to `lib/Sys.raz`, the C `Sys`. It holds 108 of the row's 110 |
| 2842 | | -`ADR`s, 63 of its 64 casts and all 35 of its `p[i]`. The tests' own |
| 2843 | | -files hold 2 `ADR`s, 1 cast and 1 `NEW`. **Correction:** move 242 |
| 2844 | | -fenced operations to `lib/` (`lib/Sys`, the C one), and say so when |
| 2845 | | -naming the library's unsafe modules (2.2, "Sys (287 operations)" is |
| 2846 | | -the Linux file only). |
| 2847 | | - |
| 2848 | | -**1.3 rnet was compiled in part.** `S/out/rnet.log` shows |
| 2849 | | -`test/Net.raz` and `test/Https.raz` failing, because `module Tls is in |
| 2850 | | -.../gnutls/Tls.raz and .../openssl/Tls.raz`. So neither TLS backend |
| 2851 | | -was counted. Both are `extern` modules: 26 and 35 `extern`s, 27 and 24 |
| 2852 | | -`ADR`s. **Correction:** 5.4 says "rnet needs it only to keep |
| 2853 | | -`Http.Message`". In fact both `tls/*/Tls.raz` must say `unsafe;`, as |
| 2854 | | -`Sqlite` must. Section 15's rnet row should list them. |
| 2855 | | - |
| 2856 | | -**1.4 rnet's and rjson's `ADR` totals disagree with appendix 1.** 2.2 |
| 2857 | | -gives rnet 572 and rjson 77. Appendix 1 gives 471 and 91 (lines, from |
| 2858 | | -the tally). A grep outside comments finds 792 occurrences in rnet (621 |
| 2859 | | -lines) and 110 in rjson. rlX11's 89 doesn't come out either: grep |
| 2860 | | -finds 108, 78 of them in `src/`. ravite's 202 and rmacs's 560 match a |
| 2861 | | -grep. |
| 2862 | | - |
| 2863 | | -**1.5 "Almost every ADR is ... the library's old pointer parameters" |
| 2864 | | -is wrong for most repositories.** I sorted each `ADR` by the call it |
| 2865 | | -is an argument to (`W/py/adr.py`, a textual parser): |
| 2866 | | - |
| 2867 | | -| repo | `ADR`s | to the library | to its own procedures and modules | casts and other | |
| 2868 | | -|---|---|---|---|---| |
| 2869 | | -| rnet | 792 | 226 | 525 | 41 (34 to `Tls`) | |
| 2870 | | -| rjson | 110 | 35 | 70 | 5 | |
| 2871 | | -| rflate | 67 | 48 | 16 | 3 | |
| 2872 | | -| rsqlite | 42 | 12 | 27 (some to C) | 3 | |
| 2873 | | -| rmacs | 560 | 424 | 132 | 4 | |
| 2874 | | -| ravite | 202 | 107 | 93 | 2 | |
| 2875 | | -| rlX11 | 108 | 5 | 100 | 3 | |
| 2876 | | - |
| 2877 | | -The top callees in rnet are its own `fetches`, `resolves`, |
| 2878 | | -`Conn.close` and `parseAnswer`. In rlX11 it is its own `expect`. Those |
| 2879 | | -are the programs' pointer-taking headings. They mend by `var`, but the |
| 2880 | | -programs have to be rewritten for it; v0.19.0's library didn't remove |
| 2881 | | -them. **Correction:** "Most `ADR`s are arguments; in rmacs and rflate |
| 2882 | | -mostly to the library, in rnet, rjson and rlX11 mostly to the |
| 2883 | | -programs' own pointer parameters." |
| 2884 | | - |
| 2885 | | -**1.6 "Nobody uses `check off;`" (2.2, 13.2) is wrong.** All seven |
| 2886 | | -kernels in `test/bench` say `check off;` (`grep -l '^check off' |
| 2887 | | -test/bench/*.raz` gives 7 of 7). The Makefile says so too: "the |
| 2888 | | -kernels of test/bench, which say check off". So does |
| 2889 | | -`test/run/mods/Unchecked.raz`. The survey left `test/` out, but the |
| 2890 | | -inference "no one has wanted them off" doesn't follow: raz's own speed |
| 2891 | | -comparison with FPC turns the checks off. **Correction:** "No library |
| 2892 | | -module or program surveyed turns them off. raz's benchmark kernels do, |
| 2893 | | -to match FPC -O2." |
| 2894 | | - |
| 2895 | | -**1.7 Frees and `done`s (2.2, 8.1).** |
| 2896 | | - |
| 2897 | | -- The hand frees match: `src/` 7, rmacs 9 (4 `Mem.free` plus 5 |
| 2898 | | - `Heap.heap^.free`), rjson 6, ravite 2, rlX11 1, others 0. |
| 2899 | | -- rnet has 41 `done`s, not 30: `src/` has 30, its tests 11. With 41, |
| 2900 | | - "54 to 26" becomes 65 to 25 or 26. That still makes the point. |
| 2901 | | -- The mendings in section 15 misdescribe some of the frees: |
| 2902 | | - - rjson's 6 are all `Mem.free` of grown arrays (`nodes`, `kids`, |
| 2903 | | - `stack`), with no `Str.free`. They mend by `Vec`, not by `Names` |
| 2904 | | - or `Buf`. |
| 2905 | | - - ravite's 2 are `Text`'s grown `data` and `changes`, not windows. |
| 2906 | | - They mend by `Vec` or `Buf`, not `Pool`. |
| 2907 | | - - Only rmacs's 5 `Heap` frees, of windows and parts, are `Pool` |
| 2908 | | - material. |
| 2909 | | - |
| 2910 | | -**1.8 "35 places assign Buf.bytes, Vec.all or Windows.all"** holds. |
| 2911 | | -A grep finds 36 assignments to locals and 3 to fields (`m^.body`, and |
| 2912 | | -`res^.body` twice). The only `.all` is rmacs's `Windows.all`. |
| 2913 | | - |
| 2914 | | -**1.9 "Records that hold slices: src/ 10" isn't reproduced.** I find |
| 2915 | | -three slice fields in `src/`'s records: `Diag.File.path`, |
| 2916 | | -`Sym`'s `path*` (line 116) and `X64.Said.text`. 13.3 repeats "10". |
| 2917 | | -**Correction:** 3, or say how 10 was counted. |
| 2918 | | - |
| 2919 | | -**1.10 Dereferences: "Every one is a pointer from NEW on the heap, |
| 2920 | | -which the compiler never frees" (2.2) is false today.** Some are not: |
| 2921 | | - |
| 2922 | | -- `X64`'s `r^`, `size^` and `o^` point at locals through `ADR(r)` and |
| 2923 | | - `ADR(ao[an])`. |
| 2924 | | -- `Elf`'s `dynSize^` and `roExtra^` point at locals. |
| 2925 | | -- `Scan`'s `bits^` points at a local. |
| 2926 | | -- `Diag`'s `f^` and `Chunk`'s `c^` point into grown arrays that |
| 2927 | | - `regrab` frees (`Scan.raz:137`, `Diag.raz:103`). |
| 2928 | | - |
| 2929 | | -They are few (tens), and part A's mendings would remove them. But the |
| 2930 | | -sentence should say "nearly every". |
| 2931 | | - |
| 2932 | | -**1.11 The `src/` `ADR`-and-cast table (2.2) misses some sites and |
| 2933 | | -miscounts others.** The table sums to 55. There are 62 distinct lines |
| 2934 | | -with an `ADR` or a cast. |
| 2935 | | - |
| 2936 | | -- Grown arrays: 31 lines are `grab`/`regrab`/`free` of arrays. 3 more |
| 2937 | | - are single records, `^Buf.Buf(Scan.grab(SIZE(Buf.Buf)))`, which |
| 2938 | | - should be `NEW`, not `Vec`. |
| 2939 | | -- "A real's bits" are 4 lines (Item 152, 165, 364; Scan 879). 3 more |
| 2940 | | - are a value's bytes for data (`Gen.raz:293`, `Parse.raz:3186`, |
| 2941 | | - `Parse.raz:3334`). They need `setData` and the copy to take a slice, |
| 2942 | | - besides the view. |
| 2943 | | -- `intern`: 7, correct. Two `Elf.putBytes(ADR(s[0]), LEN(s))` are |
| 2944 | | - missing. |
| 2945 | | -- Out-parameters: 4 lines, 8 `ADR`s, not 5. |
| 2946 | | -- Not listed at all: |
| 2947 | | - - `ADR(chunks[n])`, `ADR(files[i])` ×2 and `ADR(ao[an])`; |
| 2948 | | - - `Scan.raz:119` (`return ADR(sbuf[0])`, the allocator); |
| 2949 | | - - `Item.raz:2155` (`^I64(p)`); |
| 2950 | | - - `Raz.raz`'s two `SYSCALL`s (`memfd_create`, and `execve` with |
| 2951 | | - `ARGV() + first`). |
| 2952 | | - |
| 2953 | | - The `SYSCALL`s mend by `Sys.memFile`, and `Sys.execve` with |
| 2954 | | - `Sys.envAt`, but they are not "1 SYSCALL". |
| 2955 | | - |
| 2956 | | -### 2. The five programs |
| 2957 | | - |
| 2958 | | -Each was extracted from appendix 3 and compiled with |
| 2959 | | -`/home/user/raz/raz -Werror`. Each is identical to `S/demo/`. |
| 2960 | | - |
| 2961 | | -| program | printed | status | |
| 2962 | | -|---|---|---| |
| 2963 | | -| SelfAppend | 24 `a` | 0 | |
| 2964 | | -| Stale | `1 2` | 0 | |
| 2965 | | -| Escape | `########` | 0 | |
| 2966 | | -| Kept | `name-001: missing`, `name-002: missing` | 0 | |
| 2967 | | -| Temp | `name-..b`, a space, then `01 00 00 00 00 00 00 00` | 0 | |
| 2968 | | - |
| 2969 | | -All as claimed. |
| 2970 | | - |
| 2971 | | -**2.1 SelfAppend's explanation (1.2) is vague where it could be |
| 2972 | | -exact.** |
| 2973 | | - |
| 2974 | | -- `Buf.room` copies, then frees the old block (`Buf.raz:36-37`). |
| 2975 | | - `Buf.str` then copies from `s`. |
| 2976 | | -- The old block is size class 3 and the new one class 4. `Heap.free` |
| 2977 | | - writes only the 16-byte header (`b := ^Block(h)`, `Heap.raz:96`). |
| 2978 | | - Nothing allocates between the free and the copy. |
| 2979 | | -- So with `Heap` in one thread the program is always right. That is |
| 2980 | | - not luck "in time". |
| 2981 | | -- A block past 4,080 bytes gets pages of its own, and `free` unmaps |
| 2982 | | - them. Filled to 8,192 bytes, the same line stops the program: |
| 2983 | | - `Buf.raz:67:5: stopped by a bad address` (`W/demo/SelfBig.raz`). |
| 2984 | | - That makes a stronger demonstration than the one shown. |
| 2985 | | - |
| 2986 | | -**2.2 Stale.** Holds as explained: |
| 2987 | | - |
| 2988 | | -- The class-4 block of 16 elements is freed when the `Vec` grows to 32. |
| 2989 | | -- `p` points into the class-5 block, which is freed at the next growth. |
| 2990 | | -- `free` touches only headers, so `first[0]` and `first[1]` read 1 |
| 2991 | | - and 2. |
| 2992 | | - |
| 2993 | | -**2.3 Escape** holds. |
| 2994 | | - |
| 2995 | | -**2.4 Temp.** The listing (`raz -S`) confirms one slot, |
| 2996 | | -`[rbp - 40]`, for both calls. |
| 2997 | | - |
| 2998 | | -- `a` was printed before anything overwrote the slot, so it shows |
| 2999 | | - `b`'s bytes. |
| 3000 | | -- `b` points at the same slot. That slot was overwritten by the next |
| 3001 | | - call's argument, `Out.str(" ")`, whose length 1 lands at |
| 3002 | | - `[rbp - 40]`. Hence `01 00 ...`. |
| 3003 | | -- "Whatever came after" is right. The precise cause is the next |
| 3004 | | - statement's temporaries. |
| 3005 | | - |
| 3006 | | -**2.5 "Three are what the library's own documentation warns of" (1.2) |
| 3007 | | -is two.** `Buf` ("until it next grows") and `Vec` warn. `Map`'s |
| 3008 | | -documentation says nothing about keeping its keys: neither the module |
| 3009 | | -comment nor `put`'s "k now maps to v". The proposal itself says the |
| 3010 | | -caller "must know, from the documentation alone". **Correction:** "two |
| 3011 | | -are what the library's documentation warns of, one what it doesn't |
| 3012 | | -say, and two what 7.3 and 8 warn of." Or mend `Map`'s comment. |
| 3013 | | - |
| 3014 | | -### 3. Benchmarks |
| 3015 | | - |
| 3016 | | -The machine is a 4-core Xeon VM at 2.1 GHz, with AVX-512. `lscpu` |
| 3017 | | -reports L2 2 MiB a core and **L3 260 MiB**. THP is `madvise`. |
| 3018 | | - |
| 3019 | | -**3.1 Two runs each of MemBench and GenBench (ms):** |
| 3020 | | - |
| 3021 | | -| kernel | proposal | mine, run 1 | mine, run 2 | |
| 3022 | | -|---|---|---|---| |
| 3023 | | -| big, raw, 16-byte nodes | 8,312 / 7,515 | 5,300 | 4,859 | |
| 3024 | | -| big, handles, 32-byte slots | 12,336 / 11,992 | 10,665 | 10,429 | |
| 3025 | | -| small, raw | 857 / 810 | 864 | 876 | |
| 3026 | | -| small, handles | 1,631 / 1,643 | 1,829 | 1,734 | |
| 3027 | | -| big, raw, 32-byte nodes | 14,001 / 13,725 | 13,734 | 13,499 | |
| 3028 | | -| big, fat pointers | 8,672 / 10,145 | 9,232 | 10,624 | |
| 3029 | | -| small, raw, 32-byte | 870 / 917 | 852 | 870 | |
| 3030 | | -| small, fat | 830 / 1,047 | 815 | 888 | |
| 3031 | | -| sum, big, `^U8` / `[]U8` | 305 / 342; 271 / 434 | 296 / 279 | 318 / 370 | |
| 3032 | | -| sum, small, `^U8` / `[]U8` | 261 / 265; 256 / 306 | 336 / 428 | 387 / 392 | |
| 3033 | | - |
| 3034 | | -Findings: |
| 3035 | | - |
| 3036 | | -- **Big handles cost 2.0 to 2.2 times here, not 1.5 to 1.6.** The raw |
| 3037 | | - baseline varies by 40% between sessions. |
| 3038 | | -- **The working sets are not "past the caches".** The big arrays are |
| 3039 | | - 16 MB and 32 MB, inside a reported 260 MB L3. So "doesn't fit in |
| 3040 | | - the caches" and `Big = 1000000; (* past the caches *)` are wrong |
| 3041 | | - here. What grows with the node is the page-walk footprint and the |
| 3042 | | - share of L3, not a miss to DRAM. |
| 3043 | | -- **"Half of it the larger slot" is not supported.** Across the two |
| 3044 | | - programs, the 32-byte raw chase (13.5 s) is *slower* than the |
| 3045 | | - 32-byte handle chase (10.5 s). The two programs aren't comparable. |
| 3046 | | - |
| 3047 | | -**3.2 Why big-gen beats big-ptr.** I tested three explanations: |
| 3048 | | - |
| 3049 | | -- Run order (`W/mb/GenOrder.raz`): not it. Gen first or second, gen |
| 3050 | | - 11.4 to 11.6 s, ptr 13.4 s. |
| 3051 | | -- Array placement in bss (`W/mb/GenSwap.raz`): not it. Ptr stays |
| 3052 | | - slower. |
| 3053 | | -- Layout and code (`W/mb/GenWhy.raz`, 50M steps): |
| 3054 | | - - ptr 6.8 s; |
| 3055 | | - - gen 3.8 to 4.5 s; |
| 3056 | | - - gen with no check 2.7 to 3.9 s; |
| 3057 | | - - a raw pointer chase over the *gnodes* array 4.2 to 5.8 s. |
| 3058 | | - |
| 3059 | | - In `W/mb/Offs.raz`, the same 32-byte node chased raw takes 6.3 to |
| 3060 | | - 6.5 s with the link at offset 0, and 5.3 to 5.9 s with it at offset |
| 3061 | | - 8. |
| 3062 | | - |
| 3063 | | -So part of the gap is the node's layout (where the link and the value |
| 3064 | | -sit), and the rest is noise of ±20 to 30% on this VM. The generation |
| 3065 | | -check itself isn't what the rows measure. Its cost is within noise; |
| 3066 | | -calling it "free" or "the check is free here" goes further than the |
| 3067 | | -data. The same layout effect sits inside the "+70–85%" for doubling a |
| 3068 | | -node: the comparison is across two programs with different layouts. |
| 3069 | | -**Correction:** "On this machine, wider records and handles cost 1.5 to |
| 3070 | | -2.2 times in a pointer chase; the measurements can't separate the |
| 3071 | | -check from layout and noise." Keep the conclusion against fat |
| 3072 | | -pointers on other grounds: C interop, record size. |
| 3073 | | - |
| 3074 | | -**3.3 MemBench understates a real `Pool`.** `chaseHandle` indexes a |
| 3075 | | -fixed module array inline: no call, no copy of `T`, no heap |
| 3076 | | -indirection, no `LENDS` count. `Pool.get` (8.2) is a call that copies |
| 3077 | | -`T`, through a `const p: Pool`, into a heap block. `Pool.at` adds a |
| 3078 | | -counted lend. Expect more than the table's figure. |
| 3079 | | - |
| 3080 | | -**3.4 The bounds-check sums** do test the check: the listing shows |
| 3081 | | -`cmp r12, rsi; jae` in the loop. My figures run from -6% to +27%. |
| 3082 | | -"0–15%" is about right, given the noise. |
| 3083 | | - |
| 3084 | | -**3.5 The scanner experiment** repeats: `valgrind --tool=callgrind` |
| 3085 | | -of `S/base/raz` and `S/safe/raz` over `src/Raz.raz` gives 240,850,230 |
| 3086 | | -and 251,594,863 instructions, +4.46%. |
| 3087 | | - |
| 3088 | | -Caveats: |
| 3089 | | - |
| 3090 | | -- The "safe" `Scan` still uses `PTR(cur.buf)` and |
| 3091 | | - `intern(PTR(buf) + start, ...)`, so it isn't safe. The cost of |
| 3092 | | - `intern(s)` taking a slice isn't measured. |
| 3093 | | -- `PTR` is not in v0.19.0, so this `Scan` can't be built by `BOOT` |
| 3094 | | - yet. |
| 3095 | | -- Wall-clock times of the 348,025-line bench were 688 to 891 ms for |
| 3096 | | - the base compiler and 723 to 858 ms for the "safe" one, interleaved |
| 3097 | | - six times. The "safe" one was sometimes faster. Wall clock can't |
| 3098 | | - show 5% here. |
| 3099 | | -- The proposal's "625 to 660 ms" was a quiet moment. At this |
| 3100 | | - session's best (688 ms, 506,000 lines a second) 5% more is about |
| 3101 | | - 480,000, still above the floor. On a slow run (891 ms, 390,000) the |
| 3102 | | - floor already fails today. |
| 3103 | | - |
| 3104 | | -**3.6 "Two 8-byte moves become one 16-byte one" (13.3)** is true only |
| 3105 | | -from memory to memory. Into the rax/rdx pair the ABI returns a slice |
| 3106 | | -in, or from it, a `movdqa` needs `movq` and `pextrq`/`pinsrq`. That is |
| 3107 | | -three instructions and a domain crossing, not none. |
| 3108 | | - |
| 3109 | | -### 4. Library signatures, report sections, quotations |
| 3110 | | - |
| 3111 | | -- **Exact:** |
| 3112 | | - - `Thread.spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR)`; |
| 3113 | | - - `Str.copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL)`; |
| 3114 | | - - `Buf.spare*(var b: Buf; n: INT): []U8`; |
| 3115 | | - - `Buf.bytes*(const b: Buf): []U8`; |
| 3116 | | - - `Map.put*(var m: Map; k: K; v: V): BOOL`; |
| 3117 | | - - `Sys.mmap`, `Sys.munmap`, `Sys.nextEntry(var d: Dir)`, |
| 3118 | | - `Sys.read(fd: INT; buf: []U8): INT`; |
| 3119 | | - - `Item.raz:58` is `frame*: BOOL` with the comment the proposal |
| 3120 | | - describes; |
| 3121 | | - - `C` has 96 `extern`s and `CAbi` 2; `Vec` has 11 fenced lines; |
| 3122 | | - - `src/` is about 11,550 lines of code by a comment-stripping count |
| 3123 | | - (rloc isn't installed), so "about 11,500" holds. |
| 3124 | | -- **`Vec.all`'s comment** is "The elements, until the array next |
| 3125 | | - grows." "Good until the array next grows" is in `Vec`'s module |
| 3126 | | - comment and in `add`'s (capitalized). The quote is fair, but not |
| 3127 | | - `all`'s own words. |
| 3128 | | -- **7.6 is misquoted (9.1).** The report says a variable raced on |
| 3129 | | - "holds no particular value then: a read of it gives a value it had |
| 3130 | | - or was given, or a mixture of their bytes. Nothing else of the |
| 3131 | | - program becomes undefined by it." The proposal puts "holds" in |
| 3132 | | - front of "a value it had or was given", which the report doesn't |
| 3133 | | - say. **Correction:** quote "a read of it gives a value it had or was |
| 3134 | | - given, or a mixture of their bytes". |
| 3135 | | -- **Section 10's "no run time besides the code it uses" (19)** is said |
| 3136 | | - of "a program that doesn't [use C]". The quote is exact. It is a |
| 3137 | | - property of programs without C, not a promise of the language. That |
| 3138 | | - weakens the argument a little; line 7 of the report ("no hidden run |
| 3139 | | - time") supports it better. |
| 3140 | | -- **5.3 (16):** a slice's alignment is set in 5.1 ("a slice is aligned |
| 3141 | | - as an address is"), not 5.3. The sentence to change is there. |
| 3142 | | -- **Elf "writes the executable through `Sys.write`" (5.4):** it uses |
| 3143 | | - `Files.write(path, buf[0..len])` (`Elf.raz:442`). The conclusion |
| 3144 | | - holds. |
| 3145 | | -- **Zig in 12:** `@intToPtr` has been `@ptrFromInt` since Zig 0.11. |
| 3146 | | -- **The Go memory-model wording** in 9.1, "arbitrary memory |
| 3147 | | - corruption", is accurate. |
| 3148 | | -- **Section 15's `ret` list** leaves out `Vec.tryAdd`, which 17 marks. |
| 3149 | | - **Neither list marks `init`'s allocator `keep`** on `Buf`, `Vec`, |
| 3150 | | - `Map`, `List` or `Pool`. Every one stores `a` in its record, and |
| 3151 | | - 5.3(3) says "what it doesn't mark keep, it doesn't hold past the |
| 3152 | | - call". See 5.5 below. |
| 3153 | | - |
| 3154 | | -### 5. Code samples and the proposal's own rules |
| 3155 | | - |
| 3156 | | -**5.1 Today's-raz samples compile.** |
| 3157 | | - |
| 3158 | | -- Appendix 2 and 3 compile. |
| 3159 | | -- 6.4's `greet`, `first` (without `ret`) and `remember` compile. |
| 3160 | | -- 7.1's loop compiles (`W/demo/Samples.raz`). |
| 3161 | | - |
| 3162 | | -**5.2 The help in 6.4 and 14.3 doesn't compile.** "give put a copy |
| 3163 | | -that lasts: `Str.copy(Heap.heap, buf[0..8])`". `Str.copy` has two |
| 3164 | | -results: |
| 3165 | | - |
| 3166 | | -``` |
| 3167 | | -Samples.raz:31:27: error: copy returns several results |
| 3168 | | - help: they go to variables: a, b := copy(...) |
| 3169 | | -``` |
| 3170 | | - |
| 3171 | | -**Correction:** "copy it first: `k, ok := Str.copy(Heap.heap, |
| 3172 | | -buf[0..8])`". |
| 3173 | | - |
| 3174 | | -**5.3 The message positions are off.** The positions shown don't match |
| 3175 | | -the programs: |
| 3176 | | - |
| 3177 | | -- `Kept.raz:10:30`: the call is at line 11, column 27. |
| 3178 | | -- `Escape.raz:14:12`: it is at 15:12. |
| 3179 | | -- `Window.raz:41:13 ... XNextEvent(dpy, ADR(ev))`: the line in |
| 3180 | | - `examples/Window.raz` is 59, `_ := XNextEvent(d, ^U8(ADR(ev)))`. |
| 3181 | | - |
| 3182 | | -Window's help, "or pass ev as a var", is impossible. An `extern`'s |
| 3183 | | -parameters are integers, `BOOL`, reals, pointers or procedures (report |
| 3184 | | -9), and the module is unsafe for its `extern`s anyway. Pick a safe |
| 3185 | | -module's `ADR` for that example. |
| 3186 | | - |
| 3187 | | -**5.4 The Escape message assumes a `head` that 6.2 forbids.** It says |
| 3188 | | -"head's result points into what it is given (ret h)". Appendix 3's |
| 3189 | | -`head(var h: Hex)` has no `ret`, so under 6.2 the first error is in |
| 3190 | | -`head` itself: "returning what is lent by h, not marked ret". |
| 3191 | | - |
| 3192 | | -**5.5 7.3 forbids what 14.2 recommends.** 7.3 says an owner-lent |
| 3193 | | -reference "returned ... is an error". 14.2's option 1 is `proc |
| 3194 | | -name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by |
| 3195 | | -m *)`, which returns bytes of `m.head`, a `Buf`. That is exactly an |
| 3196 | | -owner-lent return. 7.2 also says a `Message` is not an owner, so it |
| 3197 | | -can't lend through `ret` at all. |
| 3198 | | - |
| 3199 | | -The same rule refuses `tools/Widths.raz`'s `load(path; var b: |
| 3200 | | -Buf.Buf): []U8 ... return Buf.bytes(b)`, yet section 15 says `tools/` |
| 3201 | | -has "none found". It also refuses any safe wrapper over `Vec.all` or |
| 3202 | | -`Pool.at`. |
| 3203 | | - |
| 3204 | | -Either 7.3 allows returning through a `ret` parameter that is itself |
| 3205 | | -an owner, or the library's own exports, which do this, need a |
| 3206 | | -different rule from safe code. If returning is allowed, the hold must |
| 3207 | | -pass to the caller, and 7.3 doesn't say how. |
| 3208 | | - |
| 3209 | | -**5.6 Part C stops correct programs, the library's and the compiler's |
| 3210 | | -included.** 7.3 lets a local's hold go only when the procedure |
| 3211 | | -returns, and 7.4 makes `done` stop while a count is above zero. A scan |
| 3212 | | -for a slice held from `Buf.bytes(b)` and a later `Buf.done(b)` in one |
| 3213 | | -procedure (`W/py/heldone.py`) finds: |
| 3214 | | - |
| 3215 | | -- `lib/Opt.raz` `say`: `s := Buf.bytes(b)`, loop, `Buf.done(b)`; |
| 3216 | | -- `src/Parse.raz` `moduleParams`, lines 3696 to 3699 (every generic |
| 3217 | | - instance); |
| 3218 | | -- ravite's `load` (`Ravite.raz:1402`, done at 1411). |
| 3219 | | - |
| 3220 | | -Five more do `defer Buf.done(x)` and then hold `Buf.bytes(x)`: |
| 3221 | | -`examples/Elf.raz` `main`, rnet `Dns.init` and `fromHosts`, and rmacs |
| 3222 | | -`writeFile` and `loadInit`. Whether those stop depends on whether a |
| 3223 | | -hold's let-go runs before or after the deferred statements. The |
| 3224 | | -proposal says only "as a defer would". |
| 3225 | | - |
| 3226 | | -So the compiler itself would stop on every program with a generic |
| 3227 | | -import. 14.2 calls this "a false alarm only when name is never read |
| 3228 | | -again", and these are exactly such cases. Section 15's claim that |
| 3229 | | -every break is found when compiling, but `done`, should count them. |
| 3230 | | -**Correction:** let a hold go at the variable's last use, or at a |
| 3231 | | -`done` of the owner from the same procedure (both known in one pass |
| 3232 | | -only for straight-line code). Or count these breaks and mend them with |
| 3233 | | -`s := []`. |
| 3234 | | - |
| 3235 | | -**5.7 A `Buf` or `Vec` over an `Arena` has no safe form.** By 8.4, |
| 3236 | | -`Arena.allocator(ar)` is lent by `ar`, and a lent value can't be |
| 3237 | | -stored in a record (6.2) or given to `keep` (5.5 above). `Buf.init` |
| 3238 | | -keeps its allocator, so `Buf.init(b, Arena.allocator(ar))` is an |
| 3239 | | -error. This pattern appears in: |
| 3240 | | - |
| 3241 | | -- `Fmt.eprint`; |
| 3242 | | -- `Fmt`'s test; |
| 3243 | | -- `Buf`'s test; |
| 3244 | | -- `examples/Sh.raz`, lines 88 and 188. |
| 3245 | | - |
| 3246 | | -So "Fmt ... can be safe" (5.4, 15, 17) and "Sh ... mended by var" (5.4, |
| 3247 | | -15) fail. `Fmt.format` also takes `^Buf.Buf` with `nil` for standard |
| 3248 | | -output, which needs an interface change. |
| 3249 | | - |
| 3250 | | -**5.8 Other "can be safe" claims (5.4).** |
| 3251 | | - |
| 3252 | | -- `Files.arg` *is* `ARGV()[i]` and pointer indexing |
| 3253 | | - (`Files.raz:10-13`). 5.1 fences `ARGV` and names `Files.arg` as the |
| 3254 | | - safe form, so `Files` must stay unsafe, or `ARGV` must move into a |
| 3255 | | - trusted module. |
| 3256 | | -- `Str.copy` and `Str.free` index and free a `Mem.alloc` pointer. `Str` |
| 3257 | | - can be safe only if `Mem` gains a safe slice allocation. Section 17 |
| 3258 | | - doesn't add one, and `free` is an `unsafe proc` in a module 17 calls |
| 3259 | | - safe. |
| 3260 | | -- `Lock` needs E.4 (`CAS` on a variable) first. |
| 3261 | | -- `examples/Workers.raz` uses `Thread.spawn(work, nil)` and |
| 3262 | | - `XADD(ADR(next), 1)`. It needs `Task` and E.4, not `var`. |
| 3263 | | - |
| 3264 | | -**5.9 Owners can't sit in generic containers.** 7.6 forbids passing an |
| 3265 | | -owner as a value parameter or copying it. `Vec.push(x: T)`, |
| 3266 | | -`Pool.add(keep x: T)`, `Map.put(..., v: V)` and `List.push` all copy. |
| 3267 | | -So `Vec(Buf.Buf)`, `Pool(Window)` where a `Window` holds a `Buf`, and |
| 3268 | | -`Names(Buf.Buf)` can't be used. Yet 14.2 turns rmacs's windows, which |
| 3269 | | -hold `Buf`s, into a `Pool(Window)`. The proposal needs an `add` that |
| 3270 | | -gives a zero slot in place (`Pool.at` after a zero `add`) and says |
| 3271 | | -that copies are refused there. |
| 3272 | | - |
| 3273 | | -### 6. The compiler's cost (section 18) |
| 3274 | | - |
| 3275 | | -- **A, 120:** about right, perhaps to 150. It needs `unsafe proc`'s |
| 3276 | | - rules in `Sym.same` and assignability, the two contextual places the |
| 3277 | | - word stands, the interface check, and a generic instance taking its |
| 3278 | | - module's mark. |
| 3279 | | -- **B, 300–450: low.** PROPOSALS' own second review (its open |
| 3280 | | - question 4, PROPOSALS.md line 476) revised part 3 to "400 to 600 |
| 3281 | | - lines, not 250 to 400", for slices alone. This proposal adds |
| 3282 | | - pointers, owners as lenders, `match` names (10.4), literal parts and |
| 3283 | | - generic instances checked one by one. Likely 550 to 800. |
| 3284 | | -- **C, 200: low.** |
| 3285 | | - - Hidden hold slots per local. |
| 3286 | | - - A raise at each call that returns an owner-lent value. |
| 3287 | | - - A lower at the end of each statement. Only `const`'s temporaries |
| 3288 | | - have such a point today. |
| 3289 | | - - A let-go on every exit, `try` and early `return` included, with |
| 3290 | | - an order against `defer` (5.6). |
| 3291 | | - - The copy check at assignment, value parameters, results, literals, |
| 3292 | | - comparison, views and generic instances (5.9). |
| 3293 | | - - Likely 300 to 450. |
| 3294 | | -- **D, 20:** plausible. |
| 3295 | | -- **E, 80: low.** |
| 3296 | | - - 16-byte alignment of slices changes record layout in `Sym`, and |
| 3297 | | - frame-slot and temporary alignment in `Gen`. |
| 3298 | | - - Every slice load and store goes through xmm, with |
| 3299 | | - `movq`/`pinsrq`/`pextrq` for the rax/rdx pair. `X64` today |
| 3300 | | - encodes `movdqu` but not those. |
| 3301 | | - - Records holding slices are copied by `rep movsb` past `MaxMoves`. |
| 3302 | | - - `CAS`, `XCHG` and `XADD` change from pointer to variable in |
| 3303 | | - `Parse` and `Item`. |
| 3304 | | - - `lock xadd` when `Thread` is imported. |
| 3305 | | - - Likely 150 to 250. |
| 3306 | | -- **F, 20:** plausible, since `defer`'s reserved slots exist. |
| 3307 | | -- **Messages, 100:** plausible for about 10 new kinds with help. |
| 3308 | | - |
| 3309 | | -**In all, likely 1,250 to 1,700, not 840 to 990.** That still fits |
| 3310 | | -under 14,000, from about 11,550, but with much less room than 18 |
| 3311 | | -suggests for the documentation the house style requires. |
| 3312 | | - |
| 3313 | | -The `src/` rewrite is also larger than "35 grown arrays". `Chunk.chunks`, |
| 3314 | | -`Chunk.text` and `Chunk.rodata` are exported and indexed from `Item`, |
| 3315 | | -`Parse`, `Gen`, `Raz`, `Elf`, `Link` and `X64`: about 250 lines of |
| 3316 | | -`p[i]` and `p[a..b]` outside `Scan`. Each would become a `Vec.all(...)` |
| 3317 | | -with a counted lend, often in `X64`'s emitter and `Link`'s patching, |
| 3318 | | -which are hot. 13.1's "cost nothing measurable" for these is |
| 3319 | | -unmeasured. |
| 3320 | | - |
| 3321 | | -### 7. `src/` becoming safe (2.2, 5.4, 15) |
| 3322 | | - |
| 3323 | | -The plan is plausible module by module, with three gaps: |
| 3324 | | - |
| 3325 | | -- **Elf:** its buffers are a `grab`/`regrab` byte array (a `Buf`), plus |
| 3326 | | - `putBytes(ADR(s[0]), LEN(s))` (a slice parameter) and |
| 3327 | | - `sizeTables(ADR, ADR)` (`var`). It can be safe. |
| 3328 | | -- **Diag:** `files` is a grown array (`Vec`), and two `^Buf.Buf(grab)` |
| 3329 | | - become `NEW`. `File.buf: ^U8` keeps a pointer to the scanner's |
| 3330 | | - source. As a slice it is lasting only if `Scan`, unsafe, promises |
| 3331 | | - so. It can be safe. |
| 3332 | | -- **Link:** four arrays sized once from `Scan.grab`, then `p[i]` 63 |
| 3333 | | - times. They need `Vec(INT)` with `resize`, or a typed `grab` that |
| 3334 | | - gives a slice. Safe, at the cost of checks on the linker's paths. |
| 3335 | | -- **Chunk:** grown record arrays exported to every module, and |
| 3336 | | - `ADR(chunks[n])`. Safe as `Vec`s, but see 6 on cost and lines. |
| 3337 | | -- **X64:** `said` is grown, `^Buf.Buf(grab)` becomes `NEW`, and the |
| 3338 | | - `isReg` out-parameters and `operand(ADR(ao[an]))` become `var`. It |
| 3339 | | - writes `Chunk.text` per byte. Safe, with that cost. |
| 3340 | | -- **Gaps:** |
| 3341 | | - - `Raz.raz` needs its `SYSCALL`s and `ARGV() + first` replaced: |
| 3342 | | - `Sys.memFile`, and `Sys.execve` with an environment built from |
| 3343 | | - `Sys.envAt`. |
| 3344 | | - - `Scan.grab`'s callers outside `Scan` (`Item.raz:2154`, |
| 3345 | | - `Parse.raz:452`, `Parse.raz:3812`, `Raz.raz:165`) index its |
| 3346 | | - `^U8`. `grab` must give a slice. |
| 3347 | | - - `Parse.moduleParams` stops at run time under part C (5.6). |
| 3348 | | - |
| 3349 | | -"`src/` keeps one unsafe module: Scan" can be reached, but it is |
| 3350 | | -several hundred changed lines, not the table's 55 sites. |
| 3351 | | - |
| 3352 | | -### Confirmed |
| 3353 | | - |
| 3354 | | -- The demos' outputs and status 0, and that each does the undefined |
| 3355 | | - thing claimed. |
| 3356 | | -- The callgrind counts, +4.5%. |
| 3357 | | -- Appendix 1's per-module tallies, as the aggregator gives them, read |
| 3358 | | - as lines. |
| 3359 | | -- The hand-free counts. |
| 3360 | | -- rmacs's 560 and 556, and ravite's 202, `ADR`s. |
| 3361 | | -- About 36 held `Buf.bytes`/`Windows.all` slices. |
| 3362 | | -- `tools/` has no fenced operation. |
| 3363 | | -- Threads in rnet (`Http`'s server, tests) and rsqlite (`Sqlite`'s |
| 3364 | | - test) only. |
| 3365 | | -- Lines per repository, about 50,000. |
| 3366 | | -- `src/`'s 7 frees all in grown arrays. |
| 3367 | | -- The cited signatures, and `Item.raz:58`. |
| 3368 | | -- 7.3's and 8's text on what isn't caught. |
| 3369 | | -- `C` 96 and `CAbi` 2 `extern`s. |
| 3370 | | -- The sums' bounds check really emitted. |
| 3371 | | -- `src/` about 11,500 lines of code. |
| 3372 | | - |
| 3373 | | ---- |
| 3374 | | - |
| 3375 | | -## Appendix 7: adversarial review, porting real code |
| 3376 | | - |
| 3377 | | -Section 14 says most raz stays as it is and the pain is narrow. To |
| 3378 | | -test that, six pieces of real code were ported on paper under parts A |
| 3379 | | -to F, read as strictly as a compiler would read them: rnet's `Http` |
| 3380 | | -with its test servers, rmacs's buffers and windows, the compiler's |
| 3381 | | -name table, grown arrays, files and scopes, the library's `Fmt`, `Opt`, |
| 3382 | | -`Map` and the containers, `examples/Sh.raz`, and rjson's `Json`. About |
| 3383 | | -25,000 lines were read; about 900 of them change for parts B to F, 4%, |
| 3384 | | -on top of the `ADR`s the fence turns into `var`, which `STANDARDS.md` |
| 3385 | | -asks for anyway. By lines, then, the claim holds. By kind it doesn't. |
| 3386 | | -The changes gather in the one type each piece is built round |
| 3387 | | -(`Http.Message`, rmacs's `Text` and its accessors, `Chunk`'s arrays, |
| 3388 | | -`Sh`'s arena, `Json.Doc`), and each of those needs a redesign, not a |
| 3389 | | -mark. Three rules cause most of it: an owner's lend can't be returned |
| 3390 | | -by any procedure but the owner's own, can't sit in a record, and the |
| 3391 | | -fence has no safe form for a pointer to "the caller's state". The |
| 3392 | | -port also found six holes in the rules as written (A7.7): four let |
| 3393 | | -unsafe code through, and two leave a trap or an undecided stop. It |
| 3394 | | -found eight places in correct code that would stop at run time with |
| 3395 | | -`done` while held, and no real bug in today's code. |
| 3396 | | -Most of the pain goes away with seven additions that weaken nothing |
| 3397 | | -(A7.10). |
| 3398 | | - |
| 3399 | | -### A7.1 How it was done |
| 3400 | | - |
| 3401 | | -Each piece was first brought to today's library, so that an `ADR` at a |
| 3402 | | -call where the library now takes `var` doesn't count. Then each rule |
| 3403 | | -was applied to every line. Where the proposal is unclear, the stricter |
| 3404 | | -reading was taken, and noted: |
| 3405 | | - |
| 3406 | | -- **A pointer parameter is lent by its parameter** (6.1, 6.5). Storing |
| 3407 | | - one in a module variable or a record needs `keep`. |
| 3408 | | -- **Reading through a pointer gives a lasting value.** Only lasting |
| 3409 | | - values may be stored through a pointer (6.2), so what is read back |
| 3410 | | - is lasting too. The more lenient reading is taken here. |
| 3411 | | -- **An owner's lend may be returned only through a `ret` parameter |
| 3412 | | - that is the owner itself**, as `Buf.bytes` does. 7.3 says that |
| 3413 | | - returning one is an error. 6.2 allows it through `ret`. The middle |
| 3414 | | - reading is the only one under which the caller still knows whose |
| 3415 | | - count to raise. |
| 3416 | | -- **A local array or record may not hold an owner's lend** (7.3), not |
| 3417 | | - even one of slices. |
| 3418 | | - |
| 3419 | | -"Changed" counts lines touched, written or removed, against the |
| 3420 | | -source as it stands. The counts come from reading and `grep`, not from |
| 3421 | | -a compiler, and are good to about a fifth. |
| 3422 | | - |
| 3423 | | -### A7.2 rnet's `Http` (`src/Http.raz`, `src/Conn.raz`, `test/Webserver.raz`, `test/Server.raz`, `examples/Hello.raz`) |
| 3424 | | - |
| 3425 | | -**What the rules reject.** |
| 3426 | | - |
| 3427 | | -| Line or construct | Rule | The compiler's error | |
| 3428 | | -|---|---|---| |
| 3429 | | -| `m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}` (`parseHeaders`), `l` a slice of `Buf.bytes(m^.head)` | 6.2, 7.3 | `Buf.bytes(m^.head) is lent by m^.head, which counts what it lends: hold it in a slice variable` | |
| 3430 | | -| `m^.raw := text`, `m^.method := l[0..i]`, `m^.target := ...`, `m^.reason := ...` | 7.3 | the same | |
| 3431 | | -| `m^.body := Buf.bytes(ADR(m^.data))` (`readWhole`) | 7.3 | the same | |
| 3432 | | -| `res^.body := Buf.bytes(ADR(text))` (Webserver, twice) | 7.3 | the same, in the program that uses `Http` | |
| 3433 | | -| `Http.add(res, "Location", Buf.bytes(ADR(text)))` (Webserver, twice), `add(ADR(res), "Date", Buf.bytes(ADR(when)))` (`serveConn`) | 6.2: `add` stores `name` and `value`, so it is `keep` | `Http.add keeps its value, and Buf.bytes(text) is lent by text` | |
| 3434 | | -| `head := m^.head; ... m^ := {..., head: head, data: data}` (`reset`) | 7.6 | `a Buf.Buf owns memory, and can't be copied` | |
| 3435 | | -| `out := req^` (`open`): a `Message` with two `Buf`s, copied | 7.6 | the same | |
| 3436 | | -| `try parseUrl(Buf.bytes(ADR(here)), ADR(u))`: `parseUrl` keeps slices of `s` in `u^` | 6.2 | `parseUrl keeps s, and Buf.bytes(here) is lent by here` | |
| 3437 | | -| `cl^.scheme := u^.scheme` (`connect`), always `"http"` or `"https"` | 6.2: `u`'s parts are lent as `u` is | `u.scheme is lent by u, a parameter not marked keep` | |
| 3438 | | -| `r^ := {conn: c, ...}` (`startBody`), `c` an `ADR` of a local `Conn` or of `cl^.conn` | 5.1, then 6.2 | `ADR is for unsafe modules`; with `var c`, `c is a var parameter and can't be kept` | |
| 3439 | | -| `return ADR(cl^.body), nil` (`open`) | 5.1 | `ADR is for unsafe modules` | |
| 3440 | | -| `Thread.spawn(work, ^U8(s))`, `s := ^Server(arg)` | 5.1, 5.2 | `a conversion to a pointer is for unsafe modules`; `Thread.spawn is an unsafe procedure` | |
| 3441 | | -| `Handler = proc(req, res: ^Message; arg: ^U8)`: a safe handler can't turn `arg` back into its own type | 5.1 | the same, in every program with state | |
| 3442 | | -| `t := ^Text(c^.state)` (`Http`'s and `Conn`'s tests); `Conn.state: ^U8` | 5.1 | the same | |
| 3443 | | -| `proc trim(s: []U8): []U8` returns `s` | 6.2 | `trim's result is lent by s, which isn't marked ret` | |
| 3444 | | -| every `^Message`, `^Conn.Conn`, `^Reader`, `^Url`, `^Client`, `^Server` parameter given `ADR(local)`: 228 `ADR`s in `Http.raz`, 37 in `Conn.raz` | 5.1 | `ADR is for unsafe modules` | |
| 3445 | | - |
| 3446 | | -The last row is what `STANDARDS.md` asks for, `var` or `const`. It |
| 3447 | | -changes `Http`'s whole interface, and every program that calls it. |
| 3448 | | -It is counted apart below. |
| 3449 | | - |
| 3450 | | -Section 14.2 offers a way out: `Http` says `unsafe;` and keeps |
| 3451 | | -`Message` as it is. That breaks the proposal's own rule 4 of 5.3. A |
| 3452 | | -safe program can read `req^.body` after `Http.done(req)`, so the |
| 3453 | | -exported slice fields are just what a safe module could misuse. And |
| 3454 | | -the programs that *write* messages (Webserver, `Hello`) are safe |
| 3455 | | -modules: they still can't store a `Buf`'s bytes in `res^.body`. So the |
| 3456 | | -spans are the only design that compiles. |
| 3457 | | - |
| 3458 | | -**Rewritten.** The text a message holds goes in its own buffers, as |
| 3459 | | -spans. Everything a program gives it is copied in. |
| 3460 | | - |
| 3461 | | -``` |
| 3462 | | -(* Before *) |
| 3463 | | -Header* = record |
| 3464 | | - name*, value*: []U8; |
| 3465 | | -end; |
| 3466 | | -Message* = record |
| 3467 | | - method*, target*: []U8; |
| 3468 | | - status*: INT; |
| 3469 | | - reason*: []U8; |
| 3470 | | - minor*: INT; |
| 3471 | | - headers*: [MaxHeaders]Header; |
| 3472 | | - n*: INT; |
| 3473 | | - body*: []U8; |
| 3474 | | - maxBody*: INT; |
| 3475 | | - close*: BOOL; |
| 3476 | | - raw*: []U8; |
| 3477 | | - head, data: Buf.Buf; |
| 3478 | | -end; |
| 3479 | | - |
| 3480 | | -(* After *) |
| 3481 | | -Span = record at, len: INT; end; (* bytes at up to at + len of one of the buffers *) |
| 3482 | | -Header = record name, value: Span; end; (* in head *) |
| 3483 | | -Message* = record |
| 3484 | | - status*, minor*, n*, maxBody*: INT; |
| 3485 | | - close*: BOOL; |
| 3486 | | - method, target, reason, raw: Span; (* in head *) |
| 3487 | | - headers: [MaxHeaders]Header; |
| 3488 | | - body: Span; (* in data *) |
| 3489 | | - head, data: Buf.Buf; (* all of its text, read or to be written *) |
| 3490 | | -end; |
| 3491 | | - |
| 3492 | | -(* s added to b, and where it stands there *) |
| 3493 | | -proc put(var b: Buf.Buf; s: []U8): Span; |
| 3494 | | -begin |
| 3495 | | - Buf.str(b, s); |
| 3496 | | - return {at: b.len - LEN(s), len: LEN(s)}; |
| 3497 | | -end; |
| 3498 | | - |
| 3499 | | -proc add*(var m: Message; name, value: []U8): ERROR; |
| 3500 | | -begin |
| 3501 | | - if m.n = MaxHeaders then return TooManyHeaders; end; |
| 3502 | | - m.headers[m.n] := {name: put(m.head, name), value: put(m.head, value)}; |
| 3503 | | - INC(m.n); |
| 3504 | | - return nil; |
| 3505 | | -end; |
| 3506 | | - |
| 3507 | | -proc setBody*(var m: Message; s: []U8); (* new: s copied into the message *) |
| 3508 | | -begin |
| 3509 | | - Buf.reset(m.data); |
| 3510 | | - m.body := put(m.data, s); |
| 3511 | | -end; |
| 3512 | | - |
| 3513 | | -(* The bytes of sp in b *) |
| 3514 | | -proc bytesOf(ret const b: Buf.Buf; sp: Span): []U8; |
| 3515 | | -begin |
| 3516 | | - return Buf.bytes(b)[sp.at..sp.at + sp.len]; (* fine: b is the owner, and ret *) |
| 3517 | | -end; |
| 3518 | | - |
| 3519 | | -proc target*(ret const m: Message): []U8; |
| 3520 | | -begin |
| 3521 | | - return bytesOf(m.head, m.target); (* refused as written: lent by m.head, a part of m; see A7.7, H2 *) |
| 3522 | | -end; |
| 3523 | | -``` |
| 3524 | | - |
| 3525 | | -`target`, `method`, `reason`, `raw`, `body`, `header`, `name(i)` and |
| 3526 | | -`value(i)` are new accessors, and the setters `setMethod`, |
| 3527 | | -`setTarget`, `setReason` and `setBody` are new too. They need the |
| 3528 | | -relaxation R1 of A7.10 to compile at all. In the programs: |
| 3529 | | - |
| 3530 | | -``` |
| 3531 | | -(* Before (Webserver) *) |
| 3532 | | -path := req^.target; |
| 3533 | | -Fmt.write(ADR(text), "{}", [Fmt.int(conns)]); |
| 3534 | | -res^.body := Buf.bytes(ADR(text)); |
| 3535 | | - |
| 3536 | | -(* After *) |
| 3537 | | -path := Http.target(req); (* held, and counted on req's head *) |
| 3538 | | -Fmt.write(text, "{}", [Fmt.int(conns)]); |
| 3539 | | -Http.setBody(res, Buf.bytes(text)); (* copied *) |
| 3540 | | -``` |
| 3541 | | - |
| 3542 | | -`reset` keeps its buffers by moving them out and back: |
| 3543 | | - |
| 3544 | | -``` |
| 3545 | | -proc reset*(var m: Message); |
| 3546 | | -var head, data: Buf.Buf; max: INT; |
| 3547 | | -begin |
| 3548 | | - Buf.take(m.head, head); |
| 3549 | | - Buf.take(m.data, data); |
| 3550 | | - max := m.maxBody; |
| 3551 | | - m := {minor: 1, maxBody: max}; (* the owners left out: empty *) |
| 3552 | | - Buf.take(head, m.head); |
| 3553 | | - Buf.take(data, m.data); |
| 3554 | | - Buf.reset(m.head); |
| 3555 | | - Buf.reset(m.data); |
| 3556 | | -end; |
| 3557 | | -``` |
| 3558 | | - |
| 3559 | | -`m := {minor: 1, maxBody: max}` alone also compiles. It drops both |
| 3560 | | -buffers' memory and their allocator, so the next `Buf.add` calls a |
| 3561 | | -`nil` allocator and stops (A7.7, H4). |
| 3562 | | - |
| 3563 | | -A `Reader` can't hold the `Conn` it reads from, since no safe pointer |
| 3564 | | -to a local `Conn`, or to `cl^.conn`, exists. Either the `Conn` comes |
| 3565 | | -from `NEW`, and a `Client`'s 16 KB buffer can never be freed (D), or |
| 3566 | | -the reader takes the connection on each call: |
| 3567 | | - |
| 3568 | | -``` |
| 3569 | | -proc read*(var r: Reader; var c: Conn.Conn; b: []U8): (INT, ERROR); |
| 3570 | | -proc readBody*(var cl: Client; b: []U8): (INT, ERROR); (* open no longer returns ^Reader *) |
| 3571 | | -``` |
| 3572 | | - |
| 3573 | | -`parseUrl` fills a local `Url` with slices of a `Buf`, and the `Url` |
| 3574 | | -dies before the `Buf` does. That is PROPOSALS' false alarm of "a record |
| 3575 | | -that lives in the frame". Returning the `Url` as a result doesn't help, |
| 3576 | | -since a local record may not hold a lend (7.3). The cure that compiles |
| 3577 | | -copies the URL into a frame array, whose slices a local record *may* |
| 3578 | | -hold: |
| 3579 | | - |
| 3580 | | -``` |
| 3581 | | -var here: [MaxUrl]U8; hereLen: INT; u: Url; |
| 3582 | | -... |
| 3583 | | -try parseUrl(here[0..hereLen], u); (* frame-lent: allowed in the local u; parseUrl's s is keep *) |
| 3584 | | -``` |
| 3585 | | - |
| 3586 | | -So a URL gets a fixed limit only to get past the rule. `cl^.scheme := |
| 3587 | | -u.scheme` becomes `cl.tls := u.scheme = "https"`. The server's threads |
| 3588 | | -become `Task(^Server)`, `Hello` makes its `Server` with `NEW`, and |
| 3589 | | -`arg: ^U8` goes from `Handler`. A server with state keeps it in module |
| 3590 | | -variables, shared by its workers with no lock unless it uses |
| 3591 | | -`Lock.Guarded`. The tests that cast `Conn.state` go into an unsafe |
| 3592 | | -module of their own. |
| 3593 | | - |
| 3594 | | -**Count.** About 2,700 lines, tests included. The fence alone |
| 3595 | | -(`ADR` to `Http`'s own pointer parameters, casts): about 330 lines. |
| 3596 | | -Parts B to F: `Message` and its accessors and setters about 120, the |
| 3597 | | -readers and writers that use them about 40, `reset` and `open`'s copy |
| 3598 | | -15, `Url` 15, `Reader` and `Client` 20, threads and the handler 10, |
| 3599 | | -Webserver 8, `Server` 16, `Hello` 3. About 230 lines in all, 9%. |
| 3600 | | - |
| 3601 | | -**Judgement: worse.** Every field is now a call. Each header and each |
| 3602 | | -body a handler makes is copied once more, and a 100,000-byte body made |
| 3603 | | -in a `Buf` is copied whole. Fixed limits come in only to dodge a rule |
| 3604 | | -(`MaxUrl`), and handlers lose their context. In return, "good until the |
| 3605 | | -message is read again or reset", which `Http`'s header comment asks a |
| 3606 | | -reader to remember, is now checked. |
| 3607 | | - |
| 3608 | | -**Contortions and false alarms:** `parseUrl` into a frame array; the |
| 3609 | | -scheme as a BOOL; `Reader` without its `Conn`; the accessors, which |
| 3610 | | -don't compile without R1. **Run-time stops in correct code:** none |
| 3611 | | -found. **Real bugs caught:** none. `reset`'s copy of the `Buf`s, which |
| 3612 | | -section 7.6 calls "safe by luck", is right: the copies are put back at |
| 3613 | | -once. `res^.body := req^.body` in `test/Server.raz` is right by the |
| 3614 | | -order `serveConn` keeps. |
| 3615 | | - |
| 3616 | | -### A7.3 rmacs (`src/Core.raz`, `Commands.raz`, `Text.raz`, `Mini.raz`, `Dired.raz`, `Windows.raz`) |
| 3617 | | - |
| 3618 | | -**What the rules reject.** |
| 3619 | | - |
| 3620 | | -| Line or construct | Rule | The compiler's error | |
| 3621 | | -|---|---|---| |
| 3622 | | -| `Text`: `data: ^U8`, `Mem.alloc`, `Mem.free`, `t^.data[i]`, `^U8(t^.changes)` | 5.1, 5.2 | `Mem.free is an unsafe procedure`, `indexing a pointer is for unsafe modules` | |
| 3623 | | -| `proc slice*(lo, hi: I64): []U8; ... return Text.slice(ADR(b^.t), lo, hi)` (`Core`), 12 callers | 7.3: returned, lent by the owner `b^.t`, which no parameter names | `Text.slice(b^.t, lo, hi) is lent by b^.t, which counts what it lends, and can't be returned` | |
| 3624 | | -| `proc text: []U8` (`Mini`), the same through `Core.mini^.t` | 7.3 | the same | |
| 3625 | | -| `proc nameAt(i: I64): []U8` (`Dired`), a slice of the module `Buf` `names` | 7.3 | the same | |
| 3626 | | -| `bufferNames(i)` returns `Buf.bytes(ADR(choices[i]^.name))`, as a `Mini.Names` procedure value | 7.3 | the same; and no mark on `Mini.Names` could allow it | |
| 3627 | | -| `Heap.heap^.free(Heap.heap, ^U8(x))` (`Core.kill`), four in `Windows` | 5.1, 5.2, D | `Heap's free is an unsafe procedure` | |
| 3628 | | -| `t := ADR(w^.buf^.t)` (`Rmacs.colours`) | 5.1 | `ADR is for unsafe modules` | |
| 3629 | | -| `DEC(out^.len)`, `DEC(line.len)`, `s.len := ...`, `t^.log.len := ...`: 7 writes of a `Buf`'s `len` | 5.3 rule 4 (see A7.7, H3) | nothing, as the proposal stands: a safe hole | |
| 3630 | | -| `selected := w`, `shown := x`, `Core.b := x`: a pointer parameter stored in a module variable (8 procedures) | 6.2, read strictly | `w is lent by the parameter w; mark it keep` | |
| 3631 | | -| 139 `ADR`s given to rmacs's own pointer parameters (`Text.len(ADR(b^.t))`, `Mini.read(..., ADR(answer))`) | 5.1 | `ADR is for unsafe modules` | |
| 3632 | | - |
| 3633 | | -**Rewritten.** No procedure but the owner's own can hand out what an |
| 3634 | | -owner lends, so `Core.slice` can't be written, and each of its twelve |
| 3635 | | -callers names the text itself: |
| 3636 | | - |
| 3637 | | -``` |
| 3638 | | -(* Before *) |
| 3639 | | -Buf.str(ADR(Core.tmp), Core.slice(p, b)); |
| 3640 | | -(* After *) |
| 3641 | | -Buf.str(Core.tmp, Text.slice(Core.b^.t, p, b)); |
| 3642 | | -``` |
| 3643 | | - |
| 3644 | | -A procedure value can't return a lend either, so `Mini.Names` changes |
| 3645 | | -to write the name into a buffer it is given: |
| 3646 | | - |
| 3647 | | -``` |
| 3648 | | -(* Before *) |
| 3649 | | -Names* = proc(i: I64): ([]U8, BOOL); |
| 3650 | | -proc bufferNames(i: I64): ([]U8, BOOL); |
| 3651 | | -begin |
| 3652 | | - if i >= numChoices then return "", false; end; |
| 3653 | | - return Buf.bytes(ADR(choices[i]^.name)), true; |
| 3654 | | -end; |
| 3655 | | - |
| 3656 | | -(* After *) |
| 3657 | | -Names* = proc(i: I64; var name: Buf.Buf): BOOL; (* the i-th name, into name *) |
| 3658 | | -proc bufferNames(i: I64; var name: Buf.Buf): BOOL; |
| 3659 | | -begin |
| 3660 | | - if i >= numChoices then return false; end; |
| 3661 | | - Buf.reset(name); |
| 3662 | | - Buf.str(name, Buf.bytes(choices[i]^.name)); |
| 3663 | | - return true; |
| 3664 | | -end; |
| 3665 | | -``` |
| 3666 | | - |
| 3667 | | -`gather`'s loop and `commandNames` change to match: about 10 lines. A |
| 3668 | | -killed buffer and a closed window are not freed. Their contents are |
| 3669 | | -(`Text.done`, `Buf.done`), and the empty record, about 200 bytes, is |
| 3670 | | -kept to the end of the run: |
| 3671 | | - |
| 3672 | | -``` |
| 3673 | | -Text.done(x^.t); |
| 3674 | | -Buf.done(x^.name); |
| 3675 | | -Buf.done(x^.path); |
| 3676 | | -(* x itself is kept, empty: part D lets no safe module free it *) |
| 3677 | | -``` |
| 3678 | | - |
| 3679 | | -That is five lines taken out. The `Pool(Buffer)` that section 14.2 |
| 3680 | | -offers would touch about 370 dereferences of `^Buffer` and `^Window`. |
| 3681 | | -`Pool` can't take a `Buffer` at all anyway: `add(var p; keep x: T)` |
| 3682 | | -passes `x` by value, and a `Buffer` holds owners (7.6). `Pool` would |
| 3683 | | -need an `alloc(var p): Handle` that hands out a zeroed slot. |
| 3684 | | - |
| 3685 | | -`Text` either says `unsafe;` and carries the owner's protocol by hand |
| 3686 | | -(a `LENDS` field, retiring in `room`, `ret` on `slice`: about 25 |
| 3687 | | -lines), or is rebuilt on `Vec(U8)` and `Vec(Change)` (about 60 lines). |
| 3688 | | -Its gap moves under a slice that is held (`moveGap`), which the rules |
| 3689 | | -let pass, since it is memory-safe. That is right: today's comment, |
| 3690 | | -"good until the next change", stays a comment. |
| 3691 | | - |
| 3692 | | -**Count.** 4,931 lines. The fence alone: about 160 (the 139 `ADR`s, |
| 3693 | | -the casts, `Text`'s heading). Parts B to F: `Text` 25, the four |
| 3694 | | -accessors and their 20 callers 35, `Mini.Names` 10, `colours` 7, frees |
| 3695 | | -5, `len` writes 7: about 90, 2%. |
| 3696 | | - |
| 3697 | | -**Judgement: the same.** Twelve calls grow a little longer. |
| 3698 | | -`Mini.Names` copies each name once per keystroke of ido, about 256 |
| 3699 | | -small copies, which doesn't show. |
| 3700 | | - |
| 3701 | | -**Run-time stops in correct code.** `writeFile` holds `p := |
| 3702 | | -Buf.bytes(abs)` under `defer Buf.done(abs)`, and `loadInit` holds |
| 3703 | | -`s := Buf.bytes(b)` under `defer Buf.done(b)`. Section 7.3 lets a |
| 3704 | | -hold go "when the procedure returns", but doesn't say whether that is |
| 3705 | | -before or after its deferred statements. If after, `C-x C-w` stops |
| 3706 | | -the editor every time, and so does starting it with a `~/.rmacs` |
| 3707 | | -(A7.7, H5). **Real bugs caught:** none. No self- |
| 3708 | | -append or kill-while-held was found. `killBuffer` and `deleteWindow` |
| 3709 | | -take care with `Core.b` and `Core.selected` already. |
| 3710 | | - |
| 3711 | | -### A7.4 The compiler (`src/Scan.raz`, `Chunk.raz`, `Diag.raz`, `Sym.raz`, and their users) |
| 3712 | | - |
| 3713 | | -**Scan's name table: can be safe, and is clearer.** Today names are |
| 3714 | | -three hand-grown arrays and a table, all freed and copied by hand, and |
| 3715 | | -the bytes sit in 64 KB chunks that are never freed. Safe, the chunks |
| 3716 | | -come from `NEW` (lasting, so their slices last), and the arrays are |
| 3717 | | -`Vec`s: |
| 3718 | | - |
| 3719 | | -``` |
| 3720 | | -var |
| 3721 | | - chunk: ^[PoolChunk]U8; (* from NEW, never freed: its slices last *) |
| 3722 | | - chunkUsed: INT; |
| 3723 | | - names: Strs.Vec; (* import Strs := Vec([]U8) *) |
| 3724 | | - hashes, table: Ints.Vec; (* import Ints := Vec(INT) *) |
| 3725 | | - |
| 3726 | | -proc intern*(s: []U8): INT; (* was intern(p: ^U8; n: INT), called with ADR(s[0]), LEN(s) *) |
| 3727 | | -var h, i, k: INT; t, hs: []INT; p: []U8; |
| 3728 | | -begin |
| 3729 | | - h := hash(s); |
| 3730 | | - t := Ints.all(table); |
| 3731 | | - hs := Ints.all(hashes); |
| 3732 | | - i := h & tableMask; |
| 3733 | | - while t[i] # 0 do |
| 3734 | | - k := t[i] - 1; |
| 3735 | | - if (hs[k] = h) and (Strs.get(names, k) = s) then return k; end; |
| 3736 | | - i := (i + 1) & tableMask; |
| 3737 | | - end; |
| 3738 | | - if (chunk = nil) or (LEN(s) > PoolChunk - chunkUsed) then NEW(chunk, Heap.heap); chunkUsed := 0; end; |
| 3739 | | - p := chunk^[chunkUsed..chunkUsed + LEN(s)]; |
| 3740 | | - COPY(p, s); |
| 3741 | | - INC(chunkUsed, LEN(s)); |
| 3742 | | - k := names.len; |
| 3743 | | - Strs.push(names, p); (* keep: p lasts *) |
| 3744 | | - Ints.push(hashes, h); (* may grow hashes: hs is retired, and not read again *) |
| 3745 | | - t[i] := k + 1; |
| 3746 | | - t := []; (* or grow's Ints.done(table) stops the program *) |
| 3747 | | - hs := []; |
| 3748 | | - if (k + 1) * 2 > tableMask then grow; end; |
| 3749 | | - return k; |
| 3750 | | -end; |
| 3751 | | -``` |
| 3752 | | - |
| 3753 | | -Two things here aren't in the proposal. `Strs.get` is new: `return |
| 3754 | | -Strs.all(names)[n]` is refused, since an element of an owner's lend is |
| 3755 | | -lent (6.1), though what it holds was stored by `keep` and lasts (A7.10, |
| 3756 | | -R4). And `t := []` before `grow` is needed only to get past `done`'s |
| 3757 | | -stop. Today's `intern` checks `n > chunkLeft` and then copies `n` |
| 3758 | | -bytes into a 64 KB chunk: a name longer than 65,536 bytes would |
| 3759 | | -overrun it. That can't happen, since `MaxStr` is 65,536 and `MaxIdent` |
| 3760 | | -is 63, so the bound holds only by the coincidence of two constants. |
| 3761 | | -The safe form checks it. About 40 lines change; the scanner's buffer |
| 3762 | | -stays unsafe, as section 21 suggests. |
| 3763 | | - |
| 3764 | | -**Chunk's grown arrays: can be safe, and grow longer.** `text`, |
| 3765 | | -`rodata`, `chunks`, `fixups`, `dataFixups`, `lines` and `varNotes` |
| 3766 | | -become `Buf`s and `Vec`s. `put1` becomes `Buf.add(text, U8(b & 0FFH))`, |
| 3767 | | -which is clearer. But there are about 200 places in `Link`, `X64`, |
| 3768 | | -`Elf`, `Gen`, `Parse` and `Item` that read `Chunk.chunks[c].adr` or |
| 3769 | | -`Chunk.lines[i].at`, and each one becomes either |
| 3770 | | - |
| 3771 | | -``` |
| 3772 | | -Chunks.all(Chunk.chunks)[c].adr := a; (* a count raised and lowered, each time *) |
| 3773 | | -``` |
| 3774 | | - |
| 3775 | | -or a local held over the procedure, `cs := Chunks.all(Chunk.chunks)`. |
| 3776 | | -The obvious mending, `proc at*(c: INT): ^Chunk` in `Chunk`, can't be |
| 3777 | | -written, since it returns a lend of an owner that no parameter names |
| 3778 | | -(7.3). And a held `cs` across a `newChunk` that grows the array is a |
| 3779 | | -new trap. The writes through `cs` go into the retired block and are |
| 3780 | | -lost, with no message, even in the debugging heap, which poisons |
| 3781 | | -retired blocks for reads only (11). Today that is a use after free. |
| 3782 | | -Under the proposal it is a wrong executable, and the proposal calls it |
| 3783 | | -"lost, but harmless" (7.4). For a compiler it is not harmless. |
| 3784 | | - |
| 3785 | | -**Diag's files and messages.** `files: ^File` becomes `Vec(File)`, and |
| 3786 | | -`pathOf` needs `Vec.get` (R4). `say` keeps every message for good, in |
| 3787 | | -a `Buf` from `grab` that is never freed: |
| 3788 | | - |
| 3789 | | -``` |
| 3790 | | -(* Before *) |
| 3791 | | -b := ^Buf.Buf(grab(SIZE(Buf.Buf))); |
| 3792 | | -Buf.init(b^, Heap.heap); |
| 3793 | | -Fmt.write(b^, f, args); |
| 3794 | | -return Buf.bytes(b^); |
| 3795 | | - |
| 3796 | | -(* After, with Buf.leak (R5) *) |
| 3797 | | -var b: Buf.Buf; |
| 3798 | | -Buf.init(b, Heap.heap); |
| 3799 | | -Fmt.write(b, f, args); |
| 3800 | | -return Buf.leak(b); (* b gives its block up for good: it lasts *) |
| 3801 | | -``` |
| 3802 | | - |
| 3803 | | -Without `Buf.leak` the only safe form is a second copy, `Str.copy` of |
| 3804 | | -the bytes and then `Buf.done`, for every message. `Sym.typeName` is the |
| 3805 | | -same, and so are four `grab`-and-slice strings in `Parse`, `Item` and |
| 3806 | | -`Raz`. |
| 3807 | | - |
| 3808 | | -**Sym's scopes.** The hash table `hashTab: ^^Obj` becomes `Vec(^Obj)`, |
| 3809 | | -and `rehash` builds a new one and drops the old. `Obj`s and `Type`s |
| 3810 | | -come from `NEW` and are never freed, so the 1,015 dereferences stay as |
| 3811 | | -they are, as 8.1 says. Under the strict reading of 6.1, though, each |
| 3812 | | -procedure that stores a pointer it is given needs `keep`: `newObj`'s |
| 3813 | | -`typ`, `insert`'s `obj`, and the 17 procedures of `Item` and `Parse` |
| 3814 | | -that put a `^Sym.Type` or `^Sym.Obj` parameter into a `var x: Item`. |
| 3815 | | -That is about 40 headings across `src/`, and every argument is a |
| 3816 | | -pointer from `NEW` already (R3 removes them). `Parse`'s `curLoop := |
| 3817 | | -ADR(lp)` becomes a stack of loops in a module array, about 10 lines. |
| 3818 | | - |
| 3819 | | -**Count.** 14,285 lines. The fence's own list (section 2.2): about 60 |
| 3820 | | -sites. Parts B to F and what the mending entails: Scan 40, Chunk 60, |
| 3821 | | -the 200 accesses, Diag and the kept strings 30, Sym 20, `keep` marks |
| 3822 | | -40, loops 10. About 420 lines, 3%. |
| 3823 | | - |
| 3824 | | -**Judgement.** Scan's table and `Diag.say` come out clearer. `Chunk` |
| 3825 | | -and `Link` come out longer, and no clearer, unless R1 allows accessors. |
| 3826 | | -Speed: a call, a count and a bounds check where a pointer index stood, |
| 3827 | | -on the symbol lookup and code emission paths. That is not measured; an |
| 3828 | | -estimate is 1 to 3% of instructions, on top of the 4.5% of 13.1 if |
| 3829 | | -`Scan` goes safe as well. **Run-time stops in correct code:** |
| 3830 | | -`Parse.raz:3696`, `text := Buf.bytes(s)` and then `Buf.done(s)`, would |
| 3831 | | -stop at the first generic instance the compiler made, and so `make |
| 3832 | | -check` would stop in its first minute. **Real bugs caught:** none, |
| 3833 | | -beyond the bound in `intern` that holds by luck. |
| 3834 | | - |
| 3835 | | -### A7.5 The library (`Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files`) and `examples/Sh.raz` |
| 3836 | | - |
| 3837 | | -**`Fmt` can't be made safe as section 5.4 says.** `format` takes |
| 3838 | | -`b: ^Buf.Buf`, with `nil` for standard output, and `write` and |
| 3839 | | -`eprint` pass `ADR(b)`. Without `ADR`, the `nil` must become a flag, |
| 3840 | | -and `print` has no `Buf` to pass: |
| 3841 | | - |
| 3842 | | -``` |
| 3843 | | -(* After *) |
| 3844 | | -var none: Buf.Buf; (* never written: what print passes for b *) |
| 3845 | | - |
| 3846 | | -proc put(var b: Buf.Buf; out: BOOL; s: []U8); |
| 3847 | | -begin |
| 3848 | | - if out then Out.str(s); else Buf.str(b, s); end; |
| 3849 | | -end; |
| 3850 | | - |
| 3851 | | -proc print*(f: []U8; args: []Arg); |
| 3852 | | -begin |
| 3853 | | - format(none, true, f, args); |
| 3854 | | -end; |
| 3855 | | -``` |
| 3856 | | - |
| 3857 | | -This is a contortion: an owner kept only to stand in for "none". |
| 3858 | | -`eprint` builds its text in a `Buf` over an arena, so that a program |
| 3859 | | -that doesn't call it carries no heap. Under the proposal |
| 3860 | | -`Buf.init(b, Arena.allocator(ar))` is refused. `init` keeps its |
| 3861 | | -allocator, so its parameter is `keep`, and the arena's allocator is |
| 3862 | | -lent by the arena (8.4). So `eprint` moves to the heap and loses the |
| 3863 | | -reason its comment gives. No container can take memory from an arena |
| 3864 | | -in safe code. About 15 lines change. |
| 3865 | | - |
| 3866 | | -**`Opt` is safe, with one stop in correct code.** `left` and |
| 3867 | | -`leftWidth` take `const r: Row` for `ADR(p.table[i])`, six lines. |
| 3868 | | -`init` is `keep name, table`, and `scope` is `keep name`. `say` would |
| 3869 | | -stop: |
| 3870 | | - |
| 3871 | | -``` |
| 3872 | | -proc say(fd: INT; var b: Buf.Buf); |
| 3873 | | -var s: []U8; n: INT; |
| 3874 | | -begin |
| 3875 | | - s := Buf.bytes(b); |
| 3876 | | - while LEN(s) > 0 do |
| 3877 | | - n := Sys.write(fd, s); |
| 3878 | | - if n <= 0 then break; end; |
| 3879 | | - s := s[n..LEN(s)]; |
| 3880 | | - end; |
| 3881 | | - s := []; (* new: else the next line stops, though s is empty and never read again *) |
| 3882 | | - Buf.done(b); |
| 3883 | | -end; |
| 3884 | | -``` |
| 3885 | | - |
| 3886 | | -Every usage message and every `--help` of every program goes through |
| 3887 | | -`say`. |
| 3888 | | - |
| 3889 | | -**`Map` marks are easy, and its uses narrow.** `put(var m; keep k: K; |
| 3890 | | -keep v: V)` is one heading. `Map([]U8, V)` keys must now last, so a |
| 3891 | | -key made in a `Buf` is `Str.copy`'d and never freed, or goes in |
| 3892 | | -`Names(V)`. `Map(K, Buf.Buf)` can't be made at all: `put` takes `V` by |
| 3893 | | -value, and an owner can't be copied. A map of strings to buffers, an |
| 3894 | | -editor's "buffer by name", has no safe form but `Pool` handles. |
| 3895 | | - |
| 3896 | | -**The containers export what breaks them.** `Buf.len*`, `Vec.len*`, |
| 3897 | | -`List.head*` and `List.Node.next*` are fields a safe module can write. |
| 3898 | | -`b.len := 1 shl 40; Buf.bytes(b)` reads any memory, because `bytes` |
| 3899 | | -slices `b.data`, a pointer, unchecked. `l.head := other.head; |
| 3900 | | -List.clear(l)` frees another list's nodes. This is 5.3's rule 4, but |
| 3901 | | -section 17 doesn't list it. Hiding the fields changes every read of |
| 3902 | | -`b.len` in every program, dozens in rmacs alone, unless fields can be |
| 3903 | | -exported read-only (R6). `Files.load` writes `INC(b.len, n)` after |
| 3904 | | -`Buf.spare`, as `spare`'s own comment says to, so `Files` isn't safe |
| 3905 | | -either until `Buf` gets a checked `took(var b; n)`. `examples/Words` |
| 3906 | | -walks `order.head` and `n^.next`, three lines that become |
| 3907 | | -`Names.first` and `Names.next`. |
| 3908 | | - |
| 3909 | | -**`examples/Sh.raz`: its arena has no safe form.** `Sh` builds each |
| 3910 | | -word in a `Buf` over a module arena, keeps `Buf.bytes(b)` in the module |
| 3911 | | -variable `text` and in `Command.args`, and resets the arena for each |
| 3912 | | -script. Every one of those is refused: the `Buf` over the arena (keep, |
| 3913 | | -8.4), `text := Buf.bytes(b)` (7.3), `c^.args[c^.n] := text` through a |
| 3914 | | -pointer (6.2), `return Buf.bytes(b), true` in `find` (7.3), and `s := |
| 3915 | | -script` from `run(Buf.bytes(line))` (keep). Building `argv` from spans |
| 3916 | | -at `spawn` is refused too, since a local array of slices may not hold |
| 3917 | | -a lend (7.3). What compiles is a bump allocator written by hand over a |
| 3918 | | -module array, whose slices last: |
| 3919 | | - |
| 3920 | | -``` |
| 3921 | | -var |
| 3922 | | - pool: [1 shl 24]U8; (* the words of what is being run; a module's array lasts *) |
| 3923 | | - used: INT; |
| 3924 | | - |
| 3925 | | -proc add(c: U8); |
| 3926 | | -begin |
| 3927 | | - if used = LEN(pool) then say("out of room for words", []); Rt.exit(2); end; |
| 3928 | | - pool[used] := c; |
| 3929 | | - INC(used); |
| 3930 | | -end; |
| 3931 | | - |
| 3932 | | -(* in readWord, for Buf.init(b, ADR(arena.base)) ... text := Buf.bytes(b) *) |
| 3933 | | -start := used; |
| 3934 | | -... |
| 3935 | | -text := pool[start..used]; |
| 3936 | | -``` |
| 3937 | | - |
| 3938 | | -The rules let this pass, and that's right: `used := 0` makes old words |
| 3939 | | -show new bytes, which is a matter of logic, not memory. But it shows |
| 3940 | | -that the arena was refused for what it is, not for anything it does. |
| 3941 | | -`ADR(p^.cmds[i])` becomes an index, and `builtin` and `start` take |
| 3942 | | -`const`. The scanner's module state (`s`, `at`, `text`) goes into a |
| 3943 | | -`Scanner` record passed by `var`, so that `run` needn't keep its |
| 3944 | | -script. That is 45 of 387 lines, 12%. The scanner comes out clearer, |
| 3945 | | -and the allocator worse: an `Arena` was one line, and this is ten. |
| 3946 | | - |
| 3947 | | -### A7.6 rjson's `Json` (`src/Json.raz`, `test/Suite.raz`) |
| 3948 | | - |
| 3949 | | -`Doc` grows its nodes by hand with `Mem.alloc` and `Mem.free`, and |
| 3950 | | -copies strings into a list of chunks that `reset` frees. So `Json` |
| 3951 | | -says `unsafe;` and carries the owner protocol itself: a `LENDS` field, |
| 3952 | | -retiring chunks in `reset`, `ret` on `text`, `key` and `copy`. That is |
| 3953 | | -about 25 lines of trusted code outside the library, and the same holds |
| 3954 | | -for every program with a container of its own (`Text` in rmacs). The |
| 3955 | | -audit surface grows with each one. The zero-copy design ("the text |
| 3956 | | -must live as long as the document") means `parse` keeps its text. The |
| 3957 | | -suite's |
| 3958 | | - |
| 3959 | | -``` |
| 3960 | | -v := Json.parse(ADR(d), Buf.bytes(ADR(text))); (* twice *) |
| 3961 | | -``` |
| 3962 | | - |
| 3963 | | -is refused, since a `Buf`'s bytes don't last. Such a program either |
| 3964 | | -leaks each file's bytes with `Buf.leak`, which is fine for a test but |
| 3965 | | -not for a server parsing request bodies, or `Json` gets a `parseCopy` |
| 3966 | | -that copies the text into the document first: one copy per parse, |
| 3967 | | -small next to parsing. About 40 lines change, 4%. |
| 3968 | | - |
| 3969 | | -### A7.7 Holes the port found in the rules |
| 3970 | | - |
| 3971 | | -Each of these lets unsafe code through as the proposal is written, or |
| 3972 | | -leaves undecided whether correct code stops. |
| 3973 | | - |
| 3974 | | -- **H1. A store through a slice isn't a store that outlives.** 6.2 |
| 3975 | | - lists module variables, `p^.f` and `var` parameters. It doesn't list |
| 3976 | | - `s[i] := e` for a slice `s`. So `proc fill(names: [][]U8); var buf: |
| 3977 | | - [8]U8; begin names[0] := buf[0..8]; end;` puts a slice of the frame |
| 3978 | | - in the caller's array. `Vec.all(v)[i] := e` puts a lend in a |
| 3979 | | - container the same way. The rule must say that a store through a |
| 3980 | | - slice not lent by the frame alone is a store that outlives. |
| 3981 | | -- **H2. A `ret` through a record that holds owners loses the owner.** |
| 3982 | | - `name*(ret const m: Message; i: INT): []U8`, the accessor section |
| 3983 | | - 14.2 recommends, returns a lend of `m.head`. The caller knows only |
| 3984 | | - that the result is lent by `m`, which isn't an owner (7.2), so it |
| 3985 | | - doesn't know whose count to raise, and it raises none. Then |
| 3986 | | - `readRequest` grows `m.head`, frees the old block, and the held |
| 3987 | | - slice dangles. Either the accessor is refused, and 14.2's way out |
| 3988 | | - doesn't compile, or it is allowed, and the count is lost. R1 |
| 3989 | | - mends it. |
| 3990 | | -- **H3. The containers' exported fields** (A7.5): `Buf.len*`, |
| 3991 | | - `Vec.len*`, `List.head*`, `Node.next*`, and `Files.load`'s `INC(b.len, |
| 3992 | | - n)` by design. |
| 3993 | | -- **H4. A literal over a live owner.** `m := {minor: 1}` is allowed |
| 3994 | | - (7.6: a literal may leave an owner out). It drops the owner's block, |
| 3995 | | - which is a safe leak, and zeroes its allocator, so the owner's next |
| 3996 | | - growth stops. It is a trap that compiles, and the obvious rewrite of |
| 3997 | | - `Http.reset` falls into it. |
| 3998 | | -- **H5. The order of a hold's let-go and `defer`.** If holds are let go |
| 3999 | | - after the deferred statements, every `defer Buf.done(b)` over a |
| 4000 | | - local that holds `Buf.bytes(b)` stops the program. If before, a |
| 4001 | | - deferred statement that reads the local reads memory still allocated, |
| 4002 | | - which is fine. Section 7.3 must say "before". |
| 4003 | | -- **H6. Option 2 of 14.2 breaks rule 4 of 5.3** (A7.2). An unsafe |
| 4004 | | - `Http` with exported slice fields hands a safe module a slice it can |
| 4005 | | - read after `Http.done`. |
| 4006 | | - |
| 4007 | | -### A7.8 The verdict, in numbers |
| 4008 | | - |
| 4009 | | -| Code | Lines | The fence alone (`ADR` to own pointers, casts) | Parts B to F | Share | Result | |
| 4010 | | -|---|---|---|---|---|---| |
| 4011 | | -| rnet `Http`, `Conn`, tests, `Hello` | 2,700 | 330 | 230 | 9% | worse | |
| 4012 | | -| rmacs | 4,931 | 160 | 90 | 2% | the same | |
| 4013 | | -| raz `src/` | 14,285 | 60 sites | 420 | 3% | Scan, Diag clearer; Chunk, Link longer | |
| 4014 | | -| `lib/`: `Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files` | 1,500 | 15 | 70 | 5% | Fmt worse; the rest the same | |
| 4015 | | -| `examples/Sh.raz` | 387 | 10 | 45 | 12% | scanner clearer, allocator worse | |
| 4016 | | -| rjson `Json`, `Suite` | 1,050 | 15 | 40 | 4% | the same, with a copy per parse | |
| 4017 | | -| **All** | **24,850** | **about 590** | **about 895** | **4%** | | |
| 4018 | | - |
| 4019 | | -Where parts B to F's 895 lines come from, by rule: |
| 4020 | | - |
| 4021 | | -| Rule | Lines | Share | What it hits | |
| 4022 | | -|---|---|---|---| |
| 4023 | | -| 7.3: an owner's lend returned, or held in a record or array | 450 | 50% | `Message`, `Url`, `Core.slice`, `Mini.Names`, `Chunk`'s accessors, `Sh`'s words, `Json`, `Diag.say` | |
| 4024 | | -| 5.1 and 8.4: no safe form for a context pointer, or for a container over an arena | 200 | 22% | `Conn.state`, `Server.arg`, `Thread.spawn`, `Fmt.eprint`, `Sh`'s arena | |
| 4025 | | -| 6.1 and 6.2 read strictly: `keep` on a pointer parameter that is stored | 60 | 7% | `Sym`, `Item`, rmacs's `Core` | |
| 4026 | | -| 7.6: owners aren't copied | 30 | 3% | `Http.reset`, `open`'s `out := req^` | |
| 4027 | | -| 5.3 rule 4: the containers' fields hidden | 20, or every read of `.len` | 2% | rmacs, `Files` | |
| 4028 | | -| D: no `free` | 5, leaking | 1% | rmacs's buffers and windows | |
| 4029 | | -| the rest: `ret` marks, `t := []`, views | 130 | 15% | everywhere, a line at a time | |
| 4030 | | - |
| 4031 | | -**Stops at run time in correct code: 8**, found by a search for a |
| 4032 | | -local holding `Buf.bytes(b)` when `b` is done: `Opt.say`, |
| 4033 | | -`Parse.raz:3696`, `examples/Elf.raz`, rmacs's `Commands` (two), |
| 4034 | | -ravite's `Ravite.raz`, rnet's `Dns` (two). Five of them depend on H5. |
| 4035 | | -Each is found the first time its code runs, and each is mended with one |
| 4036 | | -line. But there is one in the compiler and one in the library, so |
| 4037 | | -`make check` would stop the day part C came in. |
| 4038 | | - |
| 4039 | | -**Real bugs caught: none** in about 25,000 lines. One bound holds by |
| 4040 | | -the coincidence of two constants (Scan). Every slice held across a |
| 4041 | | -change of its buffer was right, by an order the code keeps. So the |
| 4042 | | -rules make "right by discipline" checked. They guard tomorrow's code; |
| 4043 | | -they don't mend today's. The five programs of section 1.2 were written |
| 4044 | | -to show the holes. None of them was found in this code. |
| 4045 | | - |
| 4046 | | -**Is the pain narrow?** By lines, yes: 96% of the code is left alone, |
| 4047 | | -or changes only where `STANDARDS.md` already asks it to. By kind, no. |
| 4048 | | -Five of the six pieces need a redesign of the one type they are built |
| 4049 | | -round. Each such type keeps a slice of a buffer in a record, or hands |
| 4050 | | -one out from a procedure that isn't the buffer's own, and those are |
| 4051 | | -the pieces that do I/O or hold data. Code that only computes, `Parse`'s |
| 4052 | | -statements, `Item`, `Gen`, rflate's inflater, `Fmt`'s formatting, is |
| 4053 | | -left alone, as section 14.1 says. |
| 4054 | | - |
| 4055 | | -### A7.9 Beside Rust and beside today's raz |
| 4056 | | - |
| 4057 | | -**Beside today's raz.** Today the six pieces compile as they are, and |
| 4058 | | -their rules of lifetime are comments ("good until the buffer next |
| 4059 | | -grows", "the text must live as long as the document"). Under the |
| 4060 | | -proposal four of those comments become checks, and the code that |
| 4061 | | -leans on them grows by about 4%. It loses three things that were |
| 4062 | | -easy: a record of slices of someone else's buffer, an accessor that |
| 4063 | | -returns a slice of a buffer, and a container over an arena. |
| 4064 | | - |
| 4065 | | -**Beside Rust.** Where a record holds slices of its *own* buffer |
| 4066 | | -(`Message`, `Doc`), Rust can't do it either: a struct can't borrow |
| 4067 | | -from itself, so Rust programs use spans, as here, or a crate built for |
| 4068 | | -it. Where a record holds slices of *another's* buffer (`Url` of a |
| 4069 | | -`Buf`, `Sh`'s `argv`, a `Doc` over a file's bytes), Rust writes |
| 4070 | | -`Url<'a>` and is done; raz must copy, or use a frame array. Where a |
| 4071 | | -procedure returns a slice of an owner it reaches through a global or a |
| 4072 | | -pointer (`Core.slice`, `bufferNames`, `Chunk.at`), Rust writes |
| 4073 | | -`&'static` or a lifetime on the result; raz can't write it at all. |
| 4074 | | -Where a callback needs its context (`Server.arg`, `Conn.state`), Rust |
| 4075 | | -has closures and trait objects; raz has `^U8`, which is fenced. On |
| 4076 | | -the other hand, 96% of the code needs no mark at all, where a Rust |
| 4077 | | -port of `Sym`, `Item` and `Parse`'s trees, with their `^Obj` and |
| 4078 | | -`^Type` links everywhere, would need `Rc`, arenas with lifetimes or |
| 4079 | | -indexes throughout. And Rust would reject at compile time the eight |
| 4080 | | -`done`-while-held places, where this proposal stops at run time. In |
| 4081 | | -short, the proposal costs much less than Rust in the code that |
| 4082 | | -computes, more than Rust in the code that holds buffers, and it has |
| 4083 | | -nothing for type-erased context, where Rust has a great deal. |
| 4084 | | - |
| 4085 | | -### A7.10 Relaxations and additions |
| 4086 | | - |
| 4087 | | -Each of these removes pain found above. Each says what it would cost, |
| 4088 | | -and what, if anything, it weakens. |
| 4089 | | - |
| 4090 | | -- **R1. A lend carries its count.** An owner's lend returned from any |
| 4091 | | - procedure carries the address of its owner's count, in a hidden word, |
| 4092 | | - as a held local already does. Then the caller counts it on the right |
| 4093 | | - owner, whoever returned it. This allows `Core.slice`, `Mini.text`, |
| 4094 | | - `Dired.nameAt`, `Chunk.at`, `Http.target` and `Json.text`, mends H2, |
| 4095 | | - and removes about 250 of the 450 lines of 7.3. A procedure type |
| 4096 | | - must say that its result carries a count (`proc(i: I64): lent |
| 4097 | | - []U8`). It costs a register on return. It weakens nothing. |
| 4098 | | -- **R2. A local array or record may hold lends** (question 4 of section |
| 4099 | | - 21: yes), with one hold for each owner it holds lends of, all let go |
| 4100 | | - when the local is assigned whole or the procedure returns. This |
| 4101 | | - allows `Url` of a `Buf`, `Sh`'s `argv`, and a local `[]Fmt.Arg` of |
| 4102 | | - several `Buf`s, and removes about 60 lines. It costs a few words in |
| 4103 | | - the frame. It weakens nothing. |
| 4104 | | -- **R3. A pointer parameter lasts, as STANDARDS says it does** ("a |
| 4105 | | - pointer, only when it is kept"). An unmarked `^T` parameter may be |
| 4106 | | - stored. An owner's pointer (`Vec.add`, `Pool.at`) may not be passed |
| 4107 | | - as a `^T` argument, only dereferenced at the call, `f(p^)` to a `var`. |
| 4108 | | - This removes the 60 `keep` marks, and it puts the check on the rare |
| 4109 | | - case, the owner's pointer, not the common one. It weakens nothing. |
| 4110 | | -- **R4. `Vec.get(const v; i: INT): T` and `Vec.set(var v; i: INT; |
| 4111 | | - keep x: T)`.** A copy of an element holds what was kept, and that |
| 4112 | | - lasts. This mends `Scan.nameOf` and `Diag.pathOf`. Library only, |
| 4113 | | - and it weakens nothing. |
| 4114 | | -- **R5. `Buf.leak(var b: Buf.Buf): []U8` and `Vec.leak`.** The owner |
| 4115 | | - gives its block up for good and is left empty, and the block lasts, |
| 4116 | | - since no one holds what could free it. This is Rust's `Box::leak`. It |
| 4117 | | - mends `Diag.say`, `Sym.typeName`, `Parse`'s and `Item`'s kept |
| 4118 | | - strings, and a test's file. Library only, and it weakens nothing, |
| 4119 | | - but leak-freedom, which the guarantee doesn't promise (3). |
| 4120 | | -- **R6. Fields exported read-only**, Oberon-2's `len-: INT`, and |
| 4121 | | - `Buf.took(var b; n: INT)`, checked against the room `spare` made. This |
| 4122 | | - closes H3 and keeps every read of `b.len` as it is, while the seven |
| 4123 | | - writes in rmacs become `Buf.cut`. A language change of one mark. |
| 4124 | | - It weakens nothing, and without it the containers aren't safe. |
| 4125 | | -- **R7. `done` with a lend held is caught when compiling where it |
| 4126 | | - can be, and otherwise retires.** In one pass, the compiler knows when |
| 4127 | | - a local was last assigned a lend of `b` and has not been assigned |
| 4128 | | - since, so at `Buf.done(b)` it can say "`s` still holds a lend of `b`: |
| 4129 | | - write `s := []` first". That turns six of the eight stops into |
| 4130 | | - messages. The two through a pointer stay. For those, `done` retires |
| 4131 | | - the block instead of stopping: question 3 of section 21, answered |
| 4132 | | - "leak". With H5 settled as "before", the eight become none. It weakens |
| 4133 | | - leak-freedom, not safety, and the debugging heap can report each |
| 4134 | | - leak. |
| 4135 | | -- **R8. A checked context pointer.** A type `^ANY`, which any pointer |
| 4136 | | - from `NEW` converts to, and a conversion back, `^T(p)`, checked |
| 4137 | | - against a type word that `NEW` writes before the record. A wrong |
| 4138 | | - type stops the program, as Oberon's type guard does. This mends |
| 4139 | | - `Conn.state`, `Http.Server.arg`, `Thread.spawn`'s `arg` and the |
| 4140 | | - tests' casts, about 150 lines, and lets a server keep its state |
| 4141 | | - without module variables shared across threads. It costs a word per |
| 4142 | | - record that is ever made `^ANY`, if `NEW` is told so, and a compare |
| 4143 | | - per conversion. It weakens nothing. |
| 4144 | | -- **R9. Growth with a *writable* lend held stops; with a lend that |
| 4145 | | - only reads, it retires.** `Vec.add` and `Buf.spare` lend for |
| 4146 | | - writing, and `bytes` and `all` lend for reading. A write into a |
| 4147 | | - retired block is lost with no message (A7.4); a stop says where. |
| 4148 | | - `Buf.str(b, Buf.bytes(b))` still runs. This is a tightening, not a |
| 4149 | | - relaxation. It costs a second count per owner, and `all` must split |
| 4150 | | - in two, since today it lends for both. |
| 4151 | | - |
| 4152 | | -Some pain has no relaxation that keeps the guarantee: |
| 4153 | | - |
| 4154 | | -- **A container over an arena** (`Fmt.eprint`, `Sh`). Making it safe |
| 4155 | | - needs the container to hold the arena's count for as long as it |
| 4156 | | - lives: an owner holding a lend, which is a lifetime in a record, |
| 4157 | | - Rust's apparatus. A module array with an index does it safely, as |
| 4158 | | - `Sh`'s rewrite shows, at a fixed size. Otherwise such code stays |
| 4159 | | - unsafe. |
| 4160 | | -- **A record that keeps slices of its own buffer** (`Message`, `Doc`) |
| 4161 | | - stays spans and accessors, in raz as in Rust. With R1 the accessors |
| 4162 | | - compile, and that is all the help there is. |
| 4163 | | -- **Freeing records one by one.** `Pool`, or leaking. For an editor |
| 4164 | | - leaking is the plain choice, and it is safe. `Pool` needs an `alloc` |
| 4165 | | - that hands out a zeroed slot, for records that hold owners. |
| 4166 | | - |
| 4167 | | -With R1 to R8, the port's 895 lines fall to about 400, under 2%. The |
| 4168 | | -contortions left are `Fmt`'s stand-in and `Sh`'s allocator, and no |
| 4169 | | -correct code stops at run time. The holes H1 to H6 are mended by |
| 4170 | | -R1, R6 and two sentences in 6.2 and 7.3. |